简体   繁体   中英

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

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.

Currently you are getting a hexa string 6d79206d657373616765 as you can check on this convertor when you enter my message it will return you 6d79206d657373616765

As used in the crypto-js Documentation

You need to make use of .toString() inside your decrypt method as currently you are getting hex for your my message and you need to convert that back to string , So you need to change this :

var _ciphertext = CryptoAES.decrypt(ciphertext, 'secret key 123');

To

var _ciphertext = CryptoAES.decrypt(ciphertext.toString(), 'secret key 123');

It will be like :

import CryptoAES from 'crypto-js/aes'

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

You can use this. cippertext use output algorytms.

ciphertext.toString("base64")

or

ciphertext.toString("hex")
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));

在此处输入图片说明

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