Vue3 ts 使用插件crypto-js实现依据Uint8Array格式的文件生成hash256

Vue3 使用插件crypto-js实现依据Uint8Array格式的文件生成hash256

1、crypto-js插件

下载插件命令

npm crypto-js --save

在使用插件的地方引入

import CryptoJS from 'crypto-js'

2、小文件生成方式

针对小于百兆的文件,建议使用小文件生成方式
关键代码,请提前将文件读取为Uint8Array格式,将返回文件生成的hash256

const fileToHash256= async (fileContents: Uint8Array) => {
 	const wordArray = CryptoJS.lib.WordArray.create(fileContents)
  	return CryptoJS.SHA256(wordArray).toString()
}

3、大文件生成方式

针对大于于百兆的文件,建议使用大文件生成方式,因为可能遇到数组长度超长error ( Invalid array length)
关键代码,请提前将文件读取为Uint8Array格式,将返回文件生成的hash256

const fileToHash256 = async (fileContents: Uint8Array) => {
  const sha256Alog = CryptoJS.algo.SHA256.create()
  const hashSize = 100 * 1024 * 1024 // 分片大小 100M
  const chunkCount = Math.ceil(fileContents.length / hashSize) // 分片数量
  for (let i = 0; i < chunkCount; i++) {
    const chunkContens = fileContents.slice(
      hashSize * i,
      Math.min(hashSize * (i + 1), fileContents.length)
    )
    sha256Alog.update(CryptoJS.lib.WordArray.create(chunkContens))
  }
  return sha256Alog.finalize().toString()
}
  • 8
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值