I'm working on REST API Data encryption in Node.js. I've been trying to encrypt the Json data from the API endpoint and use the data in the UI modules by decrypting it. What is the possible solution are there any guides please share accordingly.
I Tried Node Crypto Module, createcipheriv Method it was able to encrypt the data, but not able to decrypt to use in the ui Modules.
I want to use the Key and IV from env and use the same key and IV to decrypt the data and use in the UI modules.
import { createCipheriv,randomBytes, createDecipheriv } from 'crypto';
const key = randomBytes(32);
const iv = randomBytes(16);
export const encrypt = (jsonData : Object) => {
const cipher = createCipheriv('aes-256-cbc', key, iv)
const jsonBuffer = Buffer.from(JSON.stringify(jsonData))
const encryptedBuffer = Buffer.concat([cipher.update(jsonBuffer),cipher.final()])
const encryptedString = encryptedBuffer.toString('base64')
return encryptedString
}
export const decrypt = (encryptedString : string) => {
const encryptedBuffer = Buffer.from(encryptedString, 'base64')
const decipher = createDecipheriv('aes-256-cbc', key, iv)
const decryptedBuffer = Buffer.concat([decipher.update(encryptedBuffer),decipher.final()])
const decryptedString = decryptedBuffer.toString()
return decryptedString
}