<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"
integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/aes.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/pbkdf2.js"></script>
</head>
<body>
<h1>CryptoJs AES Encryption/Decryption</h1>
<div id="encrypted"></div>
<div id="decrypted"></div>
<script src="script.js"></script>
</body>
</html>
// Code goes here
var keySize = 256;
var ivSize = 128;
var iterations = 100;
var message = "Hello World";
var password = "Secret Password";
function encrypt (msg, pass) {
var salt = CryptoJS.lib.WordArray.random(128/8);
var key = CryptoJS.PBKDF2(pass, salt, {
keySize: keySize/32,
iterations: iterations
});
var iv = CryptoJS.lib.WordArray.random(128/8);
var encrypted = CryptoJS.AES.encrypt(msg, key, {
iv: iv,
padding: CryptoJS.pad.Pkcs7,
mode: CryptoJS.mode.CBC
});
// salt, iv will be hex 32 in length
// append them to the ciphertext for use in decryption
var transitmessage = salt.toString()+ iv.toString() + encrypted.toString();
return transitmessage;
}
function decrypt (transitmessage, pass) {
var salt = CryptoJS.enc.Hex.parse(transitmessage.substr(0, 32));
var iv = CryptoJS.enc.Hex.parse(transitmessage.substr(32, 32))
var encrypted = transitmessage.substring(64);
var key = CryptoJS.PBKDF2(pass, salt, {
keySize: keySize/32,
iterations: iterations
});
var decrypted = CryptoJS.AES.decrypt(encrypted, key, {
iv: iv,
padding: CryptoJS.pad.Pkcs7,
mode: CryptoJS.mode.CBC
})
return decrypted;
}
var encrypted = encrypt(message, password);
var decrypted = decrypt(encrypted, password);
$('#encrypted').text("Encrypted: "+encrypted);
$('#decrypted').text("Decrypted: "+ decrypted.toString(CryptoJS.enc.Utf8) );
Encryption and decryption using CryptoJS' AES implmentation