Skip to content

Instantly share code, notes, and snippets.

@ChaoLiangSuper
Forked from vlucas/encryption.js
Last active March 24, 2024 14:30
Show Gist options
  • Save ChaoLiangSuper/0e13f77712b68682f0d8ebabb2d63aa8 to your computer and use it in GitHub Desktop.
Save ChaoLiangSuper/0e13f77712b68682f0d8ebabb2d63aa8 to your computer and use it in GitHub Desktop.
Stronger Encryption and Decryption in typescript
import crypto from 'crypto';
const ALGORITHM = 'aes-256-cbc';
const ENCODING = 'hex';
const IV_LENGTH = 16;
const KEY = process.env.ENCRYPTION_KEY!;
export const encrypt = (data: string) => {
const iv = crypto.randomBytes(IV_LENGTH);
const cipher = crypto.createCipheriv(ALGORITHM, new Buffer(KEY), iv);
return Buffer.concat([cipher.update(data,), cipher.final(), iv]).toString(ENCODING);
}
export const decrypt = (data: string) => {
const binaryData = new Buffer(data, ENCODING);
const iv = binaryData.slice(-IV_LENGTH);
const encryptedData = binaryData.slice(0, binaryData.length - IV_LENGTH);
const decipher = crypto.createDecipheriv(ALGORITHM, new Buffer(KEY), iv);
return Buffer.concat([decipher.update(encryptedData), decipher.final()]).toString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment