如何在javascript中加密或解密字符串

时间:2018-05-21 12:53:17

标签: javascript jquery

我想使用以下代码在javascript中加密和解密字符串。但我得到了加密js未定义。



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>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:4)

对我来说很好。

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>

答案 1 :(得分:2)

encrypted.toString()将返回正确的字符串值。

var encrypted = CryptoJS.AES.encrypt("Message", "Secret Passphrase");
alert(encrypted.toString());
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>

答案 2 :(得分:2)

如果您要构建React或Node.js应用,则只需使用此库ncrypt-js即可加密和解密数据。

See example on codesandbox

用法:

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