1. 程式人生 > >大家好像都比較少關心webcrypto,試試寫個簡單的sha1/sha256/sha384/sha512實現看看

大家好像都比較少關心webcrypto,試試寫個簡單的sha1/sha256/sha384/sha512實現看看

<!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 bufferToString(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(bufferToString(buffer));
							}, function(e) {
								errCallback(e);
							})
					}else{
						op.oncomplete=function(s){					
							callback(bufferToString(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,一時半會兒還用不上。