javax.crypto.BadPaddingException : Decryption error
Android using different padding algorithm. You need to use other algorithm like below:
Cipher CheckCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
There are quit number of posts out there.
You can refer
RSA BadPaddingException in Java - encrypt in Android decrypt in JRE
RSA Encryption: Difference between Java and Android
Vaibhav Agarwal
Updated on June 04, 2022Comments
-
Vaibhav Agarwal almost 2 years
I am trying to implement an RSA based encryption communication between my client and server. For this I generated RSA public and private keys using openssl in the following way :
openssl genrsa -out private.pem 2048 openssl rsa -in private.pem -outform PEM -pubout -out public.pem --generate modulus and exponent openssl rsa -pubin -in public_key.pem -modulus -noout openssl rsa -pubin -in public_key.pem -text -noout
Using the above files, encryption is done on the Android side as follows :
public static byte[] encrypt(BigInteger modulus, BigInteger exp, byte[] data) { try { KeyFactory kf = KeyFactory.getInstance("RSA"); RSAPublicKeySpec keySpec = new RSAPublicKeySpec(modulus, exp); PublicKey publicKey = kf.generatePublic(keySpec); final Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.ENCRYPT_MODE, publicKey); return cipher.doFinal(data); } catch (Exception e) { FileLog.e("module" , e); } return null; }
This works fine and does encrypt the data. Now on the server side, I used the following code to decrypt. The private key is stored as a pkcs8 format key and that is read by java.
public static byte[] decrypt(byte[] data) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException{ String fileName = "location/of/private_key/file"; File f = new File(fileName); FileInputStream fis = new FileInputStream(f); DataInputStream dis = new DataInputStream(fis); byte[] keyBytes = new byte[(int)f.length()]; dis.readFully(keyBytes); dis.close(); PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes); KeyFactory kf = KeyFactory.getInstance("RSA"); PrivateKey rsaPrivate = kf.generatePrivate(spec); Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.DECRYPT_MODE, rsaPrivate); return cipher.doFinal(data); }
On running this using eclipse on the server, I get the BadPaddingException: Decryption error problem. The length of the data is exactly 256 bytes and hence the length should not be an issue.
Any help would be truly helpful.
Thanks