为什么我的代码拒绝比较生成的哈希值

Why my code refuse to compare the generated hashes

我正在处理 cs50 的破解作业。我打算从 1 个字符的密码开始比较哈希,但它根本不起作用。

下面的代码 string<cs50.h>char* 的类型定义。

#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函数returns指向静态数据缓冲区的指针。这意味着每次调用 crypt 时静态数据都会发生变化,因此 hash 指向一个在每次迭代中都会发生变化的缓冲区。这就是它每次都匹配的原因。

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

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