我正在研究 cs50 的破解作业。我打算从比较 1 个字符密码的哈希值开始,但它根本不起作用。
在下面的代码中string
是 char*
的 typedef在<cs50.h>
.
#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 argument\n");
return 1;
}
string salt = get_string("Imput the salt\n");
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("unmatch\n");
}
}
}
当我使用 salt 12 和要进行哈希处理并检查为数组中的 A 的代码运行程序时,我收到此消息:
~/pset2/ $ ./crack1 A
Imput the salt:
12
ABCDEFGHIJKLMNOPQR
换句话说,程序会打印整个数组,而不是仅打印与哈希匹配的字符。
最佳答案
crypt
函数返回一个指向静态数据缓冲区的指针。这意味着每次调用 crypt 时,静态数据都会发生变化,因此 hash 指向每次迭代时都会发生变化的缓冲区。这就是为什么它每次都会匹配。
您需要复制第一次调用crypt
时返回的字符串。然后您可以将其与后续调用进行比较。
string hash = strdup(crypt(argv[1], salt));
关于c - 为什么我的代码拒绝比较生成的哈希值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57531462/