Search code examples
javascripthashsha

SHA256 hash of binary data using Forge


I want to use Forge to create a SHA256 hash. My test uses the binary data "\x01\x02\x03\x04\x05\x06\x07\x08" which is in a file. This produces the SHA256 using sha256sum on a Linux shell:

66840dda154e8a113c31dd0ad32f7f3a366a80e8136979d8f5a101d3d29d6f72

I than used the Web Crypto API (crypto.subtle.digest()) to calculate the hash. I'm using the ArrayBuffer from the Uint8Array here. Still OK, calculates the same hash:

let data = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);
const digest = await crypto.subtle.digest('SHA-256', data.buffer);
const array = Array.from(new Uint8Array(digest));
const hex = array.map(byte => ('00' + byte.toString(16)).slice(-2)).join('');
// 66840dda154e8a113c31dd0ad32f7f3a366a80e8136979d8f5a101d3d29d6f72

Now I want to use Forge library to calculate the hash and I can't get it to produce the correct hash:

let data = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);
const md = forge.md.sha256.create();
md.update(data);
let hex = md.digest().toHex();
// 181e2276640163cbb29a50fa846412edb6489b3c73e82ca4b64ae114b752a542
let data = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);
const md = forge.md.sha256.create();
let buffer = forge.util.createBuffer(data);
md.update(buffer);
let hex = md.digest().toHex();
// 1d4e1124c22199ab44fc3acb57e2f68f18bee390d8a52d62b15c23d3fc157846

How to create a SHA256 hash from binary data using Forge?


Solution

  • Ok, I found the solution in an issue on Github:

    let data = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);
    const md = forge.md.sha256.create();
    let buffer = String.fromCharCode.apply(null, data); // <-- HERE
    md.update(buffer);
    let hex = md.digest().toHex();
    // 66840dda154e8a113c31dd0ad32f7f3a366a80e8136979d8f5a101d3d29d6f72