Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error restoring RSA private key on Android Jelly Bean

I use encription in my app. I store private key as bytes array and use the following code to restore it:

PrivateKey private = KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(s_privateKeyIn1t));

It works perfectly on all my target android platforms 2.1 -> 4.0.4, but fails on Jelly Bean!

Jelly Bean throws an exception:

07-20 17:29:35.197: E/AnyBalance:Codec(990): Caused by: java.lang.RuntimeException: error:0D0680A8:asn1 encoding routines:ASN1_CHECK_TLEN:wrong tag
07-20 17:29:35.197: E/AnyBalance:Codec(990):    at org.apache.harmony.xnet.provider.jsse.NativeCrypto.d2i_PKCS8_PRIV_KEY_INFO(Native Method)
07-20 17:29:35.197: E/AnyBalance:Codec(990):    at org.apache.harmony.xnet.provider.jsse.OpenSSLRSAKeyFactory.engineGeneratePrivate(OpenSSLRSAKeyFactory.java:73)

What is wrong?

like image 609
Dmitry Kochin Avatar asked Nov 29 '22 02:11

Dmitry Kochin


2 Answers

This is the code that worked for me (the second line is the important part):

PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(s_privateKeyIn1t);
KeyFactory keyFactory = KeyFactory.getInstance("RSA", "BC");
PrivateKey privateKey = keyFactory.generatePrivate(privSpec);
like image 165
user681443 Avatar answered Dec 09 '22 11:12

user681443


Well I don't know the reason why it has happened but I've figured out how to deal with it. I have just reencoded the key on previous android version and this reencoded key worked on Jelly Bean.

I used the following code to reencode the key:

Private key = KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(s_privateKeyIn1t));
byte [] xxx = s_privateKey.getEncoded(); //Then I watched this byte array in debugger and inserted it in a source code.
//Now it works on Jelly Bean
like image 30
Dmitry Kochin Avatar answered Dec 09 '22 11:12

Dmitry Kochin