4

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
1
  • I got this error message : cannot read property 'Utf8' of undefined Commented Apr 1, 2018 at 20:35

4 Answers 4

7
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

Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

2

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));
}

1 Comment

this is the answer, because without .toString the result should be object type not string
-1

You can use this. cippertext use output algorytms.

ciphertext.toString("base64")

or

ciphertext.toString("hex")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.