To encrypt and decrypt data, simply use encrypt() and decrypt() function from an instance of crypto-js.
Node.js
(Install)
Requirements:
1. Node.js
2. npm
(Node.js package manager)
3. npm
install crypto-js
npm install crypto-js
Usage
-
Step 1 - Import
var CryptoJS = require("crypto-js");
Step 2 - Encrypt
// Encrypt
var ciphertext = CryptoJS.AES.encrypt(JSON.stringify(data), 'my-secret-key@123').toString();
Step 3 -Decrypt
// Decrypt
var bytes = CryptoJS.AES.decrypt(ciphertext, 'my-secret-key@123');
var decryptedData = JSON.parse(bytes.toString(CryptoJS.enc.Utf8));
As an Example,
import React from 'react';
import './App.css';
//Including all libraries, for access to extra methods.
var CryptoJS = require("crypto-js");
function App() {
var data = [{ id: 1, name: 'Anil' }, { id: 2, name: 'Sunil' }]
// Encrypt
var ciphertext = CryptoJS.AES.encrypt(JSON.stringify(data), 'my-secret-key@123').toString();
//log encrypted data
console.log('Encrypt Data -')
console.log(ciphertext);
// Decrypt
var bytes = CryptoJS.AES.decrypt(ciphertext, 'my-secret-key@123');
var decryptedData = JSON.parse(bytes.toString(CryptoJS.enc.Utf8));
//log decrypted Data
console.log('decrypted Data -')
console.log(decryptedData);
return (
<div className="App">
<header className="App-header">
<div>Encrypt Data -{ciphertext}</div>
<div>
{decryptedData.map(function (object) {
//console.log(object)
})}
</div>
</header>
</div>
);
}
export default App;
The Result looks like,
Checkout another demo:
https://stackblitz.com/edit/react-encrypt?file=index.js
List
of crypto-js available modules -
1) crypto-js/core
2) crypto-js/x64-core
3) crypto-js/lib-typedarrays
4) crypto-js/md5
5) crypto-js/sha1
6) crypto-js/sha256
7) crypto-js/sha224
8) crypto-js/sha512
9) crypto-js/sha384
10) crypto-js/sha3
11) crypto-js/ripemd160
12) crypto-js/hmac-md5
13) crypto-js/hmac-sha1
14) crypto-js/hmac-sha256
15) crypto-js/hmac-sha224
16) crypto-js/hmac-sha512
17) crypto-js/hmac-sha384
18) crypto-js/hmac-sha3
19) crypto-js/hmac-ripemd160
20) crypto-js/pbkdf2
21) crypto-js/aes
22) crypto-js/tripledes
23) crypto-js/rc4
24) crypto-js/rabbit
25) crypto-js/rabbit-legacy
26) crypto-js/evpkdf
27) crypto-js/format-openssl
28) crypto-js/format-hex
29) crypto-js/enc-latin1
30) crypto-js/enc-utf8
31) crypto-js/enc-hex
32) crypto-js/enc-utf16
33) crypto-js/enc-base64
34) crypto-js/mode-cfb
35) crypto-js/mode-ctr
36) crypto-js/mode-ctr-gladman
37) crypto-js/mode-ofb
38) crypto-js/mode-ecb
39) crypto-js/pad-pkcs7
40) crypto-js/pad-ansix923
41) crypto-js/pad-iso10126
42) crypto-js/pad-iso97971
43) crypto-js/pad-zeropadding
44) crypto-js/pad-nopadding