-
文本格式秘钥
生成私钥
openssl genrsa -out rsa_private.key 1024公钥(pkcs1)
openssl rsa -in rsa_private.key -pubout -out rsa_public.key私钥转换成pkcs8 格式,输出到pkcs8.pem文件中
openssl pkcs8 -topk8 -inform PEM -in rsa_private.key -outform pem -nocrypt -out pkcs8.pem
注意:上面生成是的文本格式的秘钥,本身就是经过base64编码的,在使用过程中,只需要去掉开头和结尾的格式"---- xxxx ----"
// 加载公钥
byte[] pubBytes = IOUtils.toByteArray(new FileInputStream(new File("D:\\Desktop\\test\\test5\\rsa_public.key")));
PublicKey publicKey = getPublicKeyFromText(getKey(new String(pubBytes)), null, null);
// 加载私钥
// 私钥不要带密码
byte[] priBytes = IOUtils.toByteArray(new FileInputStream(new File("D:\\Desktop\\test\\test5\\pkcs8_1.pem")));
PrivateKey privateKey = getPrivateKeyFromText(getKey(new String(priBytes)), null, null);
/**
* 获取私钥
*
* @param privateKeyText 私钥
* @param algorithm 算法
* @param provider 提供商
* @return 私钥对象
*/
private static PrivateKey getPrivateKeyFromText(String privateKeyText, String algorithm, String provider) throws Exception {
return getKeyFactory(algorithm, provider).generatePrivate(
new PKCS8EncodedKeySpec(
Base64.decodeBase64(privateKeyText)));
}
/**
* 获取公钥
*
* @param publicKeyText 公钥
* @param algorithm 算法
* @param provider 提供商
* @return 公钥对象
*/
private static PublicKey getPublicKeyFromText(String publicKeyText, String algorithm, String provider) throws Exception {
return getKeyFactory(algorithm, provider).generatePublic(
new X509EncodedKeySpec(
Base64.decodeBase64(publicKeyText)));
}
/**
* 生成KeyFactory
*
* @param algorithm 算法
* @param provider 提供商
* @return KeyFactory
*/
private static KeyFactory getKeyFactory(String algorithm, String provider) throws Exception {
if (null == algorithm) {
algorithm = "RSA";
}
if (null == provider) {
return KeyFactory.getInstance(algorithm);
} else {
return KeyFactory.getInstance(algorithm, provider);
}
}
// 格式化
public static String getKey(String content) throws Exception {
return content.replaceAll("\\-{5}[\\w\\s]+\\-{5}", "");
}
- PFX格式
X509(PEM格式的)转PFX格式:
openssl pkcs12 -export -inkey test.key -in test.cer -out test.pfx
注:test.key和test.cert都是PEM格式的私钥和公钥证书
PFX转X509:
openssl pkcs12 -in test.pfx -nodes -out test.pem
openssl rsa -in test.pem -out test.key
openssl x509 -in test.pem -out test.crt
- cer、pfx秘钥对生成
统一keystory和私钥密码
openssl genrsa -out rsa_private002.key 1024
openssl req -new -x509 -key rsa_private002.key -days 3650 -out public_test002.cert
openssl pkcs12 -export -inkey rsa_private002.key -in public_test001.cert -out test002.pfx
参考链接:https://www.cnblogs.com/xq1314/p/8080598.html
cer生成: https://blog.csdn.net/u012191627/article/details/80990066
cer生成:https://blog.csdn.net/Solyutian/article/details/84033765
https://www.cnblogs.com/pixy/p/4722381.html