使用 OpenSSL 计算并打印文件的 SHA256 哈希值 [英] Calculate and print SHA256 hash of a file using OpenSSL

查看:82
本文介绍了使用 OpenSSL 计算并打印文件的 SHA256 哈希值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 OpenSSL/libcrypto 编写一个 C 函数来计算文件的 SHA256 总和.我的代码基于 Adam Lamer 的 C++ 示例这里.

I'm trying to write a C function using OpenSSL/libcrypto to calculate the SHA256 sum of a file. I'm basing my code on Adam Lamer's c++ example here.

这是我的代码:

int main (int argc, char** argv)
{
    char calc_hash[65];

    calc_sha256("file.txt", calc_hash);
}

int calc_sha256 (char* path, char output[65])
{
    FILE* file = fopen(path, "rb");
    if(!file) return -1;

    char hash[SHA256_DIGEST_LENGTH];
    SHA256_CTX sha256;
    SHA256_Init(&sha256);
    const int bufSize = 32768;
    char* buffer = malloc(bufSize);
    int bytesRead = 0;
    if(!buffer) return -1;
    while((bytesRead = fread(buffer, 1, bufSize, file)))
    {
        SHA256_Update(&sha256, buffer, bytesRead);
    }
    SHA256_Final(hash, &sha256);

    sha256_hash_string(hash, output);
    fclose(file);
    free(buffer);
    return 0;
}      

void sha256_hash_string (char hash[SHA256_DIGEST_LENGTH], char outputBuffer[65])
{
    int i = 0;

    for(i = 0; i < SHA256_DIGEST_LENGTH; i++)
    {
        sprintf(outputBuffer + (i * 2), "%02x", hash[i]);
    }

    outputBuffer[64] = 0;
}

问题是这样的....看看下面的示例文件的计算总和:

The problem is this....take a look at the calculated sums below for an example file:

Known good SHA256: 6da032d0f859191f3ec46a89860694c61e65460d54f2f6760b033fa416b73866
Calc. by my code:  6dff32ffff59191f3eff6affff06ffff1e65460d54ffff760b033fff16ff3866

当代码完成执行时,我也*检测到堆栈粉碎.

I also get * stack smashing detected * when the code is finished executing.

有人看到我做错了什么吗?

Does anyone see what I'm doing wrong?

谢谢!

推荐答案

看起来你的输出中有很多 '0xff' 块,并且好字符串中的相应块设置了高位......也许是在某处签名扩展问题.

Looks like there are a lot of '0xff' blocks in your output, and the corresponding blocks in the good string have the high bit set ... maybe a sign extension problem somewhere.

做:

char hash[SHA256_DIGEST_LENGTH];

未签名,例如:

unsigned char hash[SHA256_DIGEST_LENGTH];

帮助?(特别是在sha256_hash_string的签名中.)

help? (Especially in the signature of sha256_hash_string.)

这篇关于使用 OpenSSL 计算并打印文件的 SHA256 哈希值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆