Andrew Milich / 12.10.2022Home / guides

How do encryption and decryption work in Javascript?

Javascript powers every modern web application. How can secure web apps perform encryption and decryption?
Encryption and decryption diagram in Javascript.
Encryption is used by almost every single application on the internet today. From data encryption inside databases, to network encryption used in SSL/TLS (every https: website), to end-to-end encryption inside secure messaging and communication products, a diversity of algorithms, encryption processes, and cryptography now power the modern web stack.

Overview and vocabulary

Below, we’ll define a few topics that are used throughout the blog.Symmetric encryption: A type of encryption where the same key is used to encrypt and decrypt a message.Asymmetric encryption: A type of encryption where two different keys are used to encrypt and decrypt a message.Hashing: A cryptographic function (“hash function”) that produces a fixed-size output (called a hash) from an input of any size. Hashes are commonly used to verify the integrity of data.Encoding: A process of transforming data into a different format using a specific algorithm. Encoding is often used to convert data into a format that is more efficient for storage or transmission. It is not a form of encryption and does not provide any security benefits.

Encryption and decryption in Javascript

Encryption and decryption are important concepts in the field of computer science and information security. Encryption is the process of converting plain text (i.e. regular, readable text) into ciphertext (i.e. scrambled, unreadable text) using a mathematical algorithm and a secret key. Decryption is the reverse process of converting ciphertext back into plain text using the same algorithm and key.

Skiff-crypto library for easy encryption, decryption, and more

We at Skiff offer an end-to-end encrypted, privacy-first product suite with Mail, Calendar, Pages, and Drive products. Naturally, they use encryption in every part of the application to keep your emails, calendar events, notes, and files private and accessible only to you.We've open-sourced skiff-crypto to make cryptography even easier to use in JavaScript on Node.JS and in the browser. To use `skiff-crypto`, check out the short tutorial below:const skiffCrypto = require('@skiff-org/skiff-crypto');// or, `import * as skiffCrypto from '@skiff-org/skiff-crypto';`const plaintext = "Hello from skiff-crypto!";
const keypair = skiffCrypto.generatePublicPrivateKeyPair();
const encrypted = skiffCrypto.stringEncryptAsymmetric(keypair.privateKey, { key:keypair.publicKey }, plaintext);
const decrypted = skiffCrypto.stringDecryptAsymmetric(keypair.privateKey, { key:keypair.publicKey }, encrypted);
console.log('Plaintext:', plaintext);
console.log('Ciphertext:', encrypted);
console.log('Expected to be true:', plaintext === decrypted);
The library offers many, many more functions, including signature verification functions - such as verifyDetachedSignatureAsymmetric to verify cryptography signatures, or createDetachedSignatureAsymmetric to create them.Check out the GitHub library here.

More crypto libraries: Using crypto-js

In Javascript, encryption and decryption are typically implemented using one of several popular algorithms, such as the Advanced Encryption Standard (AES) or the RSA algorithm. The specific algorithm used depends on the needs of the application and the security requirements of the data being encrypted.To illustrate how encryption and decryption work in Javascript, let's consider a simple example using the AES algorithm. In this example, we will use a secret key of "12345" and a plain text message of "Hello, world!"First, we need to import the necessary libraries for AES encryption. In this case, we will use the "crypto-js" library, which can be installed into project dependencies using the following NPM command:npm install crypto-jsNote that if you prefer to use yarn, the command “yarn add crypto-js” will work as well. Once the library is installed, we can import it into our Javascript code using the following line of code:const CryptoJS = require("crypto-js");Next, we need to define our secret key and plain text message. In this example, we will use the key and message defined earlier:const key = "12345";
const plainText = "Hello, world!";
With the key and plain text defined, we can now encrypt the message using the AES algorithm and the CryptoJS encrypt function. In Javascript, this is done using the following code:const encrypted = CryptoJS.AES.encrypt(plainText, key);The encrypted message is returned as a ciphertext string, which is unreadable to anyone who does not have the secret key. For example, the encrypted text in this case might look something like this:U2FsdGVkX18cwq3S7v2bT+E9T9XkTfH4D4Gp+gWZFok=To decrypt the ciphertext back into the original plain text message, we can use the following decryption function:const decrypted = CryptoJS.AES.decrypt(encrypted, key);This line uses the encrypted ciphertext and the secret key to decrypt the message back into its original plain text (“Hello, world!”). In some cases, encryption or decryption functions expect certain encodings of text, such as hex or utf8, which each use different character sets to represent data.AES encryption, which is used here, is a symmetric encryptionalgorithm where the same secret key is used to both encrypt and decrypt the text.In asymmetric encryption, different keys are used to encrypt plain text (a public key) and decrypt the cipher text (private key).

The NodeJS crypto library

Node.js is a runtime environment for executing JavaScript code on the server side. Node.js includes a built-in library called crypto that provides a number of cryptographic functions, including functions for generating hashes, signing and verifying digital signatures, and generating random numbers.The Web Cryptography API, or WebCrypto, is a JavaScript API that provides similar cryptographic functionality to the crypto library in Node.js. WebCrypto is designed to be used in web applications and allows developers to perform cryptographic operations directly in the browser. This can be useful for implementing security features such as password hashing and encrypting sensitive data without having to send the data to a server for processing.Both the crypto library in Node.js and the WebCrypto API provide a powerful set of tools for implementing cryptographic functions in web applications. However, it is important to use these tools carefully and securely to ensure that sensitive information is protected.

Why use encryption?

Encryption is used in web applications to protect sensitive information such as passwords, credit card numbers, and other personal information from being intercepted and read by unauthorized individuals. When a user submits sensitive information to a web application, the information is encrypted by the web application before it is transmitted over the internet. This ensures that even if the information is intercepted by a third party, it will be unreadable and unable to be used. Encrypting sensitive information is an important security measure that helps to keep user information safe and secure.

Examples of apps that use encryption in the web

MetaMask (Ethereum wallet)MetaMask is a browser extension that allows users to interact with the Ethereum blockchain from their web browser. MetaMask uses encryption to protect the sensitive information that is stored in the user's wallet.When a user creates a wallet with MetaMask, they are required to choose a password. This password is used to encrypt the user's private keys, which are stored locally on the user's device. This means that the user's private keys are unreadable without the password and are therefore protected from unauthorized access.1Password (Password manager)1Password is a password manager that helps users securely store and manage their online passwords. 1Password uses encryption to protect the sensitive information that is stored in its password vault. When a user creates an account with 1Password, they are required to choose a master password. This master password is used to encrypt the user's password vault, which means that the information stored in the vault is unreadable without the master password.1Password uses a combination of symmetric and asymmetric encryption to protect user information. When a user first creates their account and sets their master password, 1Password generates a unique encryption key that is used to encrypt the user's password vault. This encryption key is then encrypted using the user's master password and stored on 1Password's servers.When a user logs in to 1Password and enters their master password, 1Password uses the encrypted encryption key to decrypt the user's password vault. The user's master password is never sent to 1Password's servers and is only used locally on the user's device to decrypt the encrypted encryption key. This means that 1Password is able to protect user information without ever having access to the user's master password.Skiff Mail, Calendar, Pages, and Drive (email and productivity suite)Skiff is a privacy-first, end-to-end encrypted email and collaboration suite with mail, calendar, collaborative notes, and file storage products. All data on Skiff - messages, files, notes, and calendar events - is end-to-end encrypted, meaning only you have access to your data. When logging into Skiff, your device decrypts data into a human readable form.Skiff is free to use, with paid plans available as well. Similar to MetaMask and 1Password, a password is used to encrypt private information when you sign in. This password also enables you to transfer and decrypt data on another device, while keeping that data end-to-end encrypted.Skiff is one of the best examples of a user-friendly, intuitive application that uses cryptography inside the browser and in Javascript.

Further reference

We hope this blog was helpful! For more information, checkout Skiff’s products or GitHub page. We’ll be sharing further tutorials on how to perform asymmetric encryption in javascript as well.

Join the community

Become a part of our 1,000,000+ community and join the future of a private and decentralized internet.

Free plan • No card required