I want to encrypt and decrypt string in javascript using following code.But i got crypto js is not defined.
var encrypted = CryptoJS.AES.encrypt("Message", "Secret Passphrase");
var decrypted = CryptoJS.AES.decrypt(encrypted, "Secret Passphrase");
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/aes.js"></script>
Works fine for me.
JSFiddle: https://jsfiddle.net/xbk736br/
// Encrypt
var ciphertext = CryptoJS.AES.encrypt('my message', 'secret key 123');
// Decrypt
var bytes = CryptoJS.AES.decrypt(ciphertext.toString(), 'secret key 123');
var plaintext = bytes.toString(CryptoJS.enc.Utf8);
console.log(plaintext);
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/aes.js"></script>
If you are building a react or nodejs app, you can simply use this library ncrypt-js to encrypt and decrypt your data.
See example on codesandbox
usage:
es5
var ncrypt = require('ncrypt-js'); // or var { encrypt, decrypt } = require('ncrypt-js);
let encryptData = ncrypt.encrypt('super secret data', 'secret_key');
// or
// let encryptData = encrypt('super secret data', 'secret_key');
console.log(encryptData); // 11ab949601eb136f58ac3fe846e30d76.f9ce133b20adc35eef32af95957547abbb6fbfc5cb91cd14f5b0a088bd031883963cde1a56fd62fe2aeb75451a065d21
var decryptedData = ncrypt.decrypt(encryptData);
// or
// var decryptedData = decrypt(encryptData);
console.log(decryptedData); // super secret data
es6
import ncrypt from 'ncrypt-js'; // or import { encrypt, decrypt } from 'ncrypt-js';
const encryptData = ncrypt.encrypt('super secret data', 'secret_key');
// or
// const encryptData = encrypt('super secret data', 'secret_key');
console.log(encryptData); // 11ab949601eb136f58ac3fe846e30d76.f9ce133b20adc35eef32af95957547abbb6fbfc5cb91cd14f5b0a088bd031883963cde1a56fd62fe2aeb75451a065d21
const decryptedData = ncrypt.decrypt(encryptData);
// or
// const decryptedData = decrypt(encryptData);
console.log(decryptedData); // super secret data
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With