Shadoww
Shadoww

Reputation: 171

Correctly hashing a string in C

When using the terminal utility "openssl" with the following command:

echo -n "Hello World!" | openssl sha1

This is the output produced:

(stdin)= 2ef7bde608ce5404e97d5f042f95f89f1c232871

I've tried producing the same output with following C code:

#include <stdio.h>
#include <stdlib.h>
#include <openssl/sha.h>

int main(void){
    const unsigned char source_string[1024] = "Hello World!";
    unsigned char dest_string[1024];
    SHA1(source_string, 16, dest_string);
    printf("String: %s\nHashed string: %s\n", source_string, dest_string);
    return 0;
}

However, it produces this weird non-unicode output:

String: Hello World!
Hashed string: #�V�#��@�����T\�

How can I make it produce the same output as the before shown openssl terminal command?

Upvotes: 0

Views: 65

Answers (1)

MikeCAT
MikeCAT

Reputation: 75062

You should

  • Pass the correct length of the string (it is 12-byte long) to SHA1.
  • Print the result in hexadecimal, not as string.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/sha.h>

int main(void){
    const unsigned char source_string[1024] = "Hello World!";
    unsigned char dest_string[1024];
    int i;
    SHA1(source_string, strlen((const char*)source_string), dest_string);
    printf("String: %s\nHashed string: ", source_string);
    for (i = 0; i < 20; i++) printf("%02x", dest_string[i]);
    putchar('\n');
    return 0;
}

I didn't check by running this, so there may be other errors.

Upvotes: 2

Related Questions