Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does sha1 return a different hash for the same input string?

Tags:

c

hash

sha1

This is a very simple program that takes a integer and converts it to a string. From there I hash the string using SHA1 and print the hash to the console. But when I rerun the program, I get a different hash for the same integer that was defined in my program. Any idea why this is happening and how could I fix it?

This is my program. To compile I use: gcc -o myhash myhash.c -lcrypto

int main (int argc, char* argv[]){

    //sha1 returns 20 byte hash
    unsigned char myHash[SHA_DIGEST_LENGTH];

    //my integer that I want to hash
    int myInt = -1613543;

    //convert to char string
    char input[50]; 
    snprintf(input,50,"%d",myInt);

    //compute hash
    SHA1(input,sizeof(input),myHash);

    //print hash
    int i;
    for(i=0;i<SHA_DIGEST_LENGTH;i++){

        printf("%02x", myHash[i]);
    }
    printf("\n");

    return 0;

}

1 Answers

Your SHA-1 calculation includes garbage memory.

char input[50]; 
snprintf(input,50,"%d",myInt);

Here you initialize a few bytes at the beginning, terminated by \0. But the trailing memory is not initialized. You could do this by using an explicit array initializer (char input[50] = { 0 };) or by calling memset(input, 0, sizeof(input)).

//compute hash
SHA1(input,sizeof(input),myHash);

Here you calculate the SHA-1 hash over the full 50-byte input. Perhaps you want to use strlen(input) instead of sizeof(input)?

Finally a hint: use a known working tool as reference. For instance:

$ echo -n -1613543 | sha1sum 
e3f0005827c95440fb6a9045b400d3b2d64001f8  -
$ echo -n -1613543 | openssl sha1
(stdin)= e3f0005827c95440fb6a9045b400d3b2d64001f8
like image 150
Lekensteyn Avatar answered Sep 24 '26 09:09

Lekensteyn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!