Skip to content
Advertisement

RSA Encryption disparity between Android and Java environments

Firstly, apologies for the amount of code I’m about to post. I’m trying to use the RSA public key from my Java application to encrypt a message in an Android app, and then send the ciphertext back to a Java environment for decryption, but upon attempting to decrypt I always get this error:

JavaScript

The ciphertext does contain the correct number of bytes (512), so it’s confusing to see a “bad padding” exception. Other similar posts on SO have suggested using “RSA/ECB/PKCS1Padding” as the algorithm, but this does not work.

Annoyingly, encryption and decryption in the Android environment (using Base64.URL_SAFE as the ‘base64Type’) works just fine, I just can’t seem to get the initial encryption working with the public key produced via Java.

I have extracted the bare minimum code into examples, as shown below:

Android Code

JavaScript

Java Code

JavaScript

I’m aware that the problem has to be to do with difference in the way Android and Java interpret the RSA algorithm, and/or differences with the Base64 encode/decode, but I’m stumped. Any assistance greatly appreciated.

Advertisement

Answer

Solved it! The issue was that I was using the same ALGORITHM String for Cipher, KeyFactory etc. I split this into two different Strings, and the full solution for my problem is…

Android Code

JavaScript

Java Code

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement