0

May be it 's not a question for information security stack exchange and if it's true excuse me for my mistake.

I want to understand how this code works:

char *s = "1";
char *s_2 = "2";

unsigned char *x;

gcry_md_hd_t h;
gcry_md_open(&h, GCRY_MD_SHA256, GCRY_MD_FLAG_SECURE); 

gcry_md_write(h, s, strlen(s)); 
gcry_md_write(h, s_2, strlen(s_2)); 
x = gcry_md_read(h, GCRY_MD_SHA256); 

Well, i have two schemes and both of them don't work.

  1. x = SHA256(SHA256("1") || SHA256("2")).

SHA256("1") = 6b86b273ff34fce19d6b804eff5a3f5747ada4eaa22f1d49c01e52ddb7875b4b;

SHA256("2") = d4735e3a265e16eee03f59718b9b5d03019c07d8b6c51f90da3a666eec13ab35

SHA256(SHA256("1") || SHA256("2")) = 4295f72eeb1e3507b8461e240e3b8d18c1e7bd2f1122b11fc9ec40a65894031a

  1. x = SHA256(SHA256("1") || "2")

x = a29972da68d930f3bd40fa9c150137c780cf55f4d7187335a9f4b9043736f02a

But the result x (output from program) is

6b51d431df5d7f141cbececcf79edf3dd861c3b4069f0b11661a3eefacbba918

How does this code work??

MrSetplus
  • 41
  • 1
  • 3

2 Answers2

1

This code is simply doing:

SHA256("12") = 6b51d431df5d7f141cbececcf79edf3dd861c3b4069f0b11661a3eefacbba918

First of all, it is using libgcrypt, something you fail to mention, and whose documentation should point you in the right path.

gcry_md_open(&h, GCRY_MD_SHA256, GCRY_MD_FLAG_SECURE);

Create a message digest context

gcry_md_write(h, s, strlen(s));

Add "1" to the things you are hashing

gcry_md_write(h, s_2, strlen(s_2));

Add "2" to the things you are hashing

x = gcry_md_read(h, GCRY_MD_SHA256);

Obtain the hash output of what was provided, ie. "1" || "2" == "12"

Also note that those strlen() work there just because you are not hashing binary data, otherwise you would get the wrong result.

Ángel
  • 18,824
  • 3
  • 28
  • 65
1

The code is not evaluating SHA256(SHA256("1") || SHA256("2")) as claimed. Instead the code is starting a SHA256 digest, putting "1" into the digest followed by "2" and then returning the result. This is the same as computing SHA256("12").

Steffen Ullrich
  • 201,479
  • 30
  • 402
  • 465