After encrypting text in the previous post, here’s how you get your plaintext back.
The code
|
|
Decoding
After checking for a signature and saving it for later if there is one, we decode the Base64-encoded string back to raw.
|
|
CryptoJS kindly does the actual decoding just after we reversed our URL-save replacements. Knowing each of their positions in the string, we can easily recover our IV, salt and ciphertext. To get them to work in CryptoJS, we have to create a WordArray out of them, but the library offers a method to do just that.
Generating a key
Just like when encrypting, we generate a key using the exact same parameters.
Verifying the signature
If there was a signature, we verify it by re-signing the ciphertext and comparing the output to the HMAC provided. Abort, if this doesn’t match!
Decrypt
Having all the preparations done, we can finally decrypt now. CryptoJS’ decrypt() method (just like the encrypt()) returns a WordArray that needs to be converted to a regular UTF-8 encoded string for further use.
Usage
Using the decrypt functionality is just as simple as encrypting. Refer to my example in the previous post for an example implementation.
Conclusion
We did it! Encrypting and decrypting text with AES directly in the browser! Let me know in the comments if you found this useful and what mighty applications you’re using this in!