JavaScript计算文件Hash值

发布时间:2023-09-29 19:30

JavaScript计算文件Hash值

三种方法计算Hash值的方法都是相同的;只是将Hash值转换为16进制base 64不同。

方法一

DOCTYPE html>
<html>
<head>
    <meta charset=\"utf-8\">
    <title>title>
    <script type=\"text/javascript\">
        window.onload = function () {
            let file = document.getElementById(\"fileid\");
            file.addEventListener(\"change\", function () {
                let read = new FileReader();
                read.readAsArrayBuffer(file.files[0])
                read.onload = function () {
                    (async function () {
    					//let inputBytes = new TextEncoder().encode(\"hello world\");
                        let sha1 = await crypto.subtle.digest(\'SHA-1\', read.result).then(a => Array.from(new Uint8Array(a)).map(a => a.toString(16).padStart(2, \'0\')).join(\"\"));
                        console.log(sha1);
                    })();
                }
            })
        }
    script>
head>
<body>
<input type=\"file\" id=\"fileid\">
body>
html>

参考:

不用引入外部库,在浏览器上一行计算出SHA-1/SHA-256的结果

https://blog.csdn.net/emu/article/details/121862519

方法二

DOCTYPE html>
<html>
<head>
    <meta charset=\"utf-8\">
    <title>title>
    <script type=\"text/javascript\">
        window.onload = function () {
            /**
             * 获取16进制摘要字符串
             * @param buffer
             * @returns {string}
             */
            function hex(buffer) {
                let code = [];
                let view = new DataView(buffer);
                for (var i = 0; i < view.byteLength; i += 4) {
                    value = view.getUint32(i)
                    let stringValue = value.toString(16)
                    // 填充切片
                    let padding = \'00000000\'
                    let paddedValue = (padding + stringValue).slice(-padding.length)
                    code.push(paddedValue);
                }
                return code.join(\"\");
            }

            /**
             * 获取文件,计算hash
             * @type {HTMLElement}
             */
            let file = document.getElementById(\"fileid\");
            file.addEventListener(\"change\", function () {
                let read = new FileReader();
                read.readAsArrayBuffer(file.files[0])
                read.onload = function () {
                    (async function () {
                        let arr = await crypto.subtle.digest(\'SHA-256\', read.result);
                        //console.log(arr);
                        //调用函数,获取16进制摘要字符串
                        let sha256Msg = hex(arr);
                        console.log(sha256Msg);
                    })();

                }
            })
        }
    script>
head>
<body>
<input type=\"file\" id=\"fileid\">
body>
html>

参考:

javascript获取文件sha-256,sha-384,sha-512摘要,验证文件是否被篡改,验证文件一致性,文件安全管理,计算文件的MD5值

https://blog.csdn.net/qq_41974199/article/details/124232425

方法三

DOCTYPE html>
<html>
<head>
    <meta charset=\"utf-8\">
    <title>title>
    <script type=\"text/javascript\">
        window.onload = function () {

            // from: https://stackoverflow.com/a/40031979/9014097
            function buf2hex(buffer) { // buffer is an ArrayBuffer
                return Array.prototype.map.call(new Uint8Array(buffer), x => (\'00\' + x.toString(16)).slice(-2)).join(\'\');
            }

            // from https://stackoverflow.com/a/11562550/9014097
            function buf2Base64(buffer) {
                return btoa(String.fromCharCode.apply(null, new Uint8Array(buffer)));
            }

            /**
             * 获取文件,计算hash
             * @type {HTMLElement}
             */
            let file = document.getElementById(\"fileid\");
            file.addEventListener(\"change\", function () {
                let read = new FileReader();
                read.readAsArrayBuffer(file.files[0])
                read.onload = function () {
                    (async function () {
                        let hashBytes = await window.crypto.subtle.digest(\"SHA-256\", read.result);
                        console.log(JSON.stringify({hash: buf2hex(hashBytes)})); // {\"hash\":\"d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592\"}
                        console.log(JSON.stringify({hash: buf2Base64(hashBytes)})); // {\"hash\":\"16j7swfXgJRpypq8sAguT41WUeRtPNt2LQLQvzfJ5ZI=\"}
                    })();

                }
            })
        }
    script>
head>
<body>
<input type=\"file\" id=\"fileid\">
body>
html>

参考:

为什么crypto.subtle.digest返回一个空对象

https://cloud.tencent.com/developer/ask/sof/767149

ItVuer - 免责声明 - 关于我们 - 联系我们

本网站信息来源于互联网,如有侵权请联系:561261067@qq.com

桂ICP备16001015号