Encryption Decryption Using CryptoJs

Posted By : Pushpandra Kumar | 17-Jun-2018

Encryption

Encryption is the process of converting the message to some other message so that only intended person can see the message. It involves a text that needs to be converted called as ciphertext and a key used to encrypt to message. The converted text is called as Encrypted Text. There is a number of algorithms out there for encryption. Based upon types of the key there are two types of Encryption. 
1. Symmetric Encryption
2. Asymmetric Encryption


Symmetric Encryption
In this type of encryption, the same key is used to Encrypt and Decrypt the ciphertext. 

Asymmetric Encryption 
In this type of encryption, different keys are used to Encrypt and Decrypt the ciphertext. 

Encryption in Javascript
We can use CryptoJS javascript library to encrypt and decrypt the ciphertext. 
First, Import the library, you either download the library or use CDN link.

  <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9-1/crypto-js.js"> </script>
 

 

Now we will use AES algorithm to encrypt the text. 

<script>
// Cipher Text
var cipherText = "This Text will be Encrypted using AES";
console.log("Cipher Text : "+ cipherText);

var key = "PasswordText";
console.log("Key : "+ key);

var encrptedText = CryptoJS.AES.encrypt(cipherText, key);
console.log("Encrpted Text : "+ encrptedText.toString());
</script>
 

Decryption
Decryption is the reverse of encryption i.e converting encrypted text to ciphertext. Luckily, CrptoJS also have functions to decrypt the encrypted text using the same key that was used to encrypt it.

Decryption in Javascript

Now, We will illustrate an example to show the use of Decrypt function.

<script>
var cipherText = "This Text will be Encrypted using AES";
console.log("Cipher Text : "+ cipherText);

var key = "PasswordText";
console.log("Key : "+ key);

var encrptedText = CryptoJS.AES.encrypt(cipherText, key);
console.log("Encrpted Text : "+ encrptedText.toString());

var decryptedText = CryptoJS.AES.decrypt(encrptedText, key);
console.log("Decrypted Text : "+ decryptedText.toString(CryptoJS.enc.Utf8));
</script>
 

 

About Author

Author Image
Pushpandra Kumar

Pushpender has experience in Core Java, C & C++. His hobbies are learning new technologies and listening music.

Request for Proposal

Name is required

Comment is required

Sending message..