Incremental Hashing in PHP vs. C

I am trying to implement hash functionality from C to PHP, but have run into a problem. It would be very helpful to help with this.

This hashes the C code several times:

SHA_CTX ctx; SHA1_Init(&ctx); SHA1_Update(&ctx, (const u_int8_t *) salt, strlen(salt)); SHA1_Update(&ctx, (const u_int8_t *) argv[1], strlen(argv[1])); SHA1_Final(temp, &ctx); 

But then it again becomes hashed in the loop, and for me there is a tricky part to implement in php:

 for (n = 0; n < 2 ; ++n) { SHA1_Init(&ctx); SHA1_Update(&ctx, (const u_int8_t *)salt, strlen(salt)); SHA1_Update(&ctx, temp, SHA_DIGEST_LENGTH); SHA1_Final(temp, &ctx); } 

SHA1_Init uses the same & ctx context in a loop. Something I'm afraid of, I can't do in php.

This is my current php code:

 $ctx = hash_init('sha1'); hash_update($ctx, $salt); hash_update($ctx, 'string'); $pw = hash_final($ctx); for ($round = 0; $round < 2; ++$round) { $ctx = hash_init('sha1'); hash_update($ctx, $salt); hash_update($ctx, $pw); $pw = hash_final($ctx); } 

From the output, I clearly see that the second time the hash hash does not match C:

 C: cf584b11970312e4b973bc7b35870d7e019affcd cb1ea097e844363e4e76d512af4245c10ade1725 PHP: cf584b11970312e4b973bc7b35870d7e019affcd 3003969f9065d7614d7cf34675b9d9bf7584d7c3 

How can I use hash with old context in php? I do not find documentation on how to do this, and I'm not sure where this is going.

I would be grateful for any comments on how to solve this problem!

+6
source share
1 answer

this is because you use in the inner loop in a binary array C (an array of bytes), but in PHP you use a string with a hexadecimal representation of this array. I think the more correct one is:

 $salt = 'salt'; $ctx = hash_init('sha1'); hash_update($ctx, $salt); hash_update($ctx, 'string'); $pw = hash_final($ctx, true); for ($round = 0; $round < 2; ++$round) { $ctx = hash_init('sha1'); hash_update($ctx, $salt); hash_update($ctx, $pw); $pw = hash_final($ctx, $round < 1); } echo $pw; 
+2
source

Source: https://habr.com/ru/post/956416/