Question

I am following the code in: https://stackoverflow.com/a/18161536/1753951 but I am getting an Exception in the following line:

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

I am trying to read a .key/.pem PKCS8 file which is:

-----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-----
Was it helpful?

Solution

After looking long time for a solution I stumbled with a library that helps me and works on 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();

OTHER TIPS

javax.crypto.EncryptedPrivateKeyInfo expects a DER-encoded input, while the contents of your file are obviously in the PEM encoding.

The relation between PEM and DER is this:

  • The DER is the actual ASN.1-encoded data as a sequence of bytes.
  • The PEM is text-based with all these -----BEGIN SOMETHING----- and -----END SOMETHING----- headers and Base64-encoded data inside. Basically, PEM is header+Base64(DER)+footer.

You need to convert your key into DER format, for example using the OpenSSL pkey command:

openssl pkey -in key.pem -outform DER -out key.der
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top