Spaces:
Sleeping
Sleeping
| const crypto = require('crypto'); | |
| /** | |
| * AES-256-CBC Decryption utility | |
| * Decrypts data encrypted with the frontend AES encrypt function | |
| */ | |
| function aesDecrypt(encryptedData) { | |
| try { | |
| const key = Buffer.from(process.env.KEY, 'utf8'); | |
| const iv = Buffer.from(process.env.IV, 'utf8'); | |
| // Create decipher | |
| const decipher = crypto.createDecipheriv('aes-256-cbc', key, iv); | |
| // Decrypt the data (encryptedData is base64 from CryptoJS) | |
| let decrypted = decipher.update(encryptedData, 'base64', 'utf8'); | |
| decrypted += decipher.final('utf8'); | |
| return decrypted; | |
| } catch (error) { | |
| console.error('Decryption error:', error.message); | |
| throw new Error('Failed to decrypt data'); | |
| } | |
| } | |
| /** | |
| * Decrypt personal information fields in an object | |
| * Only decrypts specified personal info fields | |
| */ | |
| function decryptPersonalInfo(data, fieldsToDecrypt = []) { | |
| const decryptedData = { ...data }; | |
| fieldsToDecrypt.forEach(field => { | |
| if (decryptedData[field] && typeof decryptedData[field] === 'string') { | |
| try { | |
| decryptedData[field] = aesDecrypt(decryptedData[field]); | |
| } catch (error) { | |
| console.error(`Failed to decrypt field: ${field}`); | |
| throw new Error(`Invalid encrypted data for field: ${field}`); | |
| } | |
| } | |
| }); | |
| return decryptedData; | |
| } | |
| module.exports = { aesDecrypt, decryptPersonalInfo }; | |