JavaScript offers an in-built API for performing data encryption, known as the Web Cryptography API. This API provides a suite of cryptographic operations that include hashing, signature verification, key generation, and many more.
Let's look at an example of how to use this API for encrypting and decrypting data.
HTML Markup:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Data Encryption and Decryption with JavaScript</title>
</head>
<body>
<h1>Data Encryption and Decryption with JavaScript</h1>
<button onclick="encryptData()">Encrypt Data</button>
<button onclick="decryptData()">Decrypt Data</button>
</body>
</html>
Ask your specific question in Mate AI
In Mate you can connect your project, ask questions about your repository, and use AI Agent to solve programming tasks
JavaScript Code:
// Key Generation
let iv = window.crypto.getRandomValues(new Uint8Array(16)); // Create a random Initialization Vector
let encryptionKey = null;
// Generate a secure encryption key
window.crypto.subtle.generateKey({ name: 'AES-CBC', length: 256 }, true, ['encrypt', 'decrypt']).then(key => {
encryptionKey = key;
}).catch(err => {
console.error(err);
});
// Function to Encrypt Text
function encryptData() {
let encoder = new TextEncoder();
let dataToEncrypt = encoder.encode('Secure Text');
window.crypto.subtle.encrypt({ name: 'AES-CBC', iv: iv }, encryptionKey, dataToEncrypt).then(cipherText => {
let encryptedData = new Uint8Array(cipherText);
console.log(`Cipher text: ${Array.from(encryptedData).join(",")}`); // Display the encrypted data
}).catch(err => {
console.error(err);
});
}
// Function to Decrypt Text
function decryptData() {
let encryptedData = new Uint8Array([/*Cipher text data comes here*/]); // Add the encrypted data
window.crypto.subtle.decrypt({ name: 'AES-CBC', iv: iv }, encryptionKey, encryptedData.buffer).then(plainText => {
let decoder = new TextDecoder();
console.log(`Plain text: ${decoder.decode(plainText)}`); // Display the decrypted data
}).catch(err => {
console.error(err);
});
}
Remember following things while using this script:
- Make sure to convert the data into an ArrayBuffer before encryption and decryption.
- The same initialization vector (IV) and key must be used for decryption that were used for encryption.
- Make sure to keep your key securely and never expose it.
- This script should run on a server. The Web Crypto API doesn’t work with the file:// protocol due to security restrictions, so it won’t run properly as a local file in your web browser.
- Note that cryptographic operation (like generateKey(), encrypt(), and decrypt()) are asynchronous and return promises. This fact is crucial when programming the control flow of your application.
AI agent for developers
Boost your productivity with Mate:
easily connect your project, generate code, and debug smarter - all powered by AI.
Do you want to solve problems like this faster? Download now for free.