OpenSSL生成公钥私钥
用 OpenSSL, Linux 上自带,常用命令如下(生成密钥位数:512bit):
-----1.生成 RSA 私钥,输出私钥文件到rsa_private_key.pem-----------
openssl genrsa -out rsa_private_key.pem 512
-----2.用以下命令在同级目录下生成pkcs8格式的新私钥: pkcs8.pem(JAVA需要使用的私钥需要经过PKCS#8编码)
openssl pkcs8 -topk8 -inform PEM -in rsa_private_key.pem -outform pem -nocrypt -out pkcs8.pem
##### 可选:如果需要把pkcs8转成pkcs1可以用以下命令:
openssl pkcs8 -in pkcs8.pem -nocrypt -out pri_key.pem
-----3.生成 RSA 公钥,输出私钥文件到rsa_public_key.pem-------------
openssl rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem
注:
在进行RSA加密的时候,报异常:algid parse error, not a sequence。具体错误信息如下:
Exception in thread "main" java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: IOException : algid parse error, not a sequence
at sun.security.rsa.RSAKeyFactory.engineGeneratePrivate(RSAKeyFactory.java:217)
at java.security.KeyFactory.generatePrivate(KeyFactory.java:372)
at com.hashland.otc.common.util.coder.RSACoder.sign(RSACoder.java:42)
at com.hashland.otc.common.util.coder.RSACoder.main(RSACoder.java:306)
Caused by: java.security.InvalidKeyException: IOException : algid parse error, not a sequence
at sun.security.pkcs.PKCS8Key.decode(PKCS8Key.java:352)
at sun.security.pkcs.PKCS8Key.decode(PKCS8Key.java:357)
at sun.security.rsa.RSAPrivateCrtKeyImpl.<init>(RSAPrivateCrtKeyImpl.java:91)
at sun.security.rsa.RSAPrivateCrtKeyImpl.newKey(RSAPrivateCrtKeyImpl.java:75)
at sun.security.rsa.RSAKeyFactory.generatePrivate(RSAKeyFactory.java:316)
at sun.security.rsa.RSAKeyFactory.engineGeneratePrivate(RSAKeyFactory.java:213)
... 3 more
原因分析:
是因为密钥的格式不正确,密钥非 pkcs8 格式,需私钥改成pkcs8 格式及执行上面的第2步获得新的私钥即可