Skip to content
Advertisement

JavaScript AES encryption and decryption (Advanced Encryption Standard)

How to implement encryption and decryption using AES (Advanced Encryption Standard) in JavaScript.

Why AES (Advanced Encryption Standard) ?

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.

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement