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步獲得新的私鑰即可