C语言正确实现字符串SHA1哈希 匹配openssl终端命令输出
问题原因&修改方案
你的代码存在两处核心错误:
SHA1函数的第二个参数为输入数据的字节长度,你错误传入了16,而echo -n "Hello World!"输出的内容实际长度为12字节,长度错误会直接导致哈希结果和终端命令不一致- SHA1计算输出的是20字节的二进制原始哈希值,不是可打印的字符串,直接用
%s打印二进制内容自然会出现乱码,需要手动将每个字节转换为两位十六进制字符后输出
修改后的完整代码
#include <stdio.h> #include <string.h> #include <openssl/sha.h> int main(void){ const unsigned char source_string[] = "Hello World!"; unsigned char hash_result[SHA_DIGEST_LENGTH]; // SHA1固定输出20字节,用宏定义更规范 // 第二个参数传入实际字符串长度,不要写死错误值 SHA1(source_string, strlen((const char*)source_string), hash_result); printf("String: %s\nHashed string: ", source_string); // 逐个字节转十六进制输出 for(int i = 0; i < SHA_DIGEST_LENGTH; i++){ printf("%02x", hash_result[i]); } printf("\n"); return 0; }
编译&运行说明
编译时需要链接openssl的crypto库:
gcc your_file_name.c -o sha1_test -lcrypto
运行后输出的哈希值就和openssl sha1命令的结果完全一致。
内容的提问来源于stack exchange,提问作者Shadoww
相关产品推荐
相关产品推荐

