24 lines
845 B
TypeScript
24 lines
845 B
TypeScript
import { Service } from "@tsed/di";
|
|
import crypto from "crypto";
|
|
|
|
@Service()
|
|
export class EncryptionService {
|
|
private algorithm = 'aes-256-cbc';
|
|
private key = crypto.randomBytes(32);
|
|
|
|
async encrypt(text: string): Promise<{ encryptedText: string; iv: string }> {
|
|
const iv = crypto.randomBytes(16);
|
|
const cipher = crypto.createCipheriv(this.algorithm, this.key, iv);
|
|
let encrypted = cipher.update(text, 'utf8', 'hex');
|
|
encrypted += cipher.final('hex');
|
|
return { encryptedText: encrypted, iv: iv.toString('hex') };
|
|
}
|
|
|
|
async decrypt(encryptedText: string, iv: string): Promise<string> {
|
|
const decipher = crypto.createDecipheriv(this.algorithm, this.key, Buffer.from(iv, 'hex'));
|
|
let decrypted = decipher.update(encryptedText, 'hex', 'utf8');
|
|
decrypted += decipher.final('utf8');
|
|
return decrypted;
|
|
}
|
|
}
|