json-crypto
Version:
Encrypt and decrypt JSON objects easily and safely
1 lines • 1.08 kB
JavaScript
const crypto=require("crypto"),fs=require("fs");function createCodec(stringKey){if("string"!=typeof stringKey)throw Error("Expected ciphertext to be of type: string");const key=crypto.createHash("sha256").update(stringKey).digest();return{encrypt:function(json){const iv=crypto.createHash("sha256").update(crypto.randomBytes(48).toString("hex")).digest(),resizedIV=Buffer.allocUnsafe(16);iv.copy(resizedIV);const cipher=crypto.createCipheriv("aes256",key,resizedIV),msg=[];return msg.push(cipher.update(JSON.stringify(json),"binary","hex")),msg.push(cipher.final("hex")),encodeURIComponent(JSON.stringify([resizedIV.toString("hex"),msg.join("")]))},decrypt:function(input){const[iv,ciphertext]=JSON.parse(decodeURIComponent(input)),bufferIV=Buffer.from(iv,"hex"),decipher=crypto.createDecipheriv("aes256",key,bufferIV),msg=[];return msg.push(decipher.update(ciphertext,"hex","binary")),msg.push(decipher.final("binary")),JSON.parse(msg.join(""))}}}function createKey(){return crypto.randomBytes(48).toString("hex")}module.exports={createCodec:createCodec,createKey:createKey};