Similar to Do identical strings always have the same SHA-256 value? however in this case the question is discussing two specific tools. Clearly one is adding characters, or different string encodings, but I'm asking this question to help find out what specifically is causing this issue.
Using the MDN implementation (which in turn uses webcrypto) to get a SHA256 string of the input: swag
const log = console.log;
const getSHA256Hash = async (message) => {
const messageEncodedAsUint8 = new TextEncoder().encode(message);
const hashedMessageBuffer = await crypto.subtle.digest(
"SHA-256",
messageEncodedAsUint8
);
const hashAsByteArray = Array.from(new Uint8Array(hashedMessageBuffer));
const hashHexString = hashAsByteArray
.map((b) => b.toString(16).padStart(2, "0"))
.join("");
return hashHexString;
};
const main = async () => {
log(await getSHA256Hash("swag"));
};
main();
Returns 712985CC1194DFFE8B30127444E0C92FE214420A84A5B2D28ABE6684F4540409 which seems to be match many other tools.
However Ubuntu's sha256sum returns a different value:
$ echo 'swag' | sha256sum
4888faaee170816fd4950f90f494f0a49abe5b5f618d9003f46efd9acbbd8b27 -
I originally was using a file and thought this may be a newline character or similar, but using stdin doesn't add any characters and the output still doesn't match.
Why is Ubuntu sha256sum giving a different result from MDN's webcrypto implementation?
Edit: maybe because JS uses USC2 and Ubuntu uses UTF8?