I have simple code on Java backend side that is hashing some bytes.
import org.bouncycastle.jcajce.provider.digest.SHA256;
import java.util.Arrays;
public class ShaTest {
public static void main(String... args) {
var input = new byte[] {0, 1, 2, 3, 4, 5, 6, 7};
var result = new SHA256.Digest().digest(input);
System.out.println(Arrays.toString(result));
}
}
The result equals to [-118, -123, 31, -8, 46, -25, 4, -118, -48, -98, -61, -124, 127, 29, -33, 68, -108, 65, 4, -46, -53, -47, 126, -12, -29, -37, 34, -58, 120, 90, 13, 69]
Now on frontend side, I need to hash the same bytes and I expect to have the same result using js-sha256
library. Hash function is as simple as
hash(input: any): any {
return sha.sha256.update(input).digest();
}
And I'm trying to hash it using several different inputs
const rawInput = [0, 1, 2, 3, 4, 5, 6, 7];
console.log('rawInput', this.hash(rawInput));
console.log('uint8Input', this.hash(new Uint8Array(rawInput)));
console.log('int8Input', this.hash(new Int8Array(rawInput)));
const intArr = new Int8Array(new ArrayBuffer(8));
intArr.set(rawInput);
console.log('intArrayWithBuffer', this.hash(intArr));
const uintArr = new Uint8Array(new ArrayBuffer(8));
uintArr.set(rawInput);
console.log('uintArrayWithBuffer', this.hash(uintArr));
However, the result is different than on backend side. Frontend instead produces
[138, 133, 31, 248, 46, 231, 4, 138, 208, 158, 195, 132, 127, 29, 223, 68, 148, 65, 4, 210, 203, 209, 126, 244, 227, 219, 34, 198, 120, 90, 13, 69]
Why is that happening?