73 lines
1.9 KiB
TypeScript
73 lines
1.9 KiB
TypeScript
import * as crypto from 'crypto';
|
|
|
|
export class EncryptionHelper {
|
|
private static readonly algorithm = 'aes-256-cbc';
|
|
private static readonly secretKey = crypto.scryptSync(
|
|
'sales-price-formula-secret',
|
|
'salt',
|
|
32,
|
|
);
|
|
|
|
/**
|
|
* Encrypts a string using AES-256-CBC algorithm
|
|
* @param text - The string to encrypt
|
|
* @returns Encrypted string in format: iv:encryptedData
|
|
*/
|
|
static encrypt(text: string): string {
|
|
if (!text) {
|
|
return '';
|
|
}
|
|
|
|
const iv = crypto.randomBytes(16);
|
|
const cipher = crypto.createCipheriv(this.algorithm, this.secretKey, iv);
|
|
let encrypted = cipher.update(text, 'utf8', 'hex');
|
|
encrypted += cipher.final('hex');
|
|
|
|
return `${iv.toString('hex')}:${encrypted}`;
|
|
}
|
|
|
|
/**
|
|
* Decrypts a string that was encrypted using the encrypt method
|
|
* @param encryptedText - The encrypted string in format: iv:encryptedData
|
|
* @returns Decrypted original string
|
|
*/
|
|
static decrypt(encryptedText: string): string {
|
|
if (!encryptedText) {
|
|
return '';
|
|
}
|
|
|
|
try {
|
|
const [ivHex, encrypted] = encryptedText.split(':');
|
|
if (!ivHex || !encrypted) {
|
|
throw new Error('Invalid encrypted text format');
|
|
}
|
|
|
|
const iv = Buffer.from(ivHex, 'hex');
|
|
const decipher = crypto.createDecipheriv(
|
|
this.algorithm,
|
|
this.secretKey,
|
|
iv,
|
|
);
|
|
let decrypted = decipher.update(encrypted, 'hex', 'utf8');
|
|
decrypted += decipher.final('utf8');
|
|
|
|
return decrypted;
|
|
} catch (error) {
|
|
throw new Error('Failed to decrypt data: Invalid encrypted text format');
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Generates a hash of the input string using SHA-256
|
|
* @param text - The string to hash
|
|
* @returns SHA-256 hash of the input string
|
|
*/
|
|
static hash(text: string): string {
|
|
if (!text) {
|
|
return '';
|
|
}
|
|
|
|
return crypto.createHash('sha256').update(text).digest('hex');
|
|
}
|
|
}
|