user1454308
user1454308

Reputation: 33

Java AES decryption

I am encrypting some data and then sending it over the network and finally decrypting that data on an Android device using the class below. The encryption happens on the java server and then the decryption happens on the phone. I am getting this error though when I decrypt the data on the phone, “javax.crypto.BadPaddingException: pad block corrupted”. I don't get this error when I run my unit tests on the computer. Any thoughts as to why this is happening?

import java.security.*;
import javax.crypto.Cipher; 
import javax.crypto.spec.SecretKeySpec;
import sun.misc.*;

public class Encryption {
private static final String ALGORITHM = "AES";
private static final byte[] keyValue = 
    new byte[] { '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G' };

public static String encrypt(String valueToEnc) throws Exception {
    Key key = generateKey();
    Cipher c = Cipher.getInstance(ALGORITHM);
    c.init(Cipher.ENCRYPT_MODE, key);
    byte[] encValue = c.doFinal(valueToEnc.getBytes());
    String encryptedValue = new BASE64Encoder().encode(encValue);
    return encryptedValue;
}

private static Key generateKey() throws Exception {
    Key key = new SecretKeySpec(keyValue, ALGORITHM);
    return key;
}

private static String decrypt(String encryptedValue) throws Exception {
    Key key = generateKey();
    Cipher c = Cipher.getInstance(ALGORITHM);
    c.init(Cipher.DECRYPT_MODE, key);
    byte[] decordedValue = new BASE64Decoder().decodeBuffer(encryptedValue);
    byte[] decValue = c.doFinal(decordedValue);
    String decryptedValue = new String(decValue);
    return decryptedValue;
}
}

Upvotes: 0

Views: 1514

Answers (1)

Jeremy Brooks
Jeremy Brooks

Reputation: 589

My guess is that the two platforms are using different default values for the mode and/or padding. If you specify just the cipher, the underlying implementation will select a mode and padding for you.

Try specifying the exact cipher/mode/padding you want on both ends:

Cipher.getInstance("AES/ECB/PKCS5Padding");

This is just an example. Use the mode and padding that you want.

Upvotes: 1

Related Questions