Sling Academy
Home/JavaScript/Encrypt and Decrypt Data Using the Web Crypto API in JavaScript

Encrypt and Decrypt Data Using the Web Crypto API in JavaScript

Last updated: December 13, 2024

In today's digital world, data security is more crucial than ever. Encrypting and decrypting sensitive data ensures that unauthorized parties cannot access it. The Web Crypto API in JavaScript provides developers with a powerful set of tools for handling cryptographic operations.

Understanding the Web Crypto API

The Web Crypto API is a native JavaScript API that allows you to perform various cryptographic operations in a secure and efficient manner. It is available in most modern browsers and enables operations such as hashing, digital signature generation, encryption, and decryption.

Setting Up the Environment

Before you start encrypting and decrypting data, ensure that your development environment supports the Web Crypto API. Most modern browsers have integrated support, so no external libraries are needed. To begin using the API, ensure that your code runs in a secure context (HTTPS or localhost).

Generating a CryptoKey

The first step in using the Web Crypto API for encryption is generating a CryptoKey, which is used for both encryption and decryption operations. Here's how you can generate a symmetric key using the API:

// Generate a random AES-GCM key
async function generateKey() {
  const key = await window.crypto.subtle.generateKey(
    {
      name: "AES-GCM",
      length: 256
    },
    true, // extractable (allows export)
    ["encrypt", "decrypt"]
  );
  return key;
}

Encrypting Data

Once you have a CryptoKey, the next step is to encrypt data. The Web Crypto API uses various encryption algorithms, with AES-GCM being a common choice for symmetrical encryption:

// Encrypt data using the AES-GCM algorithm
async function encryptData(key, data) {
  const encodedData = new TextEncoder().encode(data);
  const iv = window.crypto.getRandomValues(new Uint8Array(12)); // Initialization vector
  const encryptedData = await window.crypto.subtle.encrypt(
    {
      name: "AES-GCM",
      iv: iv
    },
    key,
    encodedData
  );
  return { iv, encryptedData };
}

In this example, the TextEncoder is used to convert strings into binary data, suitable for encryption. The Initialization Vector (IV) is a random byte array that helps ensure that encrypting the same data multiple times results in different ciphertext each time.

Decrypting Data

Decrypting the data requires the same CryptoKey and IV that were used during encryption. Here's a succinct example of how to decrypt your data:

// Decrypt data using the AES-GCM algorithm
async function decryptData(key, encryptedData, iv) {
  const decryptedData = await window.crypto.subtle.decrypt(
    {
      name: "AES-GCM",
      iv: iv
    },
    key,
    encryptedData
  );
  return new TextDecoder().decode(decryptedData);
}

In this decrypt operation, we convert the binary data back into readable text using the TextDecoder.

Putting It All Together

By combining these functions, you can create a simple application to securely encrypt and decrypt your data:

async function example() {
  const key = await generateKey();
  const data = "Secret message!";
  // Encrypt the data
  const { iv, encryptedData } = await encryptData(key, data);
  console.log('Encrypted Data:', new Uint8Array(encryptedData));

  // Decrypt the data
  const decryptedData = await decryptData(key, encryptedData, iv);
  console.log('Decrypted Data:', decryptedData);
}
example();

Conclusion

The Web Crypto API empowers developers to incorporate robust encryption and decryption mechanisms into their web applications without relying on third-party libraries. By following the outlined steps, you can safeguard user data effectively. Ensure that you always handle keys securely and follow best practices in cryptography to protect the confidentiality, integrity, and authenticity of data.

Next Article: Generate and Manage Keys with the Web Crypto API in JavaScript

Previous Article: Enhance Modularity and Maintainability with JavaScript Web Components

Series: Web APIs – JavaScript Tutorials

JavaScript

You May Also Like

  • Handle Zoom and Scroll with the Visual Viewport API in JavaScript
  • Improve Security Posture Using JavaScript Trusted Types
  • Allow Seamless Device Switching Using JavaScript Remote Playback
  • Update Content Proactively with the JavaScript Push API
  • Simplify Tooltip and Dropdown Creation via JavaScript Popover API
  • Improve User Experience Through Performance Metrics in JavaScript
  • Coordinate Workers Using Channel Messaging in JavaScript
  • Exchange Data Between Iframes Using Channel Messaging in JavaScript
  • Manipulating Time Zones in JavaScript Without Libraries
  • Solving Simple Algebraic Equations Using JavaScript Math Functions
  • Emulating Traditional OOP Constructs with JavaScript Classes
  • Smoothing Out User Flows: Focus Management Techniques in JavaScript
  • Creating Dynamic Timers and Counters with JavaScript
  • Implement Old-School Data Fetching Using JavaScript XMLHttpRequest
  • Load Dynamic Content Without Reloading via XMLHttpRequest in JavaScript
  • Manage Error Handling and Timeouts Using XMLHttpRequest in JavaScript
  • Handle XML and JSON Responses via JavaScript XMLHttpRequest
  • Make AJAX Requests with XMLHttpRequest in JavaScript
  • Customize Subtitle Styling Using JavaScript WebVTT Integration