Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to encrypt or decrypt string in javascript

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>
like image 787
PRIYANKA MORE Avatar asked May 21 '18 12:05

PRIYANKA MORE


2 Answers

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>
like image 82
Alex Avatar answered Oct 21 '22 15:10

Alex


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
like image 4
ajimae Avatar answered Oct 21 '22 14:10

ajimae