123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105 |
- import crypto from "crypto";
- import fs from "node:fs";
- import SparkMD5 from "spark-md5";
- import environment from "#environment";
- export function createMD5(filePath) {
- return new Promise((res, rej) => {
- const hash = crypto.createHash("md5");
- const rStream = fs.createReadStream(filePath);
- rStream.on("data", (data) => {
- hash.update(data);
- });
- rStream.on("end", () => {
- res(hash.digest("hex"));
- });
- });
- }
- /**
- * 作者:起一个可以中奖的名字
- * 链接:https://juejin.cn/post/7142831050052665381
- * 来源:稀土掘金
- * 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
- * 计算文件Md5
- * 将文件分片逐步计算最终合并得出整个文件md5, 提升计算速度
- * @param {*} file
- */
- // export function computeFileMD5(file) {
- // return new Promise((resolve, reject) => {
- // let blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice;
- // let chunkSize = 2097152; // 按照一片 2MB 分片
- // let chunks = Math.ceil(file.size / chunkSize); // 片数
- // let currentChunk = 0;
- // let spark = new SparkMD5.ArrayBuffer();
- // let fileReader = new FileReader();
- // fileReader.onload = function (e) {
- // console.log('read chunk nr', currentChunk + 1, 'of', chunks);
- // spark.append(e.target.result);
- // currentChunk++;
- // if (currentChunk < chunks) {
- // loadNext();
- // } else {
- // console.log('finished loading');
- // let md5 = spark.end(); //最终md5值
- // spark.destroy(); //释放缓存
- // resolve(md5);
- // }
- // };
- // fileReader.onerror = function (e) {
- // console.warn('oops, something went wrong.');
- // reject(e);
- // };
- // function loadNext() {
- // let start = currentChunk * chunkSize;
- // const end = ((start + chunkSize) >= file.size) ? file.size : start + chunkSize;
- // fileReader.readAsArrayBuffer(blobSlice.call(file, start, end));
- // }
- // loadNext();
- // })
- // }
- //
- export function computeFileMD5(file) {
- return new Promise((resolve, reject) => {
- const hash = crypto.createHash("md5");
- // 直接将整个 Buffer 更新到 hash
- hash.update(file.data);
- // 计算哈希值
- const md5 = hash.digest("hex");
- resolve(md5);
- });
- }
- // 加密
- export function aes_encrypt(msg) {
- const aesInfo = environment.aes_info();
- const cipher = crypto.createCipheriv("aes-256-cbc", aesInfo.key, aesInfo.iv);
- // input encoding: utf8
- // output encoding: hex
- let encrypted = cipher.update(msg, "utf8", "hex");
- encrypted += cipher.final("hex");
- return encrypted;
- }
- // 解谜
- export function aes_decrypt(encrypted) {
- const aesInfo = environment.aes_info();
- const decipher = crypto.createDecipheriv(
- "aes-256-cbc",
- aesInfo.key,
- aesInfo.iv,
- );
- let decrypted = decipher.update(encrypted, "hex", "utf8");
- decrypted += decipher.final("utf8");
- return decrypted;
- }
|