首页 > 解决方案 > 节点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());
  }
});

标签: node.jsreactjs

解决方案


推荐阅读