在不同服务器或系统之间进行交互时我们往往需要进行身份的认证,以满足安全上的防抵赖和防篡改。
要实现以上要求使用非对称加密算法是目前最理想的方案。
以下是具体的实现:
1. 生成RSA算法私钥和公钥对,用openssl(openssl的安装网上有很多资料,可以自行查看)
生成RSA私钥
openssl>genrsa -out rsa_private_key.pem 1024
生成RSA公钥
openssl>rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem
将RSA私钥转换成PKCS8格式
openssl>pkcs8 -topk8 -inform PEM -in rsa_private_key.pem -outform PEM -nocrypt
2. 私钥由请求方系统妥善保管,不能泄漏;公钥交由系统的响应方用于验证签名
3. 请求方使用私钥对发送的请求进行签名,具体的实现方法如下(JAVA)
import java.security.KeyFactory; import java.security.PrivateKey; import java.security.PublicKey; import java.security.Signature; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import org.apache.commons.codec.binary.Base64; public String sign(String data, String privateKey) { String result = ""; byte[] keyBytes = Base64.decodeBase64(privateKey); PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes); try{ KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); PrivateKey priKey = keyFactory.generatePrivate(pkcs8KeySpec); Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM); signature.initSign(priKey); signature.update(data.getBytes()); result = (new Base64()).encodeAsString(signature.sign()); }catch(Exception ex){ throw new ServiceException(ex); } return result; }
4. 响应方的系统对请求数据验证签名
public boolean verify(String data, String publicKey, String sign) { boolean result; byte[] keyBytes = Base64.decodeBase64(publicKey); X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory; try { keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); PublicKey pubKey = keyFactory.generatePublic(keySpec); Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM); signature.initVerify(pubKey); signature.update(data.getBytes()); result = signature.verify((new Base64()).decode(sign)); } catch (Exception ex) { throw new RuntimeException(ex); } return result; }
时间: 2024-10-11 05:52:18