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 Python as our app is sending the encrypted data in the headers while requesting for index.html from server. I tried to decrypt using Crypto. It is giving the decrypted string but also some additional characters in the end.
import base64
from Crypto.Cipher import AES
key = base64.b64decode(myKeyBase64)
enc = base64.b64decode(encDataBase64)
ivBase = base64.b64decode('AAAAAAAAAAAAAAAAAAAAAA==');
cipher = AES.new(key, AES.MODE_CBC, ivBase)
cipher.decrypt(enc).decode('utf-8')
It is decrypting properly but in the end it is giving some extra characters which are not in the original string like 'myText\x06\x06\x06\x06\x06\x06'.
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.