Skip to content

Instantly share code, notes, and snippets.

@elranu
Forked from ChaoLiangSuper/encryption.ts
Created August 23, 2023 19:59
Show Gist options
  • Save elranu/5fdc98fb0125421be062691037a1220b to your computer and use it in GitHub Desktop.
Save elranu/5fdc98fb0125421be062691037a1220b 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