Web加密API - 散列(Hashing)

本文说明了如何使用Web加密API生成数据的HASH值.

转换字符串为ArrayBuffer,并且把ArrayBuffer转换为16进制字符串

要生成字符串文本或二进制数据的Hash值, 必须先把它转换为ArrayBuffer类型.

1
2
3
4
5
6
7
8
9
10
function convertStringToArrayBufferView(str)
{

var bytes = new Uint8Array(str.length);
for (var iii = 0; iii < str.length; iii++)
{
bytes[iii] = str.charCodeAt(iii);
}

return bytes;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function convertArrayBufferToHexaDecimal(buffer)
{

var data_view = new DataView(buffer)
var iii, len, hex = '', c;
for(iii = 0, len = data_view.byteLength; iii < len; iii += 1)
{
c = data_view.getUint8(iii).toString(16);
if(c.length < 2)
{
c = '0' + c;
}

hex += c;
}
return hex;
}

生成字符串的HASH值

1
var data = "QNimate";

var crypto = window.crypto || window.msCrypto;

if(crypto.subtle)
{
    alert("Cryptography API Supported");

    var promise = crypto.subtle.digest({name: "SHA-256"}, convertStringToArrayBufferView(data));

    promise.then(function(result){
        var hash_value = convertArrayBufferToHexaDecimal(result);
    });
}
else
{
    alert("Cryptography API not Supported");
}

参考资料

  1. http://qnimate.com/hashing-using-web-cryptography-api/