I am trying to implement hash functionality from C to PHP but have encountred an issue. Would really appreciate to get some help with this.
This is the C-code hashing multiple 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 gets hashed again in a loop, and there is the tricky part for me 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);
}
The SHA1_Init uses the same context &ctx in the loop. Something I fear I cannot 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 can clearly see that in the second time it hashes the hash is not the same as in C:
C:
cf584b11970312e4b973bc7b35870d7e019affcd
cb1ea097e844363e4e76d512af4245c10ade1725
PHP:
cf584b11970312e4b973bc7b35870d7e019affcd
3003969f9065d7614d7cf34675b9d9bf7584d7c3
How may I hash with the old context in php? I don't find any documentation on how to do this and I am not really sure where it goes wrong.
Would be grateful for any kind comments on how to solve this problem!
this is because you're use in internal cycle in C binary array (array of bytes), but in the PHP you're use string with hex-representation of this array. i think more correct 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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With