Question

I am trying to compute the SHA1 value of a given string in C. I am using the OpenSSL library via #include <openssl/sha.h>. The relevant part of the program is below. but it shouldn't cause any issues.

void checkHash(char* tempString) {
    unsigned char testHash[SHA_DIGEST_LENGTH];
    unsigned char* sha1String = (unsigned char*)tempString;
    SHA1(sha1String, sizeof(sha1String), testHash);
    printf("String: %s\nActual hash:   86f7e437faa5a7fce15d1ddcb9eaeaea377667b8\nComputed hash: ", tempString);
// I verified the actual hash for "a" using multiple online hash generators.
    for (i = 0; i < SHA_DIGEST_LENGTH; i++)
        printf("%x", testHash[i]);
    printf("\n");
}

Running the program with checkHash("a"); yields the following output:

String: a
Actual hash:   86f7e437faa5a7fce15d1ddcb9eaeaea377667b8
Computed hash: 16fac7d269b6674eda4d9cafee21bb486556527c

How come these hashes do not match? I am running in a 64-bit Linux VM on top of a 64-bit Windows 7 machine. That has caused some problems with poor hashing implementations for me in the past but I doubt that is the issue using the OpenSSL version.

Was it helpful?

Solution

sizeof(sha1string) is the same thing as sizeof(unsigned char*), i.e. the size of a data pointer. You want to pass the string's length there, use strlen instead of sizeof, otherwise you won't be hashing what you think you're hashing.

If tempString isn't a null-terminated string but arbitrary data, you need to pass in the length of the data to checkHash, there's no way in that case to tell the length from within that function.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top