C语言 为什么我的代码拒绝比较生成的哈希



我正在研究cs50的破解任务。我计划从 1 个字符密码的比较哈希开始,但它根本不起作用。

在下面的代码中string是一个用于<cs50.h>char*的typedef。

#include <stdio.h>
#include <cs50.h>
#include <crypt.h>
#include <string.h>
int main(int argc, string argv[])
{
if(argc != 2)
{
printf("Enter the hash code as a single argumentn");
return 1;
}
string salt = get_string("Imput the saltn");
string hash = crypt(argv[1], salt);
string key[] = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S"};
if(strlen(argv[1]) == 1)
{
for(int i=0; i<18; i++)
{
string cypher = crypt(key[i], salt);
int comp = strcmp(cypher, hash);
if(comp == 0)
{
printf("%s", key[i]);
}
else
printf("unmatchn");
}
}
}

当我使用 salt 12 和要散列并检查为数组中的 A 的代码运行程序时,我收到以下消息:

~/pset2/ $ ./crack1 A
Imput the salt:
12

ABCDEFGHIJKLMNOPQR

换句话说,程序会打印我整个数组,而不是只打印与哈希匹配的字符女巫。

crypt函数返回指向静态数据缓冲区的指针。 这意味着每次调用crypt时,静态数据都会更改,因此hash指向每次迭代时都会更改的缓冲区。 这就是为什么它每次都匹配的原因。

您需要复制第一次调用crypt时返回的字符串。 然后,您可以将其与后续调用进行比较。

string hash = strdup(crypt(argv[1], salt));

最新更新