Last active
May 17, 2025 15:54
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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