Skip to content

Instantly share code, notes, and snippets.

@maxktz
Created September 12, 2024 08:57
Show Gist options
  • Save maxktz/1be6d7dcc09560266ea44aba14d5d1a8 to your computer and use it in GitHub Desktop.
Save maxktz/1be6d7dcc09560266ea44aba14d5d1a8 to your computer and use it in GitHub Desktop.
JS/TS encrypt string with password using AES and decrypt methods
import crypto from "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