简体   繁体   中英

Decrypt data using CryptoJs

I'm using below code to encrypt data using CryptoJS

export const encryptData = (data) => {
    let key = CryptoJS.enc.Utf8.parse(api.encryption.Key);
    let iv = {
        keySize: 128 / 8,
        iv: CryptoJS.enc.Utf8.parse(api.encryption.IV),
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    };
    return encodeURIComponent(CryptoJS.AES.encrypt(CryptoJS.enc.Utf8.parse(data), key, iv));
}

And for decrypting the data i used below code. But data is not getting decrypted. However encrypt is working fine.

export const decryptData = (data) => {
    let key = CryptoJS.enc.Utf8.parse(api.encryption.Key);
    let iv = {
        keySize: 128 / 8,
        iv: CryptoJS.enc.Utf8.parse(api.encryption.IV),
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    };
    return decodeURIComponent(CryptoJS.AES.decrypt(CryptoJS.enc.Utf8.parse(data), key, iv));
}

Any idea what I am doing wrong while decrypting?

I think the issue is that when you encrypt you return encodeURIComponent string, but when you decrypt you decode such string too late.

export const decryptData = (data) => {
  let key = CryptoJS.enc.Utf8.parse(api.encryption.Key);
  let iv = {
      keySize: 128 / 8,
      iv: CryptoJS.enc.Utf8.parse(api.encryption.IV),
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7
  };
  return CryptoJS.AES.decrypt(decodeURIComponent(data), key, iv).toString(CryptoJS.enc.Utf8);
}

this version, instead, decode data before passing it to decrypt , otherwise you decrypt something that has been encoded, hence it's not usable for decrypt.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM