Files
TurboHR/backend/src/lib/crypto.ts
T

27 lines
961 B
TypeScript

import crypto from 'crypto'
const ENCRYPTION_KEY = process.env.ENCRYPTION_KEY || 'default-32-byte-encryption-key!!'
const ALGORITHM = 'aes-256-cbc'
const KEY = Buffer.from(ENCRYPTION_KEY.padEnd(32, '0').slice(0, 32), 'utf8')
export function encrypt(text: string): string {
const iv = crypto.randomBytes(16)
const cipher = crypto.createCipheriv(ALGORITHM, KEY, iv)
let encrypted = cipher.update(text, 'utf8', 'hex')
encrypted += cipher.final('hex')
return iv.toString('hex') + ':' + encrypted
}
export function decrypt(encryptedText: string): string {
const [ivHex, encrypted] = encryptedText.split(':')
const iv = Buffer.from(ivHex, 'hex')
const decipher = crypto.createDecipheriv(ALGORITHM, KEY, iv)
let decrypted = decipher.update(encrypted, 'hex', 'utf8')
decrypted += decipher.final('utf8')
return decrypted
}
export function sha256(text: string): string {
return crypto.createHash('sha256').update(text, 'utf8').digest('hex')
}