Web Crypto Encryption and Decryption Example
This basic example encrypts and decrypts values in the browser. The AES-GCM encryption and decryption keys are derived from a password based key (PBKDF2). The encrypted output is written to and read from the DOM, but such a solution could be used to store encrypted values on a server or database.
An overview of the logical steps used for encryption and decryption in
- Create a password based key (PBKDF2) that will be used to derive the AES-GCM key used for encryption / decryption.
- Create an AES-GCM key using the PBKDF2 key and a randomized salt value.
- Encrypt the input data using the AES-GCM key and a randomized initialization vector (iv).
- The values used for the password, salt, iv for encryption are needed for decryption. Therefore, create a base64 string to be stored that includes the salt that was used when creating the password based key (PBKDF2), iv used for creating the AES key, and the encrypted content. The password should remain secret.
- Derive the salt, iv, and encrypted data from the base64 string.
- Create a password based key (PBKDF2) that will be used to derive the AES-GCM key used for encryption / decryption. Password must be the same used for encryption.
- Create an AES-GCM key using the PBKDF2 key and the salt from the base64 string.
- Decrypt the input data using the AES-GCM key and the iv from the base64 string.
- Decode the decrypted value to a string.