48 lines
1.2 KiB
TypeScript
48 lines
1.2 KiB
TypeScript
import crypto from 'crypto';
|
|
import { CLIENT_SECRET } from '../constants';
|
|
|
|
const IV_LENGTH = 16;
|
|
const ALGORITHM = 'aes-256-cbc';
|
|
|
|
export const generateString = (length: number): string =>
|
|
crypto.randomBytes(length).toString('hex').slice(0, length);
|
|
|
|
// https://stackoverflow.com/q/52212430
|
|
/**
|
|
* Symmetric encryption function
|
|
* @param value String to encrypt
|
|
* @returns Encrypted text
|
|
*/
|
|
export const encrypt = (value: string) => {
|
|
const iv = crypto.randomBytes(IV_LENGTH);
|
|
const cipher = crypto.createCipheriv(
|
|
ALGORITHM,
|
|
Buffer.from(CLIENT_SECRET, 'hex'),
|
|
iv
|
|
);
|
|
let encrypted = cipher.update(value);
|
|
encrypted = Buffer.concat([encrypted, cipher.final()]);
|
|
return `${iv.toString('hex')}:${encrypted.toString('hex')}`;
|
|
};
|
|
|
|
/**
|
|
* Symmetric decryption function
|
|
* @param text Encrypted string
|
|
* @returns Decrypted text
|
|
*/
|
|
export const decrypt = (text: string) => {
|
|
const [iv, encryptedText] = text
|
|
.split(':')
|
|
.map((part) => Buffer.from(part, 'hex'));
|
|
|
|
const decipher = crypto.createDecipheriv(
|
|
ALGORITHM,
|
|
Buffer.from(CLIENT_SECRET, 'hex'),
|
|
iv
|
|
);
|
|
|
|
let decrypted = decipher.update(encryptedText);
|
|
decrypted = Buffer.concat([decrypted, decipher.final()]);
|
|
return decrypted.toString();
|
|
};
|