建立摘要(例如 SHA-256)
// Convert string to ArrayBuffer. This step is only necessary if you wish to hash a string, not if you aready got an ArrayBuffer such as an Uint8Array.
var input = new TextEncoder('utf-8').encode('Hello world!');
// Calculate the SHA-256 digest
crypto.subtle.digest('SHA-256', input)
// Wait for completion
.then(function(digest) {
// digest is an ArrayBuffer. There are multiple ways to proceed.
// If you want to display the digest as a hexadecimal string, this will work:
var view = new DataView(digest);
var hexstr = '';
for(var i = 0; i < view.byteLength; i++) {
var b = view.getUint8(i);
hexstr += '0123456789abcdef'[(b & 0xf0) >> 4];
hexstr += '0123456789abcdef'[(b & 0x0f)];
}
console.log(hexstr);
// Otherwise, you can simply create an Uint8Array from the buffer:
var digestAsArray = new Uint8Array(digest);
console.log(digestAsArray);
})
// Catch errors
.catch(function(err) {
console.error(err);
});
目前的草案建議至少提供 SHA-1
,SHA-256
,SHA-384
和 SHA-512
,但這不是嚴格要求,可能會有變化。但是,SHA 系列仍然可以被認為是一個不錯的選擇,因為它可能會在所有主流瀏覽器中得到支援。