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

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

问题描述

我试图写证明SHA1是免费的近碰撞C程序,但我想不出如何实际创建我的输入值的哈希值。我只需要创建哈希和十六进制值存储到一个数组。一些谷歌搜索后,我发现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);

我相信我应该是使用操作无符号的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 = sizeof(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);

这篇关于如何使用SHA1散列C编程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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