Skip to content

Instantly share code, notes, and snippets.

@maxktz
Last active May 17, 2025 15:54
Show Gist options
  • Save maxktz/5ee283468dfee493c6ce9890688cd98f to your computer and use it in GitHub Desktop.
Save maxktz/5ee283468dfee493c6ce9890688cd98f to your computer and use it in GitHub Desktop.
JS TS module to encrypt and decrypt string with password, using AES, 256bit salt, and 128 bit init vector.
import crypto from "crypto"; // npm i crypto
/** Helper function to generate a random salt */
export function generateSalt(length: number = 32): string {
return crypto.randomBytes(length).toString("hex");
}
/** Derive a key from a password and salt */
export function deriveKey(password: string, salt: string): Buffer {
return crypto.pbkdf2Sync(password, salt, 100000, 32, "sha256");
}
/** Encrypt a string using AES, returns string "salt32:iv16:encrypted"*/
export function encryptString(str: string, password: string): string {
const salt = generateSalt();
const key = deriveKey(password, salt);
const iv = crypto.randomBytes(16); // Initialization Vector
const cipher = crypto.createCipheriv("aes-256-cbc", key, iv);
let encrypted = cipher.update(str, "utf8", "hex");
encrypted += cipher.final("hex");
return `${salt}:${iv.toString("hex")}:${encrypted}`;
}
/** Decrypt a string using AES */
export function decryptString(str: string, password: string): string {
const [salt, ivHex, encrypted] = str.split(":");
const key = deriveKey(password, salt);
const iv = Buffer.from(ivHex, "hex");
const decipher = crypto.createDecipheriv("aes-256-cbc", key, iv);
let decrypted = decipher.update(encrypted, "hex", "utf8");
decrypted += decipher.final("utf8");
return decrypted;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment