我试图在从 mongoDb 收到数据后解密数据。从数据库接收到的数据,其中一部分是加密的,其余部分不是。
app.get("/recieve", async (req, res) => {
try {
const data = await UploadData.find();
const decryptedData = data.map((item) => {
const decryptedFullName = decryptData(item.fullname, secretKey);
const decryptedCatName = decryptData(item.catName, secretKey);
const decryptedEmail = decryptData(item.email, secretKey);
const decryptedContact = decryptData(item.contact, secretKey);
const decryptedLocation = decryptData(item.location, secretKey);
return {
...item.toObject(),
fullname: decryptedFullName,
catName: decryptedCatName,
email: decryptedEmail,
contact: decryptedContact,
location: decryptedLocation,
};
});
res.json(decryptedData);
} catch (error) {
console.error("Error fetching data:", error);
res.status(500).json({ error: "Internal server error" });
}
});
这是更新解密函数:
function decryptData(encryptedData, key) {
try {
const buff = Buffer.from(encryptedData, "base64");
encryptedData = buff.toString("utf-8");
var decipher = crypto.createDecipheriv("aes-256-cbc", key, iv);
return (
decipher.update(encryptedData, "base64", "utf8") +
decipher.final("utf8")
);
} catch (error) {
console.log("Error decrypting data:", error);
return null;
}
}
如果您想了解我更新如何加密我的数据,这里是函数代码:
function encryptData(data, key) {
console.log("Encrypted called");
const keyBuffer = Buffer.from(key, "hex");
const cipher = crypto.createCipheriv("aes-256-cbc", keyBuffer, iv);
let encryptedData =
cipher.update(data, "utf8", "base64") + cipher.final("base64");
return Buffer.from(encryptedData).toString("base64");
}
这就是我创建 iv 和 key 的方式。
const crypto = require("crypto");
const secretKey = crypto.randomBytes(32);
const iv = crypto.randomBytes(8).toString("hex");
使用最新更新,我收到错误解密错误
对于解密,必须使用与加密相同的 IV。您(最初)发布的代码并非如此,这是问题的原因。
通常,每次加密都会生成一个随机 IV(这样使用同一密钥的多次加密就不会导致密钥/IV 对的重复使用,这将是一个漏洞)。生成的IV与密文连接起来,以这种方式传递到解密端。由于 IV 不是秘密,因此其泄露不会造成安全问题。
解密时,根据已知的IV长度将IV和密文分开。
NodeJS 的 crypto 模块的示例实现是:
const crypto = require("crypto");
function encryptData(plaintext, key) {
const iv = crypto.randomBytes(16); // generate a random IV for each encryption
const cipher = crypto.createCipheriv("aes-256-cbc", key, iv);
return Buffer.concat([iv, cipher.update(plaintext, "utf8"), cipher.final()]).toString("base64"); // encrypt, concatenate IV and ciphertext
}
function decryptData(ciphertextB64, key) {
const ivCiphertext = Buffer.from(ciphertextB64, "base64");
const iv = ivCiphertext.subarray(0, 16); // separate IV...
const ciphertext = ivCiphertext.subarray(16); // ...and ciphertext
const decipher = crypto.createDecipheriv("aes-256-cbc", key, iv);
return Buffer.concat([decipher.update(ciphertext), decipher.final()]).toString("utf8"); // decrypt
}
const key = crypto.randomBytes(32); // apply a random byte sequence as key
const encryptedData = encryptData("The quick brown fox jumps over the lazy dog", key);
const decryptedData = decryptData(encryptedData, key);
console.log(decryptedData); // The quick brown fox jumps over the lazy dog