by @kodeazy
How to encrypt and decrypt a string in java script using SHA-256 algorithm
Here in this example will show you how to encrypt and decrypt a string using crypto js
.
Below are the script tags required for the implementation using cryptojs
and sha256
<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.9/sha256.js"></script>
To encrypt the data first generate the hash of the key and provide an empty initailization vector to encrypt you can provide what ever Initialization vector you want for now I am providing empty Initialization vector
var data="Example1";//Message to Encrypt
var iv = CryptoJS.enc.Base64.parse("");//giving empty initialization vector
var key=CryptoJS.SHA256("Message");//hashing the key using SHA256
var encryptedString=encryptData(data,iv,key);
console.log(encryptedString);//genrated encryption String: swBX2r1Av2tKpdN7CYisMg==
function encryptData(data,iv,key){
if(typeof data=="string"){
data=data.slice();
encryptedString = CryptoJS.AES.encrypt(data, key, {
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
});
}
else{
encryptedString = CryptoJS.AES.encrypt(JSON.stringify(data), key, {
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
});
}
return encryptedString.toString();
}
To decrypt the encrypted string take the encrypted string provide the same key which you have provided for encryption and as we have provided empty initialization vector for encryption provide same empty initialization vector and pass it to decrypt function
var iv = CryptoJS.enc.Base64.parse("");
var key=CryptoJS.SHA256("Message");
var decrypteddata=decryptData(encryptedString,iv,key);
console.log(decrypteddata);//genrated decryption string: Example1
function decryptData(encrypted,iv,key){
var decrypted = CryptoJS.AES.decrypt(encrypted, key, {
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
});
return decrypted.toString(CryptoJS.enc.Utf8)
}