【问题标题】:Windows C SHA256 Invalid Generation IssueWindows C SHA256 无效生成问题
【发布时间】:2010-06-20 16:14:02
【问题描述】:

你好。我在创建 sha256 哈希时遇到了一个非常奇怪的问题。我制作了一个简单的 C 控制台程序,它以文件路径作为参数,并使用可以在 here 找到的独立 sha256 代码。我在 Windows 7 x64 上使用 MinGW 5.1.6 编译了程序。

在文件上测试程序时,生成的哈希是错误的。我通过在文件上使用 md5deep 来确保这一点,然后在 Linux 下对文件使用 sha256sum。 我还通过在我的 Linux 机器上使用相同的文件编译和运行相同的代码来验证它不是代码;它产生的哈希值与 md5deep 和 sha256sum 产生的哈希值相同。

我还将 Aaron Gifford 的 sha256 实现改编为我的简单程序的不同版本,并在 Windows 和 Linux 上再次执行测试,最终得到相同的结果。

有没有可能是编译器标志没有打开造成的?

我对 C 的了解并不惊人,而且我对编译器选项的了解更差,因此我们将不胜感激。

简单程序的代码如下:

#include <stdio.h>
#include "sha256.h"

#define BUFLEN 16384

int main(int argc, char *argv[]) {
    sha256_context ctx256;
    sha256_starts(&ctx256);
    int kl, l, fd;
    unsigned char buf[BUFLEN];
    FILE *file = (FILE*) 0;
    char *filepath;

    fd = fileno(stdin);

    filepath = argv[1];
    file = fopen(filepath, "r");

    fd = fileno(file);
    while ((l = read(fd, buf, BUFLEN)) > 0) {
        kl += l;
        sha256_update(&ctx256, buf, l);
    }
    fclose(file);
    uint8 sha256sum[32];
    sha256_finish(&ctx256, sha256sum);
    int i;
    for (i = 0; i < 32; i++) {
        printf("%02x", sha256sum[i]);
    }
    printf("\n");

    return 0;
}

【问题讨论】:

  • 你应该真正以二进制模式(“rb”)打开文件,这样不同的行尾就不会给你带来问题。
  • 你能相信修复了吗?我已经如此接近代码,以至于文件模式完全超出了我的想象。感谢您发现它!

标签: c windows linux mingw sha256


【解决方案1】:

二进制模式在 Linux 上会被忽略,但它适用于 Windows。有关其作用的参考,请参阅http://msdn.microsoft.com/en-us/library/yeby3zcb%28VS.71%29.aspx。简而言之,\r\n 在非二进制模式下被翻译成 \n。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-16
    • 1970-01-01
    • 1970-01-01
    • 2021-08-22
    • 2016-08-24
    • 2018-09-18
    相关资源
    最近更新 更多