生成秘钥对
生成RSA私钥,以X509编码,指定生成的密钥的位数为2048位,该步生成的私钥只是临时文件,以便第二步将私钥转为PKCS#8编码。
1  | openssl genrsa -out rsa_private_key_2048.pem 2048  | 
将上一步生成的RSA私钥转换成PKCS#8编码,作为最终使用的私钥。
1  | openssl pkcs8 -topk8 -in rsa_private_key_2048.pem -out pkcs8_rsa_private_key_2048.pem -nocrypt  | 
导出RSA公钥,以X509编码,作为最终交换的公钥。
1  | openssl rsa -in rsa_private_key_2048.pem -out rsa_public_key_2048.pem -pubout  | 
注:一般Linux系统都装有openssl工具,在windows下可以安装OpenSSL工具包。
用法
加密工具
CryptoUtil.java:
1  | import org.apache.commons.codec.binary.Base64;  | 
签名
1  | byte[] signBytes = CryptoUtil.digitalSign(xml.getBytes("UTF-8"), privateKey, "SHA1WithRSA");  | 
加密
1  | byte[] encryptedBytes = CryptoUtil.encrypt(xmlBytes, publicKey, 2048, 11, "RSA/ECB/PKCS1Padding");  | 
解密
1  | byte[] xmlBytes = CryptoUtil.decrypt(encryptedBytes, privateKey, 2048, 11, "RSA/ECB/PKCS1Padding");  | 
验签
1  | boolean isValid = CryptoUtil.verifyDigitalSign(xmlBytes, signBytes, publicKey, "SHA1WithRSA");  | 
加载私钥
1  | /**  | 
加载公钥
1  | /**  |