Calculate File SHA1 hash - client side Rusha

by lid0

HTML

<script>
    /*! rusha 2015-03-14 */
(function(){if(typeof module!=="undefined"){module.exports=d}else if(typeof window!=="undefined"){window.Rusha=d}if(typeof FileReaderSync!=="undefined"){var a=new FileReaderSync,b=new d(4*1024*1024);self.onmessage=function e(a){var c,d=a.data.data;try{c=b.digest(d);self.postMessage({id:a.data.id,hash:c})}catch(e){self.postMessage({id:a.data.id,error:e.name})}}}var c={getDataType:function(a){if(typeof a==="string"){return"string"}if(a instanceof Array){return"array"}if(typeof global!=="undefined"&&global.Buffer&&global.Buffer.isBuffer(a)){return"buffer"}if(a instanceof ArrayBuffer){return"arraybuffer"}if(a.buffer instanceof ArrayBuffer){return"view"}if(a instanceof Blob){return"blob"}throw new Error("Unsupported data type.")}};function d(b){"use strict";var e={fill:0};var f=function(a){for(a+=9;a%64>0;a+=1);return a};var g=function(a,b){for(var c=b>>2;c<a.length;c++)a[c]=0};var h=function(a,b,c){a[b>>2]|=128<<24-(b%4<<3);a[((b>>2)+2&~15)+14]=c>>29;a[((b>>2)+2&~15)+15]=c<<3};var i=function(a,b,c,d,e){var f=this,g,h=e%4,i=d%4,j=d-i;if(j>0){switch(h){case 0:a[e+3|0]=f.charCodeAt(c);case 1:a[e+2|0]=f.charCodeAt(c+1);case 2:a[e+1|0]=f.charCodeAt(c+2);case 3:a[e|0]=f.charCodeAt(c+3)}}for(g=h;g<j;g=g+4|0){b[e+g>>2]=f.charCodeAt(c+g)<<24|f.charCodeAt(c+g+1)<<16|f.charCodeAt(c+g+2)<<8|f.charCodeAt(c+g+3)}switch(i){case 3:a[e+j+1|0]=f.charCodeAt(c+j+2);case 2:a[e+j+2|0]=f.charCodeAt(c+j+1);case 1:a[e+j+3|0]=f.charCodeAt(c+j)}};var j=function(a,b,c,d,e){var f=this,g,h=e%4,i=d%4,j=d-i;if(j>0){switch(h){case 0:a[e+3|0]=f[c];case 1:a[e+2|0]=f[c+1];case 2:a[e+1|0]=f[c+2];case 3:a[e|0]=f[c+3]}}for(g=4-h;g<j;g=g+=4|0){b[e+g>>2]=f[c+g]<<24|f[c+g+1]<<16|f[c+g+2]<<8|f[c+g+3]}switch(i){case 3:a[e+j+1|0]=f[c+j+2];case 2:a[e+j+2|0]=f[c+j+1];case 1:a[e+j+3|0]=f[c+j]}};var k=function(b,c,d,e,f){var g=this,h,i=f%4,j=e%4,k=e-j;var l=new Uint8Array(a.readAsArrayBuffer(g.slice(d,d+e)));if(k>0){switch(i){case 0:b[f+3|0]=l[0];case 1:b[f+2|0]=l[1];case...

JavaScript

$(document).ready(function () {
    $("#btn").click(function () {
        var reader = new FileReader(); //define a Reader
        var file = $("#f1")[0].files[0]; //get the File object 
        if (!file) {
            alert("no file selected");
            return;
        } //check if user selected a file

        reader.onload = function (f) {
            var file_result = this.result; // this == reader, get the
            var sha1_hash = new Rusha().digestFromArrayBuffer(file_result);
            
            alert("Calculated SHA1:" + sha1_hash.toString()); //output result
        };
        reader.readAsArrayBuffer(file); //read file as ArrayBuffer
    });
});