读取加密PKCS8海绵城堡Java



我在下面的代码: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/。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-----

在寻找了很长时间的解决方案后,我偶然发现了一个可以帮助我并在android上工作的库。Not-Yet-Commons

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();

javax.crypto.EncryptedPrivateKeyInfo期望一个der编码的输入,而您的文件的内容显然是PEM编码。

PEM和DER之间的关系如下:

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

您需要将密钥转换为DER格式,例如使用OpenSSL pkey命令:

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

相关内容

  • 没有找到相关文章

最新更新