如何在 NodeJS 中使用 public 密钥仅加密 JSON 负载的选定值?
How do I encrypt only selected values of a JSON payload using a public key in NodeJS?
示例负载:
"object": {
"a": "bau bau",
"c": "boo boo",
"e": "mrau mrau"
},
加密有效载荷:
"object": {
"a": "kjdfhsijry874rhevfbwe",
"c": "boo boo",
"e": "vcsafsdkhdlksfhj23273"
},
我已经创建了以下脚本,但即使我正在传递字符串,也会出现错误。
错误: 类型错误:第一个参数必须是字符串、缓冲区、数组缓冲区、数组或类似数组的对象。
const crypto = require('crypto');
const path = require('path');
const fs = require('fs');
const payload = require('./payload.json');
console.log("original:", payload);
const encrypted = encryptedJSON(payload, './public.pem', ["a", "e"]);
console.log("encrypted:", encrypted);
function encryptedJSON(obj, key, propertiesToEncrypt) {
let result = { ...obj }; // Clone the object.
const publicKey = fs.readFileSync(path.resolve(key), "utf8");
for(let property of propertiesToEncrypt) {
result[property] = crypto.publicEncrypt({ key: publicKey }, Buffer.from(obj[property], "utf8")).toString("base64");
}
return result;
}
您的代码 对于 payload.json
的这种格式是正确的:
{
"a": "bau bau",
"c": "boo boo",
"e": "mrau mrau"
}
但是这个会失败:
{
"object": {
"a": "bau bau",
"c": "boo boo",
"e": "mrau mrau"
}
}
因为它试图加密不存在的顶级 属性 "a"(唯一的 属性 是 "object")。
如果您的负载遵循后一种格式,您可以像这样调整您的代码:
const encrypted = encryptedJSON(payload.object, './public.pem', ["a", "e"]);
示例负载:
"object": {
"a": "bau bau",
"c": "boo boo",
"e": "mrau mrau"
},
加密有效载荷:
"object": {
"a": "kjdfhsijry874rhevfbwe",
"c": "boo boo",
"e": "vcsafsdkhdlksfhj23273"
},
我已经创建了以下脚本,但即使我正在传递字符串,也会出现错误。 错误: 类型错误:第一个参数必须是字符串、缓冲区、数组缓冲区、数组或类似数组的对象。
const crypto = require('crypto');
const path = require('path');
const fs = require('fs');
const payload = require('./payload.json');
console.log("original:", payload);
const encrypted = encryptedJSON(payload, './public.pem', ["a", "e"]);
console.log("encrypted:", encrypted);
function encryptedJSON(obj, key, propertiesToEncrypt) {
let result = { ...obj }; // Clone the object.
const publicKey = fs.readFileSync(path.resolve(key), "utf8");
for(let property of propertiesToEncrypt) {
result[property] = crypto.publicEncrypt({ key: publicKey }, Buffer.from(obj[property], "utf8")).toString("base64");
}
return result;
}
您的代码 对于 payload.json
的这种格式是正确的:
{
"a": "bau bau",
"c": "boo boo",
"e": "mrau mrau"
}
但是这个会失败:
{
"object": {
"a": "bau bau",
"c": "boo boo",
"e": "mrau mrau"
}
}
因为它试图加密不存在的顶级 属性 "a"(唯一的 属性 是 "object")。 如果您的负载遵循后一种格式,您可以像这样调整您的代码:
const encrypted = encryptedJSON(payload.object, './public.pem', ["a", "e"]);