import { Injectable, InternalServerErrorException } from '@nestjs/common'; import * as crypto from 'crypto'; const CryptoJS = require('crypto-js'); const encryptionType = 'aes-256-cbc'; @Injectable() export class EncryptUtilService { constructor() {} static encryptGCM(data: any, Datakey: string, Dataiv: string) { try { const cipher = crypto.createCipheriv('aes-256-gcm', Datakey, Dataiv); const encrypted = Buffer.concat([ cipher.update(data, 'utf8'), cipher.final(), ]); const tag = cipher.getAuthTag(); return Buffer.concat([encrypted, tag]).toString('base64'); } catch (error) { throw new InternalServerErrorException('Encryption process failed'); } } static decryptGCM(data: any, Datakey: any, Dataiv: any) { try { data = Buffer.from(data, 'base64'); const decipher = crypto.createDecipheriv('aes-256-gcm', Datakey, Dataiv); const tag = data.slice(data.length - 16); decipher.setAuthTag(tag); data = data.slice(0, data.length - 16); const decrypted = decipher.update(data, 'utf8') + decipher.final('utf8'); return decrypted; } catch (error) { throw new InternalServerErrorException('Decryption process failed'); } } static encryptCBC(data: any, Datakey: any, Dataiv: any) { let encryptedRequest; try { const cipher = CryptoJS.AES.encrypt(data, Datakey, { iv: Dataiv, mode: CryptoJS.mode.CBC, }); encryptedRequest = cipher.toString(); } catch (error) { console.log(error); throw new InternalServerErrorException('Encryption process failed'); } return encryptedRequest; } static decryptCBC(data: any, Datakey: any, Dataiv: any) { let decryptRequest; try { const cipher = CryptoJS.AES.decrypt(data, Datakey, { iv: Dataiv, mode: CryptoJS.mode.CBC, }); decryptRequest = cipher.toString(CryptoJS.enc.Utf8); } catch (error) { throw new InternalServerErrorException('Encryption process failed'); } return decryptRequest; } static encryptRequest(data: any, Datakey: any, Dataiv: any, type?: any) { try { switch (type) { case 'GCM': return this.encryptGCM(data, Datakey, Dataiv); case 'CBC': return this.encryptCBC(data, Datakey, Dataiv); default: return this.encryptCBC(data, Datakey, Dataiv); } } catch (error) { throw new InternalServerErrorException('Encryption process failed'); } } static decryptRequest(data: any, Datakey: any, Dataiv: any, type?: any) { try { switch (type) { case 'GCM': return this.decryptGCM(data, Datakey, Dataiv); case 'CBC': return this.decryptCBC(data, Datakey, Dataiv); default: return this.decryptCBC(data, Datakey, Dataiv); } } catch (error) { throw new InternalServerErrorException('Encryption process failed'); } } }