gpt4 book ai didi

c - 如何在 C 编程中使用 SHA1 散列

转载 作者:太空狗 更新时间:2023-10-29 16:23:34 25 4
gpt4 key购买 nike

我正在尝试编写一个 C 程序来证明 SHA1 几乎没有冲突,但我不知道如何为我的输入值实际创建哈希。我只需要创建哈希,并将十六进制值存储到一个数组中。经过一些 Google 搜索后,我发现 OpenSSL 文档指导我使用它:

 #include <openssl/sha.h>

unsigned char *SHA1(const unsigned char *d, unsigned long n,
unsigned char *md);

int SHA1_Init(SHA_CTX *c);
int SHA1_Update(SHA_CTX *c, const void *data,
unsigned long len);
int SHA1_Final(unsigned char *md, SHA_CTX *c);

我相信我应该使用 unsigned char *SHA1 或 SHA1_Init,但我不确定参数是什么,因为 x 是我要散列的输入。有人可以帮我解决这个问题吗?谢谢。

最佳答案

如果您一次拥有所有数据,只需使用 SHA1 函数:

// The data to be hashed
char data[] = "Hello, world!";
size_t length = strlen(data);

unsigned char hash[SHA_DIGEST_LENGTH];
SHA1(data, length, hash);
// hash now contains the 20-byte SHA-1 hash

另一方面,如果您一次只获取一个数据,并且您希望在收到该数据时计算哈希值,那么请使用其他函数:

// Error checking omitted for expository purposes

// Object to hold the current state of the hash
SHA_CTX ctx;
SHA1_Init(&ctx);

// Hash each piece of data as it comes in:
SHA1_Update(&ctx, "Hello, ", 7);
...
SHA1_Update(&ctx, "world!", 6);
// etc.
...
// When you're done with the data, finalize it:
unsigned char hash[SHA_DIGEST_LENGTH];
SHA1_Final(hash, &ctx);

关于c - 如何在 C 编程中使用 SHA1 散列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9284420/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com