Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RSA decrypt on android lollipop

I have an error with decryption with RSA. The code works on android 4.4 kit kat, but the same app doesn't work on android 5.0 lollipop.

KeyFactory keyFactory = KeyFactory.getInstance("RSA");
RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(new BigInteger(modulusBytes), new BigInteger(exponentBytes));
RSAPublicKey publicKey = (RSAPublicKey) keyFactory.generatePublic(pubKeySpec);

byte[] decrypted = null;
try {
    // get an RSA cipher object and print the provider
    final Cipher cipher = Cipher.getInstance("RSA/None/NoPadding");

    // decrypt the text using the public key
    cipher.init(Cipher.DECRYPT_MODE, publicKey);
    decrypted = cipher.doFinal(area_fissa_byte);

} catch (Exception ex) {
    ex.printStackTrace();
    Log.d("error","error");
}

The error is: java.security.SignatureException: error:04067084:rsa routines:RSA_EAY_PUBLIC_DECRYPT:data too large for modulus.

My sdk target is:

<uses-sdk android:minSdkVersion="14" android:targetSdkVersion="19" /> for android 4.4

Do you know what is the problem?

EDIT: i notice that i have 2 different public keys with different lengths!!! Android 5: i have 382/383 bit (too small) Android 4.4: i have 384 bit (ok)

EDIT2: i found that there are differences with android 5.0 for TLS/SSL: https://developer.android.com/about/versions/android-5.0-changes.html But i don't know how to fix the problem.

like image 386
invisibleProgrammer Avatar asked May 25 '15 15:05

invisibleProgrammer


1 Answers

One bug is how you created the RSAPublicKeySpec:

new RSAPublicKeySpec(new BigInteger(modulusBytes), new BigInteger(exponentBytes));

In case the first bit of the modulusBytes or exponentBytes is one the number will be interpreted as negative value.

When you work with RSA numbers and BigInteger always use the constructor BigInteger (int signum, byte[] magnitude) with signum=1 for specifying that the number is positive:

new RSAPublicKeySpec(new BigInteger(1, modulusBytes), new BigInteger(1, exponentBytes));

like image 98
Robert Avatar answered Oct 02 '22 01:10

Robert