Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 353
S.M_Emamian Avatar asked Sep 02 '25 06:09

S.M_Emamian


2 Answers

import CryptoAES from 'crypto-js/aes';
import CryptoENC from 'crypto-js/enc-utf8';

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

enter image description here

like image 89
Santosh Singh Avatar answered Sep 04 '25 19:09

Santosh Singh


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.

like image 44
Afshin Avatar answered Sep 04 '25 19:09

Afshin