javascript - js中计算文件md5散列值的函数库

在前端开发中,往往需要上传文件到服务器,为了保证数据安全可靠,前端往往需要计算文件的md5摘要传递到服务器端进行验证。

1. Spark-md5

  • 安装
# npm 安装
npm install --save spark-md5
# yarn 安装
yarn add spark-md5
# pnpm 安装
pnpm add spark-md5
  • 基本使用
import SparkMD5 from 'spark-md5';
const hexHash = SparkMD5.hash('Hi there');     // 十六进制串
const rawHash = SparkMD5.hash('Hi there', true);  // 原始二进制串
  • 增量计算字符串md5
const spark = new SparkMD5();
spark.append('Hi');
spark.append(' there');
const hexHash = spark.end();                      // 十六进制
const rawHash = spark.end(true);                  // 原始二进制
  • 分片计算文件md5
document.getElementById('file').addEventListener('change', function () {
  // 获取文件对象分片方法,设置分片大小,文件读取对象
  var blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice,
      file = this.files[0],
      chunkSize = 2097152,                             // Read in chunks of 2MB
      chunks = Math.ceil(file.size / chunkSize),
      currentChunk = 0,
      spark = new SparkMD5.ArrayBuffer(),
      fileReader = new FileReader();

  // 读取分片成功时
  fileReader.onload = function (e) {
      console.log('read chunk nr', currentChunk + 1, 'of', chunks);
      spark.append(e.target.result);                   // Append array buffer
      currentChunk++;

      if (currentChunk < chunks) {
          loadNext();
      } else {
          console.log('finished loading');
          console.info('computed hash', spark.end());  // Compute hash
      }
  };

  // 读取分片失败时
  fileReader.onerror = function () {
      console.warn('oops, something went wrong.');
  };

  // 开始读取文件分片
  function loadNext() {
      var start = currentChunk * chunkSize,
          end = ((start + chunkSize) >= file.size) ? file.size : start + chunkSize;

      fileReader.readAsArrayBuffer(blobSlice.call(file, start, end));
  }

  loadNext();
});

2. blueimp-md5

用来计算字符串的md5值,无法处理二进制文件的md5, 可以通过加盐计算md5

  • 安装
npm install blueimp-md5
yarn add blueimp-md5
pnpm add blueimp-md5
  • MD5 hash (十六进制编码)
import md5 from "blueimp-md5";
const hash = md5("carlos");
console.log(hash);
  • HMAC-MD5 (hex-encoded)
    需要提供第二个参数作为密钥, 相当于加盐
import md5 from "blueimp-md5";
const hMacHash = md5("carlos", "key");
console.log(hMacHash);
  • MD5 hash (raw)
import md5 from "blueimp-md5";
const rawhash = md5("carlos", null, true);
console.log(rawhash);
  • HMAC-MD5 (raw)
    需要提供第二个参数作为密钥, 相当于加盐
import md5 from "blueimp-md5";
const rawhash = md5('carlos', 'ourcodeworld', true)
console.log(rawhash);

3. bcryptjs

主要使用bcrypt算法,对密码进行加密, 比md5更安全的散列函数

  • 安装
pnpm add bcryptjs
  • 对密码进行散列
import bcrypt from 'bcryptjs';
// 生成salt值
const salt = bcrypt.genSaltSync(10);
// 将密码和salt值一起散列化
const hash = bcrypt.hashSync('password', salt)
// 检查密码是否匹配
const isMatch = bcrypt.compareSync('password', hash);

4. js-md5

进行最简单的md5摘要计算

  • 安装
pnpm add js-md5
  • 使用
import md5 from 'js-md5';
// md5 hash
const hash = md5('hi there');
const hexHash = md5.hex('hi there');
// 支持HMAC-MD5
const hmacHash = md5.hmac('key', 'Message to hash');
const hmacHexHash = md5.hmac.hex('key', 'Message to hash');
const hmacArrayHash = md5.hmac.array('key', 'Message to hash')
// 支持定型数组,arrayBuffer
const arrayHash = md5.array('hi there');
const arrayBufferHash = md5.arrayBuffer('hi there'); // ArrayBuffer
// 支持base64
const base64Hash = md5.base64('hi there');

5. md5-file

主要专注于计算文件的md5

  • 安装
pnpm add md5-file
  • 使用
import md5File from 'md5-file';
// 异步计算文件hash
md5File('pnpm-lock.yaml').then((hash) => {
  console.log(`the hash is ${hash}`)
});
// 同步计算文件md5散列
const hash = md5File.sync('pnpm-lock.yaml');
console.log(`the hash is ${hash}`);
posted @ 2024-04-07 01:14  箫笛  阅读(305)  评论(0编辑  收藏  举报