0

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?

mikemaccana
  • 415
  • 5
  • 15
  • 5
    It is a newline issue. Try `echo -n "swag" | sha256sum` – knaccc Mar 03 '23 at 15:05
  • Hah thanks @knacc I should have remembered echo adds newlines. Want to add that as an answer and I'll accept it? – mikemaccana Mar 03 '23 at 15:19
  • 1
    This is off topic here, and I've definitely seen the same issue on [so]. – Maarten Bodewes Mar 03 '23 at 15:35
  • 3
    A related issue is that `echo` can mangle the data in ways that vary between shells, see https://unix.stackexchange.com/questions/65803/why-is-printf-better-than-echo – ilkkachu Mar 03 '23 at 16:34
  • @MaartenBodewes yep closing this is fair enough. When originally I asked the question I thought the cause may have been crypto related, but it wasn't. – mikemaccana Mar 03 '23 at 18:28
  • FYI, MDN isn't a particular implementation. The Mozilla foundation produces the FireFox browser; MDN is just a public documentation project. – DannyNiu Mar 04 '23 at 04:06
  • @DannyNiu By 'MDN implementation' I mean the entire function mentioned in the question, which includes the call to webcrypto but also has additional code. – mikemaccana Mar 04 '23 at 22:07

0 Answers0