Search code examples
javascriptaescryptojs

AES encryption / decryption gives different result for the same input, and same iv, pad & mode


I'm trying to make 2 apps, the first encrypt a data, and save it to a file, then the second will try to read this file and decrypt its content

I'm working with crypto-js library with ionic/angular

in the first program (encrypter) I wrote:

encryptTest(input: string) {
    let key = "secret";
    return crypto.AES.encrypt(input, key, {
      iv: 'aTestIvValueKey',
      mode: crypto.mode.CBC,
      padding: crypto.pad.Pkcs7
    }).toString();
  }

then I call it with:

this.encryptTest('hello world !')

it gives me on output:

U2FsdGVkX186H1iRZM4Il+10/TS6gM7DoUaghwAZX3A=

when I try to decrypt this output in the second program, it doesn't give me the previous input: hello world ! but a wrong test which is:

68656c6c6f20776f726c642021

the second program (decrypter): has:

decryptTest(input: string) {
    let key = "secret";
    return crypto.AES.decrypt(input, key, {
      iv: 'aTestIvValueKey',
      mode: crypto.mode.CBC,
      padding: crypto.pad.Pkcs7
    }).toString();
  }

PS: I use the same iv, pad & mode


Solution

  • So, what i did to resolve:

    return crypto.AES.decrypt(input, key, {
          iv: 'aTestIvValueKey',
          mode: crypto.mode.CBC,
          padding: crypto.pad.Pkcs7
        }).toString(crypto.enc.Utf8);