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

标签 c cryptography cs50

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

在下面的代码中stringchar* 的 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/

相关文章:

.net - dotNet 2.0 中哪种 FIPS 兼容算法更好?

authentication - SSH 公钥身份验证如何工作(选择正确的 key )

C语言while后do使用

java - 有没有办法只显示过滤后的结果?

c - 将字符串文字视为常量

c - Malloc 和 Void 指针

c - 使用 Newton-Raphson 方法在 C 中求平方根

objective-c - C printf 函数帮助

javascript - goog.cryp.Hmac 无法从 Node js 的 crypt 重现结果

c - 多维数组的值为 "skipped"的奇怪错误