Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node SHA-256 Base64 Digest

I have a question about Node.js Crypto module's hash digest.

With the input hello world on the command line a base64 encoded sha256 produces:

$ echo -n "hello world"|shasum -a256|base64 -
Yjk0ZDI3Yjk5MzRkM2UwOGE1MmU1MmQ3ZGE3ZGFiZmFjNDg0ZWZlMzdhNTM4MGVlOTA4OGY3YWNlMmVmY2RlOSAgLQo=

Doing the same (as far as I know) on Node.js (0.12.9) produces an entirely different result:

var crypto = require("crypto");
var shasum = crypto.createHash("sha256"); 
shasum.update("hello world", "utf-8"); 
shasum.digest("base64");
// 'uU0nuZNNPgilLlLX2n2r+sSE7+N6U4DukIj3rOLvzek='

The hex digest procuced in Node and on the command line are identical (b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9). Why the difference in the base64 encoded digest?

like image 796
nikc.org Avatar asked Feb 08 '23 20:02

nikc.org


1 Answers

For the commandline example, you're encoding the string b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9 as base64. The Node example encodes the bytes 0xb9, 0x4d, 0x27, 0xb9 etc. in base64. The two are quite different.

To see the difference, it might help to see what the hex string is, in bytes:

$ echo -n "hello world" | shasum -a256 | hexdump
0000000 3962 6434 3732 3962 3339 6434 6533 3830
0000010 3561 6532 3235 3764 6164 6437 6261 6166
0000020 3463 3438 6665 3365 6137 3335 3038 6565
0000030 3039 3838 3766 6361 3265 6665 6463 3965

That is quite different from the actual byte sequence b9, 4d, 27, b9 etc.

EDIT: In order to actually get the 'right' result on the command line, you could output an actual binary sha256 digest and encode that, instead:

$ echo -n "hello world"| openssl sha256 -binary | base64 -
uU0nuZNNPgilLlLX2n2r+sSE7+N6U4DukIj3rOLvzek=
like image 129
Joost Avatar answered Feb 11 '23 01:02

Joost