4

I am trying to get the same result I obtain at http://jssha.sourceforge.net/

where

I have the word 'testing' in question:

var word = 'testing';
var hex = toHex(word); // '740065007300740069006e006700';

on jssha when selecting input type as HEX with the value of the hex variable and SHA-512 I get the following result:

6e42b2c2a6351036b78384212774135d99d849da3066264983e495b5f74dc922e3d361b8ea9c8527169757233ed0bd4e56b2c42aab0a21bbcca67219dc53b472

although I can't achieve the same result with nodejs crypto module.

require('crypto').createHash('sha512').update(hex).digest('hex')

outputs:

9ad6d9053c6c420fe61ec2fffd094e3a325bc71708e18232fd764a5eb30315e38464e620ef0b55b92fbf6c809838652a72d9412b0398b28d61ca432962451de2

So I am wondering how can I get the same result as jssha using crypto module?

Thanks

zanona
  • 12,345
  • 25
  • 86
  • 141

1 Answers1

4

"testing" in hex is 74657374696e67 if you use utf8 which is pretty much standard. What your toHex method returns assumes utf16.

For that hash, the website says:

521b9ccefbcd14d179e7a1bb877752870a6d620938b28a66a107eac6e6805b9d0989f45b5730508041aa5e710847d439ea74cd312c9355f1f2dae08d40e41d50

Do this in node.js to hash a hex string:

require('crypto').createHash('sha512').update(
  new Buffer("74657374696e67", "hex")
).digest('hex')

Node gives you the same hash. Oh, and this also gives you the same hash:

require('crypto').createHash('sha512').update("testing").digest('hex')
thejh
  • 44,854
  • 16
  • 96
  • 107
  • thanks @thejh, it seems `new Buffer("74657374696e67", "hex")` method returns `Unknown encoding` for me. Also, is there any way to make it use utf-16 instead 8. Sorry I guess I am stuck with this encoding since it is from an external web service. – zanona Oct 31 '11 at 17:01
  • @ludicco: Sure, you can just do the same with a utf16 hex string. The "unknown encoding" is because you're using an old version of node, use 0.5.10 and change to 0.6.0 when it's available. – thejh Oct 31 '11 at 17:19
  • thanks again @thejh, the only problem is that this instance is running on heroku, and I'm afraid they only support 0.47 by now? in this case I am not sure if the method you've mentioned would be able work? if you have any idea on how I could make this work, it would be really appreciated ;) – zanona Oct 31 '11 at 18:24
  • No idea, you might want to ask in #heroku on freenode.net. As a workaround, you can use Buffer.fromHex from https://github.com/bnoordhuis/node-buffertools . – thejh Oct 31 '11 at 18:39
  • 1
    Do `require("buffertools")` at the top of your file and replace `new Buffer("74657374696e67", "hex")` with `Buffer.fromHex("74657374696e67")` – thejh Oct 31 '11 at 18:40