Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get correct SHA1 hash of BLOB using CryptoJS?

CryptoJS v3.1.2, sha1.js rollup

In JS I want to calculate the SHA1 of a blob before sending it to the server. On the server I want to calculate the SHA1 of the resulting file and compare it to the SHA1 received from JS. The problem is that the hash generated by CryptoJS.SHA1() is incorrect (always 9844f81e1408f6ecb932137d33bed7cfdcf518a3)

JS Code:

function uploadFileslice (slice) { // slice is a blob
    var fileReader = new FileReader()
    fileReader.onload = function(event){
        var arrayBuffer = event.target.result
        var wordArray = CryptoJS.lib.WordArray.create(arrayBuffer)
        var sha1crc = CryptoJS.SHA1(wordArray).toString(CryptoJS.enc.Hex)
        //etc
        requestParams.append('fileslice', slice)
        requestParams.append('sha1crc', sha1crc)
        //etc
    }
    fileReader.readAsArrayBuffer(slice)
}

PHP code:

$file_crc = sha1_file($_FILES['fileslice']['tmp_name']);
if ($_REQUEST['sha1crc'] !== $file_crc) {
    echo "Invalid CRC: {$_REQUEST['sha1crc']} (expected $file_crc)";
    return;
}

Output:

Invalid CRC: 9844f81e1408f6ecb932137d33bed7cfdcf518a3 (expected 3ebe2cd2d8fd8d8f977b6d715f0b1adf5b08b407

I was hoping for something like myHash = CryptoJS.SHA1(blob)

like image 478
Vladimir Kornea Avatar asked Jul 23 '13 19:07

Vladimir Kornea


1 Answers

From the info that you've provided I'm not sure exactly how you have things setup but in order for ArrayBuffers to be supported you have to include components/lib-typedarrays-min.js.

There's a discussion about this at https://code.google.com/p/crypto-js/issues/detail?id=67.

Hope this helps!

like image 195
Trey Avatar answered Jan 04 '23 05:01

Trey