JavaScript AES encryption and decryption (Advanced Encryption Standard)

巧了我就是萌 提交于 2019-11-29 00:47:02

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. Please see my below example that will very easy to use in your ready code.

Just need to call encryptMessage and decryptMessage fnuction. 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.

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

Why would you want to implement AES in JavaScript? it would be extremely slow compared to a native (or wasm) implementation. Luckily, you have access to a native implementation right in the browser (even IE11 if you change a few things). 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.

Using GCM in this example but you can use CTR mode if you don't need the authentication:

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). You can decrypt it just as easily, as long as you have the key and IV used for encryption.

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

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.

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!