Created
March 29, 2023 00:48
-
-
Save douglas-henrique/cd57736644af73b8b17bf99d164a6a16 to your computer and use it in GitHub Desktop.
Code to encrypt and decrypt strings using node crypto
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"; | |
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