0

Erlang returns me a different result than the bash command when I "sha256".

echo a | sha256sum, returns: 87428fc522803d31065e7bce3cf03fe475096631e5e07bbd7a0fde60c4cf25c7  -

Erlang

    Bin = crypto:hash(sha256, "a").


<<202,151,129,18,202,27,189,202,250,194,49,179,154,35,220,
      77,167,134,239,248,20,124,78,114,185,128,119,133,175,
      238,72,187>>

I tried different bin to hex from bin to hex None of them gave the result I was expecting.

I got this as a result:

    bin_to_hex:bin_to_hex(Bin).
<<"CA978112CA1BBDCAFAC231B39A23DC4DA786EFF8147C4E72B9807785AFEE48BB">>

1 Answers1

6

Your echo a will include a newline. When I add a newline to the erlang version, I get the expected hash:

1> Bin = crypto:hash(sha256, "a\n").
<<135,66,143,197,34,128,61,49,6,94,123,206,60,240,63,228,
  117,9,102,49,229,224,123,189,122,15,222,96,196,...>>
2> binary:encode_hex(Bin).
<<"87428FC522803D31065E7BCE3CF03FE475096631E5E07BBD7A0FDE60C4CF25C7">>

You can also tell echo not to use a newline with -n:

$ echo -n a | sha256sum
ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb  -
Brett Beatty
  • 5,690
  • 1
  • 23
  • 37