How to get correct SHA1 hash of BLOB using CryptoJS?
Asked Answered
S

2

8

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)

Sidneysidoma answered 23/7, 2013 at 19:55 Comment(0)
K
13

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!

Knotted answered 25/7, 2013 at 2:59 Comment(3)
I'm looking to use sha256 and I'm having difficulties.. In my case, I have a b64 string representing an image. I use the code you linked by converting to arraybuffer, and then using a wordarray to compute the hash. Unfortunately when I check the image's hash with openssl sha256 on my mac, the results are different. Any idea of what I'm doing wrong?Villalobos
(related to this previous question of mine.. #25148746)Villalobos
Anyone creating hashes from Blob using CryptoJS should be aware of this. DO NOT forget to include 'lib-typedarrays.js'. Worked just great!Bushman
G
1

If you are using modules and import you can:

import Hex from 'crypto-js/enc-hex'
import WordArray from 'crypto-js/lib-typedarrays'
import sha1 from 'crypto-js/sha1'

const hash = sha1(WordArray.create(arrayBuffer)).toString(Hex)
Guadalcanal answered 4/2, 2022 at 16:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.