Skip to content

Instantly share code, notes, and snippets.

@jtmthf
Forked from csanz/encrypt_decrypt.js
Last active April 18, 2021 13:20
Show Gist options
  • Save jtmthf/ff2f8ab100ecf71364775e1fd9c296f6 to your computer and use it in GitHub Desktop.
Save jtmthf/ff2f8ab100ecf71364775e1fd9c296f6 to your computer and use it in GitHub Desktop.
Simple String Encryption & Decryption with Node.js
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
@knulpi
Copy link

knulpi commented Apr 18, 2021

#L18 typo: ENCONDING should be ENCODING

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment