brix / crypto-js

JavaScript library of crypto standards.
Other
15.88k stars 2.39k forks source link

Issue with AES.decrypt. #484

Open baryon2 opened 9 months ago

baryon2 commented 9 months ago

Hi, We use the AES.ecrypt and AES.decrypt functions to encrypt and decrypt secrets within our application. The encryption function works as expected; however, there are instances where the AES.decrypt function outputs incorrect text, despite no changes being made to the encrypted text or the password.

Has anyone else encountered this issue?

This is how we are using the AES encrypt and decrypt functions.

import CryptoJS from ‘crypto-js’;

const keySize = 256
const iterations = 10000

export const encrypt = (msg: string, pass: string): string => {
  const salt = CryptoJS.lib.WordArray.random(128 / 8);
  const key = CryptoJS.PBKDF2(pass, salt, {
    keySize: keySize / 32,
    iterations: iterations,
  });
  const iv = CryptoJS.lib.WordArray.random(128 / 8);
  const encrypted = CryptoJS.AES.encrypt(msg, key, {
    iv: iv,
    padding: CryptoJS.pad.Pkcs7,
    mode: CryptoJS.mode.CBC,
  });
  return salt.toString() + iv.toString() + encrypted.toString();
};

export const decrypt = (transitmessage: string, pass: string): string => {
  const salt = CryptoJS.enc.Hex.parse(transitmessage.substr(0, 32));
  const iv = CryptoJS.enc.Hex.parse(transitmessage.substr(32, 32));
  const encrypted = transitmessage.substring(64);
  const key = CryptoJS.PBKDF2(pass, salt, {
    keySize: keySize / 32,
    iterations: iterations,
  });
  return CryptoJS.AES.decrypt(encrypted, key, {
    iv: iv,
    padding: CryptoJS.pad.Pkcs7,
    mode: CryptoJS.mode.CBC,
  }).toString(CryptoJS.enc.Utf8);
};