Search code examples
javascriptreactjsencryptioncryptojs

how to encrypt/decrypt with crypto-js


I'm using crypto-js library:

https://github.com/brix/crypto-js

I want to encrypt some value and decrypt them.

but it returns wrong output.

my codes:

import CryptoAES from 'crypto-js/aes'

componentDidMount(){
  var ciphertext = CryptoAES.encrypt('my message', 'secret key 123');
  var _ciphertext = CryptoAES.decrypt(ciphertext, 'secret key 123');
  console.log(_ciphertext.toString(CryptoAES.Utf8));
}

but my console doesn't return my message. it returns like this:

6d79206d657373616765

Solution

  • I have never used this library, but a small check shows your result is your input's ASCII code as hex string.

    0x6d=m
    ...
    0x65=e
    
    6d|79|20|6d|65|73|73|61|67|65
    m |y |  |m |e |s |s |a |g |e
    

    So this code is working correctly. Probably that _ciphertext.toString() mess everything up. You need to check how to use _ciphertext correctly.