<!DOCTYPE html>
<html>
<head>
<META NAME="Author" CONTENT="emu">
<META NAME="Keywords" CONTENT="webcrypto sha1 sha256 sha384 sha512">
</head>
<body>
<div id=sha></div>
<script type="text/javascript">
function output(sign) {
document.getElementById("sha").innerHTML += sign + "<br>";
}
function bufferToHex(b){
var dataview = new DataView(b);
result = "";
for (var i = 0; i < b.byteLength; i += 4) {
tmp = dataview.getUint32(i).toString(16);
result += (tmp.length == 8 ? "" : "0") + tmp;
}
return result;
}
function digest(s, callback, algorithm, errCallback) {
try {
if (!errCallback) {
errCallback = callback;
}
var c = window.crypto || window.msCrypto;
var subtle = c.subtle || c.webkitSubtle;
if (!algorithm) algorithm = "SHA-512";
var a = s.split("");
for (var i = 0; i < a.length; i++) {
a[i] = a[i].charCodeAt(0)
};
var data = new Uint8Array(a);
var op = subtle.digest({
name: algorithm
}, data);
if("then" in op){
op.then(
function(buffer) {
callback(bufferToHex(buffer));
}, function(e) {
errCallback(e);
})
}else{
op.oncomplete=function(s){
callback(bufferToHex(s.target.result));
}
}
} catch (e) {
errCallback(e);
}
}
digest("test", new Function("output('sha-1(<i>test</i>) : '+arguments[0])"), "SHA-1");
digest("test", new Function("output('sha-256(<i>test</i>) : '+arguments[0])"), "SHA-256");
digest("hello", new Function("output('sha-384(<i>hello</i>) : '+arguments[0])"), "SHA-384");
digest("world", new Function("output('sha-512(<i>world</i>) : '+arguments[0])"), "SHA-512");
</script>
</body>
</html>
使用了浏览器原生接口,对旧浏览器没有什么兼容性可言了,尤其是IE,一时半会儿还用不上。