Tag Archives: Crypto-JS Failed to Decrypt Error

[Solved] Crypto-JS Failed to Decrypt Error: Uncaught Error: Malformed UTF-8 data

java encrypt js decrypt, an error is reported: Uncaught Error: Malformed UTF-8 data

public static String encrypt(String strToEncrypt, SecretKey secretKey) {
    try {
      Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7PADDING");
      cipher.init(Cipher.ENCRYPT_MODE, secretKey);
      encryptedString = new String(Base64.encodeBase64String(cipher.doFinal(strToEncrypt.getBytes())));
    } catch (Exception e) {
      System.out.println("Error while encrypting: " + e.toString());
    }

    return encryptedString;
  }

JS:

decrypt(secret_key,code) {
        return CryptoJS.AES.decrypt(code, this.parse(secret_key), {
          mode: CryptoJS.mode.ECB,
          padding: CryptoJS.pad.Pkcs7
        }).toString(CryptoJS.enc.Utf8);
      }

The reason is that the string has a newline character, Base64 generates a newline, change to NO_WRAP

 Base64.encodeBase64String(hashPassword,Base64.NO_WRAP)

Recommended Read: https://stackoverflow.com/questions/21852889/remove-r-and-n-from-aes-encrypted-string