Viewing File: /home/ubuntu/efiexchange-node-base/src/utils/decrypt.ts
import crypto from 'crypto';
import { Request, Response } from 'express';
export const decrypt = async (encrypted: string, key: string, iv: string) => {
try {
const encryptedBuffer = Buffer.from(encrypted, 'hex');
const keyBuffer = Buffer.from(key, 'hex');
const ivBuffer = Buffer.from(iv, 'hex');
if (keyBuffer.length !== 32) throw new Error('Key must be 32 bytes');
if (ivBuffer.length !== 16) throw new Error('IV must be 16 bytes');
const decipher = crypto.createDecipheriv('aes-256-cbc', keyBuffer, ivBuffer);
let decrypted = decipher.update(encryptedBuffer, undefined, 'utf8');
decrypted += decipher.final('utf8');
return decrypted;
} catch (err) {
console.error('Decryption failed:', err.message);
return null;
}
};
export const encrypt = async (req: Request, res: Response) => {
try {
const algorithm = 'aes-256-cbc';
const key = crypto.randomBytes(32); // 256-bit key
const iv = crypto.randomBytes(16); // 128-bit IV
const cipher = crypto.createCipheriv(algorithm, key, iv);
let encrypted = cipher.update(req.body.text, 'utf-8', 'hex');
encrypted += cipher.final('hex');
return res.sendResponse({ encrypted, key: key.toString('hex'), iv: iv.toString('hex') }, '200');
} catch (error: any) {
return res.sendError(error.message);
}
}
Back to Directory
File Manager