UNPKG

@mahdi.golzar/encripttool

Version:

EncryptionTool is a simple utility for encrypting and decrypting data using symmetric encryption algorithms. It provides an easy interface to securely encrypt sensitive data and later decrypt it.

28 lines (25 loc) 1 kB
import crypto from 'crypto'; class EncryptionTool { constructor(algorithm = 'aes-256-cbc', key) { if (!key) { throw new Error('A key is required'); } this.algorithm = algorithm; this.key = crypto.scryptSync(key, 'salt', 32) this.ivLength = 16 } encrypt(text) { const InitializationVector = crypto.randomBytes(this.ivLength) const cipher = crypto.createCipheriv(this.algorithm, this.key, InitializationVector) let encrypted = cipher.update(text, 'utf8', 'hex') encrypted += cipher.final('hex') return `${InitializationVector.toString('hex')}:${encrypted}`; } decrypt(encryptedText) { const [iv, encrypted] = encryptedText.split(':'); const decipher = crypto.createDecipheriv(this.algorithm, this.key, Buffer.from(iv, 'hex')); let decrypted = decipher.update(encrypted, 'hex', 'utf8'); decrypted += decipher.final('utf8'); return decrypted; } }