我正在尝试实现从C到PHP的哈希功能,但已经解决了一个问题.真的很感激能得到一些帮助.
这是多次C代码散列:
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);
Run Code Online (Sandbox Code Playgroud)
但是它会在循环中再次进行哈希处理,并且我在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);
}
Run Code Online (Sandbox Code Playgroud)
SHA1_Init在循环中使用相同的context和ctx.我害怕我不能在PHP中做的事情.
这是我目前的PHP代码:
$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);
}
Run Code Online (Sandbox Code Playgroud)
从输出中,我可以清楚地看到它在第二次散列时散列与C中的散列不同:
C:
cf584b11970312e4b973bc7b35870d7e019affcd
cb1ea097e844363e4e76d512af4245c10ade1725
PHP:
cf584b11970312e4b973bc7b35870d7e019affcd
3003969f9065d7614d7cf34675b9d9bf7584d7c3
Run Code Online (Sandbox Code Playgroud)
我怎么能用PHP中的旧上下文哈希?我没有找到关于如何做到这一点的任何文档,我不确定它出错的地方.
将不胜感激任何关于如何解决这个问题的评论!
这是因为您在 C 二进制数组(字节数组)的内部循环中使用,但在 PHP 中您使用带有该数组的十六进制表示形式的字符串。我认为更正确的是:
$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;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
553 次 |
| 最近记录: |