【问题标题】:Correctly hashing a string in C在 C 中正确散列字符串
【发布时间】:2021-09-05 12:08:15
【问题描述】:

通过以下命令使用终端实用程序“openssl”时:

echo -n "Hello World!" | openssl sha1

这是产生的输出:

(stdin)= 2ef7bde608ce5404e97d5f042f95f89f1c232871

我尝试使用以下 C 代码生成相同的输出:

#include <stdio.h>
#include <stdlib.h>
#include <openssl/sha.h>

int main(void){
    const unsigned char source_string[1024] = "Hello World!";
    unsigned char dest_string[1024];
    SHA1(source_string, 16, dest_string);
    printf("String: %s\nHashed string: %s\n", source_string, dest_string);
    return 0;
}

但是,它会产生这种奇怪的非 unicode 输出:

String: Hello World!
Hashed string: #�V�#��@�����T\�

如何使它产生与之前显示的 openssl 终端命令相同的输出?

【问题讨论】:

  • 您在目标“字符串”中收到的数据实际上不是 C 空终止字符串。这是一个固定长度的原始字节字节序列。

标签: c string encryption hash openssl


【解决方案1】:

你应该

  • 将正确长度的字符串(长度为 12 字节)传递给SHA1
  • 以十六进制打印结果,而不是字符串。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/sha.h>

int main(void){
    const unsigned char source_string[1024] = "Hello World!";
    unsigned char dest_string[1024];
    int i;
    SHA1(source_string, strlen((const char*)source_string), dest_string);
    printf("String: %s\nHashed string: ", source_string);
    for (i = 0; i < 20; i++) printf("%02x", dest_string[i]);
    putchar('\n');
    return 0;
}

我没有通过运行这个来检查,所以可能还有其他错误。

【讨论】:

    猜你喜欢
    • 2015-04-19
    • 2018-12-30
    • 2011-09-21
    • 1970-01-01
    • 2017-05-03
    • 1970-01-01
    • 2023-04-06
    • 2011-04-22
    • 2013-04-11
    相关资源
    最近更新 更多