2015-02-10 96 views
0

嘗試讀取SSLeay格式私鑰時拋出InvalidKeyException。閱讀SSLeay使用充氣城堡格式私鑰

請看以下細節: - 我有一個SSLeay的格式私人key.The PEM格式始於以下文件

----- BEGIN RSA私鑰-----

我正在編寫代碼來獲取以字節格式保存的私鑰並將其轉換爲PrivateKey。 可變privateKeyBytes包含字節格式/私鑰

String pkStrFormat = new String(privateKeyBytes, "UTF-8"); 
pkStrFormat = pkStrFormat.replaceAll("(-----BEGIN RSA PRIVATE KEY-----\\r?\\n|-----END RSA PRIVATE KEY-----+\\r?\\n?)",""); 
byte[] keyBytesOfPrivateKey = org.bouncycastle.util.encoders.Base64 
        .decode(pkStrFormat.getBytes()); 
KeyFactory ecKeyFac = KeyFactory.getInstance("RSA"); 
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytesOfPrivateKey);    
PrivateKey priKey = ecKeyFac.generatePrivate(keySpec); 

我收到以下異常: - 當使用PKCS8格式鍵

Caused by: java.security.InvalidKeyException: IOException : version mismatch: (supported:  00, parsed:  01 
    at sun.security.pkcs.PKCS8Key.decode(PKCS8Key.java:350) 
    at sun.security.pkcs.PKCS8Key.decode(PKCS8Key.java:356) 

的代碼工作正常。

回答