Search code examples
javaandroidencryptionaescryptojs

Follow same encryption in android as developed in CryptoJS


I would like to encrypt this javascript code in android.

let base64Key = CryptoJS.enc.Base64.parse(key);

let encryptedValue = CryptoJS.AES.encrypt(value, base64Key, {
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7,
iv: base64Key
});
return encryptedValue.toString();

Code:

String encryptedKey = Base64.encodeToString(keyword.getBytes(), Base64.NO_WRAP);
Key key = new SecretKeySpec(encryptedKey.getBytes(), algorithm);
Cipher chiper = Cipher.getInstance("AES");
chiper.init(Cipher.ENCRYPT_MODE, key);
byte[] encVal = chiper.doFinal(plainText.getBytes());
String encryptedValue = Base64.encodeToString(encVal, Base64.NO_WRAP);
return encryptedValue;

But it returns a completely different value.

The first line of the code itself returns a different value in both cases:

So I got this part working. I just needed to add the following lines to the android code:

byte[] decoded = Base64.decode(key.getBytes());
        String hexString = Hex.encodeHexString(decoded);

This is the equivalent of CryptoJS.enc.Base64.parse(key); this line in CryptoJS.

But still trying to figure out the end result though. Both are different.


Solution

  • Finally got it working in Android using the below code, if anyone else faces the issue:

    public static String encrypt(String key, String value) {
        try {
            SecretKey secretKey = new SecretKeySpec(Base64.decode(key.getBytes(), Base64.NO_WRAP), "AES");
            AlgorithmParameterSpec iv = new IvParameterSpec(Base64.decode(key.getBytes(), Base64.NO_WRAP));
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
    
            return new String(Base64.encode(cipher.doFinal(value.getBytes("UTF-8")), Base64.NO_WRAP));
    
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }