阅读加密的PKCS8 SpongyCastle Java

时间:2014-03-19 21:05:37

标签: java rsa pem spongycastle pkcs#8

我正在关注https://stackoverflow.com/a/18161536/1753951中的代码,但我在以下行中收到了异常:

FileInputStream fis = new FileInputStream(priv);
DataInputStream dis = new DataInputStream(fis);
byte[] keyBytes = new byte[(int)priv.length()];
dis.readFully(keyBytes);
dis.close();
javax.crypto.EncryptedPrivateKeyInfo encryptPKInfo = new EncryptedPrivateKeyInfo(keyBytes);
//Exception: 
org.apache.harmony.security.asn1.ASN1Exception: Wrong content length

我正在尝试读取.key / .pem PKCS8文件:

-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK Info: AES-256-CBC,8AFF348907C84F2F6370A216DC0D55D9

1VIjJD3dZ5/wYnIm0mtp8d22RC24yGcY9LXgeHUDbyPJQa8PjupubFqKrpOodvQx
dPfE1F3XeY8oVG42ZfR4287X4V16n++BQCeDiuvyrwacLMAuQz6PFLT4b/Py89Cm
761UZpaWnH0PHfJqB9CHqC+pGAGfRF5vj7UtdNchCwBmo+7gvU5iGyYXNRJ/hPnU
V+8QDzro4kFIMOlDzHaJ3KN1Ftbb9LDjDNE/NShbRrAFAWJMZSY/ZjF8mfqggkoZ
            %%%%%  SKIPPED MOST OF IT %%%%%%%%%%
BMIl0y5XVgPwkApA30EdgV4YAZEJ+wQLnYIZfCklqzvCfyjxHFViVW6d41WNm8bx
wl28v4QJKlnf7KNcmmGwSmjKo7BEASSZ+XVYRu0R6FaE+Job5YzPrtUI+p/kf7et
Y+jUDbZ4BPvB8j2ZscNRs+pJkEXxPt5JKW/oQMQZPlbTtSV5K1IqiuVcRi9TbCzk
nWDSfI/wxt6cK3X9XvyOpOZDCDPchkIhDhCzfitd7fzkM1VBekwsliJwjgc1bwbc
nI4AhQcNb8li7oX1M2osyeR3zF25BDb2A04Zm1lMrWkFrypb24DKkSJxYEH33Gpu
-----END RSA PRIVATE KEY-----

2 个答案:

答案 0 :(得分:1)

经过长时间寻找解决方案后,我偶然发现了一个帮助我并在android上工作的库。 还未用CC

http://juliusdavies.ca/commons-ssl/

FileInputStream in = new FileInputStream( "/path/to/pkcs8_private_key.der" );

PKCS8Key pkcs8 = new PKCS8Key( in, "changeit".toCharArray() );

byte[] decrypted = pkcs8.getDecryptedBytes();
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec( decrypted );

// A Java PrivateKey object is born.
PrivateKey pk = null;
if ( pkcs8.isDSA() )
{
   pk = KeyFactory.getInstance( "DSA" ).generatePrivate( spec );
}
else if ( pkcs8.isRSA() )
{
   pk = KeyFactory.getInstance( "RSA" ).generatePrivate( spec );
}
// For lazier types (like me):
pk = pkcs8.getPrivateKey();

答案 1 :(得分:0)

javax.crypto.EncryptedPrivateKeyInfo需要DER编码输入,而文件内容显然是PEM编码。

PEM和DER之间的关系是:

  • DER是实际的ASN.1编码数据,作为字节序列。
  • PEM是基于文本的,其中包含所有这些-----BEGIN SOMETHING----------END SOMETHING-----标头以及Base64编码的数据。基本上,PEM是标题+ Base64(DER)+页脚。

您需要将密钥转换为DER格式,例如使用the OpenSSL pkey command

openssl pkey -in key.pem -outform DER -out key.der