initial commit
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
35
src/utils/encryption.ts
Normal file
35
src/utils/encryption.ts
Normal file
@@ -0,0 +1,35 @@
|
||||
import crypto from 'crypto';
|
||||
import { config } from '../config/env';
|
||||
|
||||
const ALGORITHM = 'aes-256-gcm';
|
||||
const IV_LENGTH = 12;
|
||||
const TAG_LENGTH = 16;
|
||||
|
||||
export function encrypt(plaintext: string): string {
|
||||
const key = Buffer.from(config.totp.encryptionKey, 'hex');
|
||||
const iv = crypto.randomBytes(IV_LENGTH);
|
||||
const cipher = crypto.createCipheriv(ALGORITHM, key, iv);
|
||||
|
||||
let encrypted = cipher.update(plaintext, 'utf8', 'hex');
|
||||
encrypted += cipher.final('hex');
|
||||
const tag = cipher.getAuthTag();
|
||||
|
||||
return iv.toString('hex') + ':' + encrypted + ':' + tag.toString('hex');
|
||||
}
|
||||
|
||||
export function decrypt(ciphertext: string): string {
|
||||
const key = Buffer.from(config.totp.encryptionKey, 'hex');
|
||||
const parts = ciphertext.split(':');
|
||||
if (parts.length !== 3) throw new Error('Invalid ciphertext format');
|
||||
|
||||
const iv = Buffer.from(parts[0], 'hex');
|
||||
const encrypted = parts[1];
|
||||
const tag = Buffer.from(parts[2], 'hex');
|
||||
|
||||
const decipher = crypto.createDecipheriv(ALGORITHM, key, iv);
|
||||
decipher.setAuthTag(tag);
|
||||
|
||||
let decrypted = decipher.update(encrypted, 'hex', 'utf8');
|
||||
decrypted += decipher.final('utf8');
|
||||
return decrypted;
|
||||
}
|
||||
Reference in New Issue
Block a user