本文介绍了从JavaScript中的Blob/文件创建SHA-256哈希的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从浏览器内部的文件(〜6MB)创建SHA-256摘要.到目前为止,我设法做到的唯一方法是这样的:

I need to create a SHA-256 digest from a file (~6MB) inside the browser. The only way that I've managed to do it so far was like this:

var reader = new FileReader();
reader.onload = function() {
    // this gets read of the mime-type data header
    var actual_contents = reader.result.slice(reader.result.indexOf(',') + 1);
    var what_i_need = new jsSHA(actual_contents, "B64").getHash("SHA-256", "HEX");
}
reader.readAsDataURL(some_file);

虽然此方法可以正常工作,但问题在于它的运行速度非常慢. 6MB的文件花了大约2-3秒的时间.我该如何改善呢?

While this works correctly, the problem is that it's very slow. It took ~2-3 seconds for a 6MB file. How can I improve this?

推荐答案

您可能想看看斯坦福JS加密库

You may want to take a look at the Stanford JS Crypto Library

GitHub

带有示例的网站

从网站上:

SJCL的测试页显示了需要多长时间.

SJCL has a test page that shows how long it will take.

184毫秒(SHA256迭代).而从分解中获得SHA-256的时间为50毫秒.

184 milliseconds for a SHA256 iterative. And 50 milliseconds for a SHA-256 from catameringue.

测试页面

示例代码:

加密数据:sjcl.encrypt("password", "data")

解密数据:sjcl.decrypt("password", "encrypted-data")

这篇关于从JavaScript中的Blob/文件创建SHA-256哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 13:06