-
-
Save jtmthf/ff2f8ab100ecf71364775e1fd9c296f6 to your computer and use it in GitHub Desktop.
Simple String Encryption & Decryption with Node.js
This file contains 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 {createCipheriv, createDecipheriv} from "crypto"; | |
const ALGORITHM = "aes-256-cbc"; | |
const ENCODING = "utf8"; | |
const DEFAULT_INITIALIZATION_VECTOR = "0"; | |
const DEFAULT_SYMMETRIC_KEY = "d6F3Efeq"; | |
function encrypt(value: string, key = DEFAULT_SYMMETRIC_KEY, iv = DEFAULT_INITIALIZATION_VECTOR) { | |
const cipher = crypto.createCipheriv(ALGORITHM, key, iv); | |
let crypted = cipher.update(value, ENCODING, "base64"); | |
crypted += cipher.final("base64"); | |
return crypted; | |
} | |
function decrypt(value: string, key = DEFAULT_SYMMETRIC_KEY, iv = DEFAULT_INITIALIZATION_VECTOR) { | |
const decipher = crypto.createDecipheriv(ALGORITHM, key, iv); | |
let dec = decipher.update(value, "base64", ENCODING); | |
dec += decipher.final(ENCONDING); | |
return dec; | |
} | |
const hw = encrypt("hello world"); | |
decrypt(hw); | |
// feel free to change >> d6F3Efeq | |
// To test just copy + paste the above inside the node shell | |
// TIP: always encrypt IDs before sending via HTTP |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
#L18 typo:
ENCONDING
should beENCODING