node.js - 节点js中的Image_Encryption
问题描述
*我也在尝试通过下面的代码加密和解密图像和其他文件。下面的代码可以加密和解密文件但不是图像有人可以帮我加密和解密图像吗?我尝试了各种方法,包括将图像转换为另一种文件格式,但它不起作用*
const crypto = require("crypto");
const fs = require("fs");
// encryption algorithm
const algorithm = "aes-256-ctr";
// secret key for increption
let key = "SecretKey";
key = crypto.createHash("sha256").update(String(key)).digest("base64").substr(0, 32);
// gives the result on the hash (digest)
/**
* encrypt
* @param {*} buffer
* @returns all the buffer objects in an array into one buffer object.
*/
const encrypt = (buffer) => {
const iv = crypto.randomBytes(16);
// creating new cipher using the algorithm, key, iv
const cipher = crypto.createCipheriv(algorithm, key, iv);
// creating new encrypted buffer
const result = Buffer.concat([iv, cipher.update(buffer), cipher.final()]);
return result;
};
/**
* decrypt
* @param {*} encrypted
* @returns
*/
const decrypt = (encrypted) => {
const iv = encrypted.slice(0, 16);
encrypted = encrypted.slice(16);
// create decipher
const decipher = crypto.createDecipheriv(algorithm, key, iv);
// decrypt it
const result = Buffer.concat([iv, decipher.update(encrypted), decipher.final()]);
return result;
};
// the code below is for encryption
// fs.readFile("./sun.jpg", (err, file) => {
// if (err) return console.log(err.message);
// console.log("current file data ====>", file);
// // encrypt the file data
// const encryptedFile = encrypt(file);
// // flow the encrypted file data to the new file
// fs.writeFile("./sun.jpg", encryptedFile, (err, file) => {
// if (err) return console.log(err.message);
// if (file) {
// console.log("File encrypted sucessfully");
// }
// });
// });
fs.readFile("./sun.jpg", (err, file) => {
if (err) return console.error(err.message);
// decrypt the file data
if (file) {
const decryptedFile = decrypt(file);
fs.writeFile("./sun.jpg", decryptedFile, (err, file) => {
if (err) return console.log(err.message);
if (file) {
console.log("File decrypted sucessfully");
}
});
console.log(decryptedFile.toString());
}
});
解决方案
推荐阅读
- ios - 如何将 cvPixelBuffer 裁剪到 CGRect 的边界?
- sql - 从一张表中查询count(*)时显示0
- html - Font Awesome 5.12.1:品牌图标被渲染,但实体图标不被渲染
- python - “IndentationError:意外缩进”尝试从文本编辑器复制并粘贴到终端时
- python - Spacy:OSError:[E050] 在 Google Colab 上找不到模型 | Python
- sql - 对于每位员工,他们被推荐了多少次酌情加薪?
- spring-boot - Apache Camel Spring Boot - 处理路由后优雅关闭应用程序
- c# - 如何为 Razor Pages (.NET Core) 绑定视图模型?
- powerbi - 您如何使用数据分析表达式 (DAX) 根据年份的周数对数字进行排名?
- java - Ubuntu (Java Card - ISO7816) 上的智能卡模拟 - 指定目标 JCRE