Skip to content

Instantly share code, notes, and snippets.

@douglas-henrique
Created March 29, 2023 00:48
Show Gist options
  • Save douglas-henrique/cd57736644af73b8b17bf99d164a6a16 to your computer and use it in GitHub Desktop.
Save douglas-henrique/cd57736644af73b8b17bf99d164a6a16 to your computer and use it in GitHub Desktop.
Code to encrypt and decrypt strings using node crypto
import crypto from "crypto";
const algorithm = "aes-256-cbc"; //Using AES encryption
const Securitykey = crypto.randomBytes(32);
const initVector = crypto.randomBytes(16);
export const encryptMessage = (message: string) => {
const cipher = crypto.createCipheriv(algorithm, Securitykey, initVector);
let encryptedData = cipher.update(message, "utf-8", "hex");
encryptedData += cipher.final("hex");
return encryptedData;
};
const decrypt = (encryptedMessage: string) => {
const decipher = crypto.createDecipheriv(algorithm, Securitykey, initVector);
let decryptedData = decipher.update(encryptedMessage, "hex", "utf-8");
decryptedData += decipher.final("utf8");
return decryptedData
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment