3

I am trying to store encrypted data in localStorage and decrypt it when needed by using crypto-js This is the encryption function:

const passphrase = CryptoJS.enc.Utf8.parse('key');
const iv = CryptoJS.enc.Utf8.parse('key');
return CryptoJS.AES.encrypt(string, passphrase, { mode: CryptoJS.mode.CBC, iv: iv, padding: CryptoJS.pad.Pkcs7}).toString();

And the decryption function is:

const passphrase = CryptoJS.enc.Utf8.parse('key');
const iv = CryptoJS.enc.Utf8.parse('key');
return CryptoJS.AES.decrypt(string, passphrase, { mode: CryptoJS.mode.CBC, iv: iv, padding: CryptoJS.pad.Pkcs7}).toString(CryptoJS.enc.Utf8)

But I get an empty string when decrypting. I have tried changing iv, padding, keysize and mode but i get different strings each time I run encryption in that case. I need encryption to always return the same result

Can somebody tell me what am I doing wrong please?

venovka
  • 31
  • 1
  • 3
  • See here: https://stackoverflow.com/a/16615194/1820553 Also, convert the output base64 before sending and convert back before decryption. Don't use IV=key since the IV is public. – kelalaka Jun 04 '20 at 22:40
  • Sorry, still no success, would you mind giving me a hand on my example, I am really new at encryption/decryption? – venovka Jun 05 '20 at 10:12
  • AES applies keys of the size 16, 24 and 32 bytes. The IV must be 16 bytes large. If that still doesn't work, post test data for plaintext, key, IV and ciphertext. By the way, if you want to use the built-in key derivation function, you have to pass a string instead of a `WordArray`, which is then interpreted as a passphrase from which the actual key is derived, see [The Cipher Input](https://cryptojs.gitbook.io/docs/#the-cipher-input). However, the key derivation function used is proprietary and relatively weak (OpenSSL's `EVP_BytesToKey`), so I would discourage it. – Topaco Jun 07 '20 at 08:24
  • https://stackoverflow.com/questions/39311514/how-to-decrypt-aes-with-cryptojs/66815024#66815024 – Nguyễn Thành Nghĩa Mar 26 '21 at 10:26

0 Answers0