UNPKG

@appveen/json-utils

Version:

Flatten object, unflatten object and find n level value and much more

37 lines (33 loc) 1.28 kB
const crypto = require('crypto'); const e = {}; e.encrypt = (data, secret) => { if (typeof data === 'object') { data = JSON.stringify(data); } const digestHash = crypto.createHash('sha256').update(secret).digest('hex'); const allocatedKey = Buffer.alloc(32, digestHash); const iv = crypto.randomBytes(IV_LENGTH); const cipher = crypto.createCipheriv('aes-256-cbc', allocatedKey, iv); let cipherText = cipher.update(data, 'utf-8', 'hex'); cipherText += cipher.final('hex'); cipherText = iv.toString('hex') + cipherText; return cipherText; }; e.decrypt = (data, secret) => { const digestHash = crypto.createHash('sha256').update(secret).digest('hex'); const allocatedKey = Buffer.alloc(32, digestHash); const bufferData = Buffer.from(data, 'hex'); const iv = bufferData.slice(0, IV_LENGTH); const textData = bufferData.slice(IV_LENGTH); const decipher = crypto.createDecipheriv('aes-256-cbc', allocatedKey, iv); let decipherText = decipher.update(textData, 'hex', 'utf-8'); decipherText += decipher.final('utf-8'); let returnValue; try { returnValue = JSON.parse(decipherText); } catch (e) { returnValue = decipherText; } return returnValue; }; module.exports = e;