Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use SHA1 hashing in C programming

Tags:

c

hash

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); 

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.

like image 630
spassen Avatar asked Feb 14 '12 21:02

spassen


People also ask

What SHA1 method is used to create a hash value?

SHA-1 or Secure Hash Algorithm 1 is a cryptographic hash function which takes an input and produces a 160-bit (20-byte) hash value. This hash value is known as a message digest.

What does a SHA1 hash look like?

What does a SHA1 hash look like? The SHA1 algorithm generates a 160-bits message digest, represented as a 40 characters hexadecimal number. For example, “A94A8FE5CCB19BA61C4C0873D391E987982FBBD3” is a SHA1 hash.

What is secure hash algorithm SHA 1 )? Explain 5 steps which are required to obtain secure hash?

Techopedia Explains Secure Hash Algorithm 1 (SHA-1) SHA-1 produces a 160-bit hash value or message digests from the inputted data (data that requires encryption), which resembles the hash value of the MD5 algorithm. It uses 80 rounds of cryptographic operations to encrypt and secure a data object.


1 Answers

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); 
like image 200
Adam Rosenfield Avatar answered Sep 19 '22 11:09

Adam Rosenfield