Is this how I should calculate a Double SHA256

5

So I have a function called sha256 which will take a string and return the SHA-256 hash.

var First = sha256('myfirstSHA');

And the output is the hex:

9b2b95b24dd9149480ebda21aafe3f1a3c0370798ceec3c4d09c6a16adfe01c8

All feels good here, but if I want a double SHA-256 how should I go abut calculating it? Can I just use the same function as above twice? like this...

var Second = sha256(sha256('myfirstSHA'));

What should the value of Second be?

I get the feeling I may need to get the value of the first hash and convert it to something before putting it back through the sha-256 function a second time??

So my question is, what should I convert it to, before feeding it back in again?

Any advice is most welcome!

Will-In-China

Posted 2017-03-08T12:44:15.553

Reputation: 448

Answers

4

Yes you should convert your first output before feeding it back in: A hash function is typically a function which takes in an array of bytes (of arbitrary size) and spits out an array of bytes (of fixed size). When making the first call first = sha256('myfirstSHA'), it is likely that the string argument is implicitly converted to an array of bytes, whereby each character is substituted by a single byte encoding. However, the string output you are getting (which is a string, not an array of bytes), clearly represents a hex encoding of a 32 bytes array. You need to convert this hex encoding into a 32 bytes array. If you have a Linux terminal, as indicated by this post, a very useful command is xxd -r -p which converts your hex encoding into actual bytes:

$ echo -n myfirstSHA | sha256sum
9b2b95b24dd9149480ebda21aafe3f1a3c0370798ceec3c4d09c6a16adfe01c8 - 
$ echo -n myfirstSHA | sha256sum | xxd -r -p | sha256sum
96082208e341446bb8ba032486d142cbe73f1a66276b96c18ff815f31293fe0d -

If you are worried about the trailing '-' which appears in the output of sha256sum, you can cut it out:

$ echo -n myfirstSHA | sha256sum | cut -d' ' -f1
9b2b95b24dd9149480ebda21aafe3f1a3c0370798ceec3c4d09c6a16adfe01c8

and then proceed as before:

$ echo -n myfirstSHA | sha256sum | cut -d' ' -f1 | xxd -r -p | sha256sum
96082208e341446bb8ba032486d142cbe73f1a66276b96c18ff815f31293fe0d  -

In case you do not trust that xxd -r -p does the right thing, you can store the output in a file:

$ echo -n myfirstSHA | sha256sum | xxd -r -p > temp

then use hexdump -C temp or indeed xxd temp to check the content of the binary file:

00000000  9b 2b 95 b2 4d d9 14 94  80 eb da 21 aa fe 3f 1a  |.+..M......!..?.|
00000010  3c 03 70 79 8c ee c3 c4  d0 9c 6a 16 ad fe 01 c8  |<.py......j.....|
00000020

Sven Williamson

Posted 2017-03-08T12:44:15.553

Reputation: 1 404