2015-02-10 98 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) 

的代码工作正常。

回答