Looking to implement AES encryption in JavaScript using the AES/CBC/NoPadding Mode and a method to complete 16-length blocks. Successfully solved this task using Java, here is an example:
public static String encrypt(byte[] key, byte[] initVector, String value) {
try {
IvParameterSpec iv = new IvParameterSpec(initVector);
SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
byte[] encrypted = cipher.doFinal(completeBlocks(value));
return Base64.encodeBase64String(encrypted);
} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException ex) {
System.out.println("Error: " + ex);
}
return null;
}
/**
* Completes 16-length blocks
*
* @param message
*/
static byte[] completeBlocks(String message) {
try {
int bytesLenght = message.getBytes("UTF-8").length;
if (bytesLenght % 16 != 0) {
byte[] newArray = new byte[bytesLenght + (16 - (bytesLenght % 16))];
System.arraycopy(message.getBytes(), 0, newArray, 0, bytesLenght);
return newArray;
}
return message.getBytes("UTF-8");
} catch (UnsupportedEncodingException ex) {
System.out.println("" + ex);
}
return null;
}
public static void main(String[] args) {
String key = "253D3FB468A0E24677C28A624BE0F939";
String strToEncrypt = "My Secret text";
final byte[] initVector = new byte[16];
String resultado = encrypt(new BigInteger(key, 16).toByteArray(), initVector, strToEncrypt.trim());
System.out.println("ENCRYPTED:");
System.out.println(resultado);
}
When using
key = 253D3FB468A0E24677C28A624BE0F939
, strToEncrypt = "My Secret text"
, and ceros IV as inputs, the output will be:
7StScX3LnPUly/VNzBes0w==
The desired output has been achieved successfully! However, I attempted to replicate this in JavaScript using the CryptoJs library but failed to produce the same result as in Java. Here is what I tried:
var text = "My Secret text";
var key = CryptoJS.enc.Base64.parse("253D3FB468A0E24677C28A624BE0F939");
var iv = CryptoJS.enc.Base64.parse(" ");
var encrypted = CryptoJS.AES.encrypt(text, key, {iv: iv});
console.log(encrypted.toString());
var decrypted = CryptoJS.AES.decrypt(encrypted, key, {iv: iv});
console.log(decrypted.toString(CryptoJS.enc.Utf8));
Using the same inputs resulted in De+CvPVIyiBX2//EE6gXTg==
being produced instead of the expected output 7StScX3LnPUly/VNzBes0w==
. Any insights on what might be going wrong or how to achieve the same result as in Java would be greatly appreciated. Thank you!