I am trying to re-create a code snippet from JS to Java, but the outputs are different. What am I doing wrong? This is the code snippet from JS:
var randomKey = 2116781760886580;
var key = CryptoJS.enc.Utf8.parse(randomKey);
var iv = CryptoJS.enc.Utf8.parse(randomKey);
var encrypt = CryptoJS.AES
.encrypt(CryptoJS.enc.Utf8.parse("Text to encrypt"), key,
{
keySize: 128 / 8,
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
});
var out = btoa(encrypt); //SGpJSWhDUXNmMEMzSk0vbmovaGZyQT09
The following is the Java code snippet:
String randomKey = "2116781760886580";
String plainText = "Text to encrypt";
byte[] keyBytes = randomKey.getBytes(StandardCharsets.UTF_8);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec ivSpec = new IvParameterSpec(keyBytes);
SecretKeySpec sKey = new SecretKeySpec(keyBytes,"AES");
cipher.init(Cipher.ENCRYPT_MODE, sKey, ivSpec);
byte[] encryptedBytes = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
String out = Base64.getEncoder().encodeToString(encryptedBytes); //HjIIhCQsf0C3JM/nj/hfrA==
CryptoJS.AES.encrypt()returns aCipherParamsobject that encapsulates various data, including the ciphertext. I don't know whatbtoadoes with this object, but it doesn't return the Base64 encoded ciphertext. You can get it withencrypt.ciphertext.toString(CryptoJS.enc.Base64)or shorter withencrypt.toString()and it corresponds to the Base64 encoded ciphertext of the Java code. By the way, using the key as IV is generally insecure.