We are using below java code to decrypt the data which is encrypted using AES-256 in CBC mode and PKCS7 padding.
Java Code:
import javax.crypto.spec.SecretKeySpec;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import java.security.*;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
public class AES256 {
private static byte[] initVector = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
public String decrypt (String encryptedDataBase64, String keyBase64)
{
try {
Security.setProperty("crypto.policy", "unlimited");
IvParameterSpec ivSpec = new IvParameterSpec(initVector); // Get the init vector
// Get the Base64-encoded key
byte[] key = Base64.decodeBase64(keyBase64.getBytes("UTF-8"));
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING"); // AES / CBC / PKCS5 padding
SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec, ivSpec);
byte[] encryptedData = Base64.decodeBase64(encryptedDataBase64.getBytes("UTF-8"));
byte[] decryptedData = cipher.doFinal(encryptedData);
return new String(decryptedData);
}
catch (Exception e) {
logger.error("AES256 Decrypt: Decryption exception: "+ e.getMessage());
return null;
}
}
}
Now we need to convert this decryption logic to Javascript as our app is sending the encrypted data in the headers while requesting for index.html from server. I tried to decrypt using Crypto.js but I am getting decoded string as empty. Below is the Javascript code I was trying to use.
var key = CryptoJS.enc.Base64.parse(keyBase64);
var data = CryptoJS.enc.Base64.parse(encryptedDataBase64);
var dec_data = CryptoJS.AES.decrypt(data, key);
dec_data is coming as empty.
I tried this after reading some of stack over flow questions. Can any one please let me know if there is any error in the code.