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()
}