0

I need encrypt in Javascript and Decrypt in Java but when i encrypt in Java the text is diferent, i used a diferent script but same algorithm, AES-128 CBC Zero Padding.

This is for Javascript and Java 7 in Intellij IDEA

Javascript:

   var message = "3258";
   var key = "CLAVE00000000000";
   var iv  = "VECTOR0000000000";

   var ciphertext = CryptoJS.AES.encrypt(message, key,  {iv: iv, padding: CryptoJS.pad.ZeroPadding, mode: CryptoJS.mode.CBC});
   alert(ciphertext.toString());

   var decrypt = CryptoJS.AES.decrypt(ciphertext, key, {iv: iv, padding: CryptoJS.pad.ZeroPadding, mode: CryptoJS.mode.CBC});
   alert(CryptoJS.enc.Utf8.stringify(decrypt).toString());

Java:

KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);
keyGenerator.init(AES_128);

String key = "CLAVE00000000000";
String IV = "VECTOR0000000000";
System.out.println("1. Message to Encrypt: " + new String(message, StandardCharsets.UTF_8));

byte[] cipherText = encrypt(key, IV, message);
System.out.println("2. Encrypted Text: " + Base64.getEncoder().encodeToString(cipherText));

byte[] decryptedString = decrypt(key, IV, cipherText);
System.out.println("3. Decrypted Message : " + new String(decryptedString));

I expect the cipher text identical in Javascript or in Java, but the values are diferent

Jose Guerra
  • 65
  • 2
  • 11

1 Answers1

1

In the JavaScript-code key and iv have to be passed as WordArrays. For this purpose CryptoJS provides conversion functions:

var key = CryptoJS.enc.Latin1.parse("CLAVE00000000000");
var iv = CryptoJS.enc.Latin1.parse("VECTOR0000000000");

If the key is passed as a string (as it is the case in the posted code), it is treated as a passphrase and used to derive a key and IV (see here, section The Cipher Input).

Furthermore, in the JavaScript-code Zero-Byte-Padding must be replaced by Pkcs7-Padding (padding: CryptoJS.pad.Pkcs7 instead of padding: CryptoJS.pad.ZeroPadding) in the encrypt- and decrypt-call.

Then the encryption of the JavaScript-code corresponds to that of the Java-code (sEAtASy0J3+Ya3g+Afcj3Q== for the used message, key and IV).

The replacing of the padding is a guess because the encrypt- and decrypt-methods of the Java-code have not been posted, so that a direct check is not possible. However, with regard to the same encryption when switching to Pkcs7, this should be true.

Topaco
  • 40,594
  • 4
  • 35
  • 62