如何在 C 编程中使用 SHA1 散列 [英] How to use SHA1 hashing in C programming

查看:15
本文介绍了如何在 C 编程中使用 SHA1 散列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to write a C program that proves SHA1 is nearly collision free, but I cannot figure out how to actually create the hash for my input values. I just need to create the hash, and store the hex value into an array. After some Google searches, I've found OpenSSL documentation directing me to use this:

 #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 是我要散列的输入.有人可以帮我解决这个问题吗?谢谢.

I believe I should be using either unsigned char *SHA1 or SHA1_Init, but I am not sure what the arguments would be, given x is my input to be hashed. Would someone please clear this up for me? Thanks.

推荐答案

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

If you have all of your data at once, just use the SHA1 function:

// 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

另一方面,如果您一次只获取一个数据,并且希望在接收数据时计算散列,则使用其他函数:

If, on the other hand, you only get your data one piece at a time and you want to compute the hash as you receive that data, then use the other functions:

// 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 编程中使用 SHA1 散列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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