In today’s digital age, securing sensitive information like API keys, passwords, and user data is more critical than ever. A robust encryption and decryption strategy can prevent unauthorized access and ensure data confidentiality. In this blog post, we’ll explore how to encrypt and decrypt text using vanilla JavaScript, leveraging the Web Crypto API for a modern, secure approach.
Why Use Encryption?
Encryption transforms readable data (plaintext) into a scrambled format (ciphertext) that can only be read if decrypted with the correct key. This ensures that even if someone intercepts the encrypted data, it remains meaningless without the key. A solid encryption mechanism protects:
- API keys stored in your frontend code.
- Sensitive user information.
- Any data transferred over insecure channels.
Let’s dive into how you can implement this securely in JavaScript.
Encryption and Decryption Using AES-GCM
We’ll use AES-GCM (Advanced Encryption Standard - Galois/Counter Mode), a modern standard that provides both encryption and integrity verification. The steps involve:
- Password Derivation: Use PBKDF2 (Password-Based Key Derivation Function 2) to derive a secure key from a password.
- Salt and IV: Generate a random salt (to make the password derivation unique) and iv (Initialization Vector) for each encryption.
- Encryption: Encrypt the plaintext using AES-GCM.
- Decryption: Decrypt the ciphertext using the same password and salt/iv.
Code Implementation
Here is the complete JavaScript implementation.
Utilities for Conversion
We’ll convert between ArrayBuffer and hexadecimal for easy data storage and retrieval:
function arrayBufferToHex(buffer) { return [...new Uint8Array(buffer)] .map(byte => byte.toString(16).padStart(2, '0')) .join(''); } function hexToArrayBuffer(hex) { const bytes = new Uint8Array(hex.length / 2); for (let i = 0; i <h3> Key Derivation from Password </h3> <p>Use PBKDF2 to derive a strong encryption key:<br> </p> <pre class="brush:php;toolbar:false">async function getCryptoKey(password) { const encoder = new TextEncoder(); const keyMaterial = encoder.encode(password); return crypto.subtle.importKey( 'raw', keyMaterial, { name: 'PBKDF2' }, false, ['deriveKey'] ); } async function deriveKey(password, salt) { const keyMaterial = await getCryptoKey(password); return crypto.subtle.deriveKey( { name: 'PBKDF2', salt: salt, iterations: 100000, hash: 'SHA-256' }, keyMaterial, { name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt'] ); }
Encryption Function
Encrypt text with a password:
async function encryptText(text, password) { const encoder = new TextEncoder(); const salt = crypto.getRandomValues(new Uint8Array(16)); const iv = crypto.getRandomValues(new Uint8Array(12)); const key = await deriveKey(password, salt); const encrypted = await crypto.subtle.encrypt( { name: 'AES-GCM', iv: iv }, key, encoder.encode(text) ); return { cipherText: arrayBufferToHex(encrypted), iv: arrayBufferToHex(iv), salt: arrayBufferToHex(salt) }; }
Decryption Function
Decrypt text with the same password:
async function decryptText(encryptedData, password) { const { cipherText, iv, salt } = encryptedData; const key = await deriveKey(password, hexToArrayBuffer(salt)); const decrypted = await crypto.subtle.decrypt( { name: 'AES-GCM', iv: hexToArrayBuffer(iv) }, key, hexToArrayBuffer(cipherText) ); const decoder = new TextDecoder(); return decoder.decode(decrypted); }
Example Usage
Let’s see how to use these functions:
function arrayBufferToHex(buffer) { return [...new Uint8Array(buffer)] .map(byte => byte.toString(16).padStart(2, '0')) .join(''); } function hexToArrayBuffer(hex) { const bytes = new Uint8Array(hex.length / 2); for (let i = 0; i <hr> <h2> Security Best Practices </h2> <ol> <li> <strong>Use a Strong Password</strong>: The encryption is only as secure as the password you use.</li> <li> <strong>Store Salt and IV Safely</strong>: Always save the salt and iv alongside your encrypted data.</li> <li> <strong>Avoid Hardcoding Secrets</strong>: Never hardcode sensitive data or passwords in your codebase.</li> <li> <strong>Use HTTPS</strong>: Ensure your application uses HTTPS to protect data in transit.</li> </ol> <hr> <p>Encrypting sensitive information like API keys is a fundamental step in securing your applications. I use this for API keys mostly.</p>
The above is the detailed content of Secure Text Encryption and Decryption with Vanilla JavaScript. For more information, please follow other related articles on the PHP Chinese website!

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver Mac version
Visual web development tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools
