简体   繁体   English

JavaScript AES 加解密(高级加密标准)

[英]JavaScript AES encryption and decryption (Advanced Encryption Standard)

How to implement encryption and decryption using AES (Advanced Encryption Standard) in JavaScript.如何在 JavaScript 中使用 AES(高级加密标准)实现加密和解密。

Why AES (Advanced Encryption Standard) ?为什么是 AES(高级加密标准)?

Security: Competing algorithms were to be judged on their ability to resist attack, as compared to other submitted ciphers, though security strength was to be considered the most important factor in the competition.安全性:与其他提交的密码相比,竞争算法将根据它们抵抗攻击的能力来判断,尽管安全强度被认为是竞争中最重要的因素。

Cost: Intended to be released under a global, nonexclusive and royalty-free basis, the candidate algorithms were to be evaluated on computational and memory efficiency.成本:打算在全球、非排他性和免版税的基础上发布,候选算法将在计算和内存效率方面进行评估。

 function encrypt(message = '', key = ''){ var message = CryptoJS.AES.encrypt(message, key); return message.toString(); } function decrypt(message = '', key = ''){ var code = CryptoJS.AES.decrypt(message, key); var decryptedMessage = code.toString(CryptoJS.enc.Utf8); return decryptedMessage; } console.log(encrypt('Hello World')); console.log(decrypt('U2FsdGVkX1/0oPpnJ5S5XTELUonupdtYCdO91v+/SMs=')) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/aes.js"></script> 

AES is very Simple and powerful encryption and decryption method. AES是非常简单而强大的加密和解密方法。 Please see my below example that will very easy to use in your ready code. 请参阅下面的示例,该示例将很容易在您准备好的代码中使用。

Just need to call encryptMessage and decryptMessage fnuction. 只需要调用encryptMessagedecryptMessage函数即可。 I already provided running example below. 我已经在下面提供了运行示例。

How to called these methods: 如何调用这些方法:

code.encryptMessage('Welcome to AES !','your_password');
code.decryptMessage('U2FsdGVkX1/S5oc9WgsNyZb8TJHsuL7+p4yArjEpOCYgDTUdkVxkmr+E+NdJmro9','your_password')

 let code = (function(){ return{ encryptMessage: function(messageToencrypt = '', secretkey = ''){ var encryptedMessage = CryptoJS.AES.encrypt(messageToencrypt, secretkey); return encryptedMessage.toString(); }, decryptMessage: function(encryptedMessage = '', secretkey = ''){ var decryptedBytes = CryptoJS.AES.decrypt(encryptedMessage, secretkey); var decryptedMessage = decryptedBytes.toString(CryptoJS.enc.Utf8); return decryptedMessage; } } })(); console.log(code.encryptMessage('Welcome to AES !','your_password')); console.log(code.decryptMessage('U2FsdGVkX1/S5oc9WgsNyZb8TJHsuL7+p4yArjEpOCYgDTUdkVxkmr+E+NdJmro9','your_password')) 
 <!DOCTYPE html> <html> <head> <title>E2EE</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/aes.js"></script> </head> <body> </body> </html> 

You can also refer my github code repository for more references. 您也可以参考我的github代码存储库以获取更多参考。

https://github.com/shedagemayur/JavaScriptCode/tree/master/AES https://github.com/shedagemayur/JavaScriptCode/tree/master/AES

Why would you want to implement AES in JavaScript? 为什么要在JavaScript中实现AES? it would be extremely slow compared to a native (or wasm) implementation. 与本地(或wasm)实现相比,这将非常慢。 Luckily, you have access to a native implementation right in the browser (even IE11 if you change a few things). 幸运的是,您可以直接在浏览器中访问本机实现 (如果您做了一些更改,甚至可以访问IE11)。 It's very fast (hundreds of times faster according to some benchmarks posted a while ago on the Webkit blog ) and it doesn't require 50kb libraries. 它非常快(根据不久前发布在Webkit博客上的一些基准测试 ,速度提高了数百倍),并且不需要50kb的库。

Using GCM in this example but you can use CTR mode if you don't need the authentication: 在此示例中使用GCM,但是如果不需要身份验证,则可以使用CTR模式:

const key = await crypto.subtle.generateKey({name: 'AES-GCM', length: 128}, true, ['encrypt', 'decrypt'])
const text = "confidential message"
// IV must be the same length (in bits) as the key
const iv = await crypto.getRandomValues(new Uint8Array(16))
const cyphertext = await crypto.subtle.encrypt({name: 'AES-GCM', tagLength: 32, iv}, key, new TextEncoder().encode(text))

That will result in cyphertext containing an ArrayBuffer with the encrypted string and a 4-byte authentication tag (that's specific to GCM, other AES modes will just produce the encrypted data). 这将导致cyphertext包含一个带有加密字符串和4字节身份验证标签的ArrayBuffer(特定于GCM,其他AES模式将仅生成加密数据)。 You can decrypt it just as easily, as long as you have the key and IV used for encryption. 只要您具有用于加密的密钥和IV,就可以轻松解密它。

const cleartext = await crypto.subtle.decrypt({name: 'AES-GCM', tagLength: 32, iv}, key, cyphertext)
console.log(new TextDecoder().decode(cleartext))

I've built an NPM package called encrypt-with-password which allows you to encrypt and decrypt text and JavaScript objects with a password, using AES and deriving the AES key from the password with PBDKF2.我构建了一个名为encrypt-with-password的 NPM 包encrypt-with-password它允许您encrypt-with-password加密和解密文本和 JavaScript 对象,使用 AES 并使用 PBDKF2 从密码中派生 AES 密钥。

Installation:安装:

npm install encrypt-with-password

or:或者:

yarn add encrypt-with-password

To Encrypt and Decrypt Text:加密和解密文本:

const encryptpwd = require('encrypt-with-password');

const text = 'Hello, World!';
const password = 'examplepassword';

const encrypted = encryptpwd.encrypt(text, password); // ---> this is the encrypted (output) value

// example encrypted value: 'e68e7ccd9e908665818a49f111c342ed:c9b83ff7624bb3b26af8cc853d61cd2f7959cecc4308383c39a0924e90637889'

const decrypted = encryptpwd.decrypt(encrypted, password) // ---> this decrypts the encrypted value and yields the original text

To Encrypt and Decrypt JavaScript Objects:加密和解密 JavaScript 对象:

const encryptpwd = require('encrypt-with-password');

const jsObject = {
  aString: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.',
  aNumber: 5,
  anArray: [1, 2, 3, 4, 5],
  anObj: {
    aKey: 'a value'
  }
};
const password = 'examplepassword2';

const encrypted = encryptpwd.encryptJSON(jsObject, password); // ---> this is the encrypted value

// example encrypted value: 'f953284ffe3e44a7b9de8487b50c3449:123378b5c481399488f520ebb774b076b85a12bc0f9a67cf8faf359eb4f804fc0594bc42374a20b4216b1312d7a408cf94517e19dfcada5513c49f6d13d26c982c562904306900a3f777b9c19b9c002e12dd216984f68566684f9f0259a45e007a0cecb2325333faafb18ed0e751933d8b1195b02b2adda29269cf1c6fa6fff73f0bac4abcf58b391521e0382c06a5f01f31c1243d827f8c7076f81d7f530259a3ae459e524bee80230672f153ab6a4e'

const decrypted = encryptpwd.decryptJSON(encrypted, password) // ---> this decrypts the encrypted value and yields the original object

The code behind this package is open sourced: https://github.com/xtrp/encrypt-with-password .这个包背后的代码是开源的: https : //github.com/xtrp/encrypt-with-password

below code was worked for me 下面的代码为我工作

encryptMessage: function(messageToencrypt = '', secretkey = ''){
    var encryptedMessage = CryptoJS.AES.encrypt(messageToencrypt, secretkey);
    return encryptedMessage.toString();
},
decryptMessage: function(encryptedMessage = '', secretkey = ''){
    var decryptedBytes = CryptoJS.AES.decrypt(encryptedMessage, secretkey);
    var decryptedMessage = decryptedBytes.toString(CryptoJS.enc.Utf8);

    return decryptedMessage;
}

Thanks 谢谢

If you are building a react or nodejs app, you can simply use this library ncrypt-js to encrypt and decrypt your data. 如果您要构建React或Node.js应用,则只需使用此库ncrypt-js即可加密和解密您的数据。

See example on codesandbox 请参见codeandbox上的示例

usage: 用法:

es5 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 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

Try out this.试试这个。 This worked out for me well for dynamic json data as well as normal text.对于动态 json 数据和普通文本,这对我来说效果很好。

var key = CryptoJS.enc.Utf8.parse("93wj660t8fok9jws");
// Please parse the your secret key
var iv = CryptoJS.enc.Utf8.parse(CryptoJS.lib.WordArray.random(128 / 8));

function encrypt(plainText) {
     return CryptoJS.AES.encrypt(
plainText, key,{ iv: iv,padding:CryptoJS.pad.Pkcs7,
mode:CryptoJS.mode.CBC }).ciphertext.toString(CryptoJS.enc.Base64);
}
function decrypt(encryptedText) {  
    var cipherParams = CryptoJS.lib.CipherParams.create(
    {
        ciphertext: CryptoJS.enc.Base64.parse(encryptedText)
    });
    return CryptoJS.AES.decrypt(cipherParams, key, { iv: iv,
                               padding: CryptoJS.pad.Pkcs7,
                               mode: CryptoJS.mode.CBC
                              }).toString(CryptoJS.enc.Utf8);
}
var start = new Date().getTime();
var encrypted = encrypt(
'{\"name\": \"Sushant\", \"loves\": \"cats\"}'
);
var end = new Date().getTime();
console.log(end - start);
document.getElementById('enc').innerHTML = encrypted;
document.getElementById('dec').innerHTML = decrypt(encrypted);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM