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

标签 c hash

我正在尝试编写一个 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/

相关文章:

c++ - 求解字符串中的等式以得到 C

python - python如何在数组中具有不同的数据类型?

c - 通过插入空字符在C中分割字符串

c++ - 如何在 C++ 中使用哈希在同一个键下存储多个值

ruby - 如何仅通过多个对象的唯一组合进行迭代?

c - 为什么 OpenMP 会搞乱这个 for 循环?

c - 递归关系: find bit strings of length seven contain two consecutive 0 in C

php - 保护 PHP 登录免受重放攻击

安卓密码哈希

c# - 将密码散列到 SqlServer