如何使用 CryptoJS 计算 blob 的 md5 校验和 [英] How to calculate md5 checksum of blob using CryptoJS
问题描述
使用 Blob API 分块上传文件.这里我想检查 blob 的 md5 校验和.当我尝试下面的代码时,它对文本文件工作正常,但它为二进制文件返回不同的值.
Uploading file in chunks using Blob API. Here I want to check the md5 checksum of the blob. When I tried the below code it is working fine for text files, but it is returning different value for binary files.
var reader = new FileReader();
reader.readAsBinaryString(blob);
reader.onloadend = function () {
var mdsum = CryptoJS.MD5(reader.result);
console.log("MD5 Checksum",mdsum.toString());
};
如何正确计算所有类型文件的 blob 的 md5 校验和?
How to calculate the md5 checksum of blob correctly for all types of files ?
推荐答案
使用以下代码创建正确的 md5 哈希:
Use the following code to create a correct md5 hash:
function calculateMd5(blob, callback) {
var reader = new FileReader();
reader.readAsArrayBuffer(blob);
reader.onloadend = function () {
var wordArray = CryptoJS.lib.WordArray.create(reader.result),
hash = CryptoJS.MD5(wordArray).toString();
// or CryptoJS.SHA256(wordArray).toString(); for SHA-2
console.log("MD5 Checksum", hash);
callback(hash);
};
}
更新(简单一点):
function calculateMd5(blob, callback) {
var reader = new FileReader();
reader.readAsBinaryString(blob);
reader.onloadend = function () {
var hash = CryptoJS.MD5(reader.result).toString();
// or CryptoJS.SHA256(reader.result).toString(); for SHA-2
console.log("MD5 Checksum", hash);
callback(hash);
};
}
一定要包含core.js
、lib-typedarrays.js
(重要)和md5.js
> CryptoJS 库中的组件.
请参阅此 fiddle 以获取完整示例(由于原始访问控制,它不适用于 fiddle,在您的本地服务器上尝试).
Be sure to include core.js
, lib-typedarrays.js
(important) and md5.js
components from CryptoJS library.
Please see this fiddle for a complete example (because of origin access control it won't work on fiddle, try it on your local server).
这篇关于如何使用 CryptoJS 计算 blob 的 md5 校验和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!