创建摘要(例如 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 系列仍然可以被认为是一个不错的选择,因为它可能会在所有主流浏览器中得到支持。