Explain Codes LogoExplain Codes Logo

Javascript string encryption and decryption?

javascript
prompt-engineering
security
crypto
Alex KataevbyAlex Kataev·Feb 27, 2025
TLDR

For secure encryption and decryption in JavaScript, you can use AES-GCM available in the Web Crypto API.

Check out this example:

async function encryptDecrypt(message, password) { const enc = new TextEncoder(); const dec = new TextDecoder(); // Presto! We have salt! const salt = window.crypto.getRandomValues(new Uint8Array(16)); // Knock knock! Who's there? IV. const iv = window.crypto.getRandomValues(new Uint8Array(12)); // Password to the rescue! const key = await window.crypto.subtle.importKey( 'raw', enc.encode(password), 'PBKDF2', false, ['deriveBits', 'deriveKey'] ).then(keyMaterial => window.crypto.subtle.deriveKey( { name: 'PBKDF2', salt: salt, iterations: 100000, hash: 'SHA-256' }, keyMaterial, { name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt'] ) ); // Encrypt a.k.a "Make it mysterious!" const encrypted = await window.crypto.subtle.encrypt( { name: 'AES-GCM', iv: iv }, key, enc.encode(message) ); // Decrypt a.k.a "I've got the power to understand!" const decrypted = await window.crypto.subtle.decrypt( { name: 'AES-GCM', iv: iv }, key, encrypted ); return { encrypted: new Uint8Array(encrypted), decrypted: dec.decode(decrypted) }; } // Here goes nothing! encryptDecrypt('Hello, world!', 'my-secret').then(result => { console.log(`Encrypted: ${result.encrypted}`); console.log(`Decrypted: ${result.decrypted}`); });

Takeaway: Use a unique IV and salt every time like they're going out of style. AES-GCM is reliable and secure. TextEncoder and TextDecoder are your best friends when it comes to encoding and decoding.

Step into the Security Spotlight

Encrypting a string? Don't go in without a battle plan! Use a unique IV (Initialization Vector) and a salt so random it'll surprise you. You want your encryption to hold up under pressure!

Haus of UTF-8

Keep an eye on your UTF-8 characters. Keep them consistent to dodge those pesky Unicode issues.

Staying on the Cutting Edge of Crypto

Security's not static, it's dynamic! Don't stick with CryptoJS. Instead, strut down the cryptographic runway with libsodium or SodiumPlus.

Don't Call It a Cipher

If you don't need heavy-duty security, a simple XOR cipher with a side of secret key might do the trick:

// XOR, report for duty! function simpleEncryptDecrypt(input, secret) { let output = ''; for (let i = 0; i < input.length; i++) { // "Say my secret name!" — XOR probably output += String.fromCharCode(input.charCodeAt(i) ^ secret.charCodeAt(i % secret.length)); } return output; } // Honey, I encrypted the text! const originalText = 'Just a test!'; const secret = 'mySecretKey'; const encryptedText = simpleEncryptDecrypt(originalText, secret); const decryptedText = simpleEncryptDecrypt(encryptedText, secret); console.log(decryptedText); // 'Just a test!'

While this XOR cipher isn't top-tier secure, it's sometimes just the right fit. Just remember to guard that secret key with your life!

Face the Music: Client-Side Limitations and Dangers

Casting a client-side encryption spell? It's not foolproof. Always anticipate a trap!

What Not to Do:

  • Treating encryption keys and passwords as if they're literally unspoilable milk? Nope!
  • Using CryptoJS's default CBC mode as if it's the most secure thing in the world? Next!
  • Believing SJCL is uncompromisable because it accepts passwords? Can't relate!
  • Putting all your trust in WebCrypto API? Well, think again!

Setting up the Perfect Security System

What's an encryption without a decryption? A night without stars.

Perfect Pair: Encryption and Purpose:

  • Protect PII: Dress your Data with the finest encryption
  • Secure communications: Whisper secret messages with encryption's help
  • Storing sensitive data: Trust encryption to guard the treasure

Double Duty: Decryption and Integrity Checks

  • Authenticity: How do we trust the decrypted data? Built-in integrity checks!
  • Digital signatures: Confirm the source of the secret message