Simple program to get sha256 hash

Paolo Bolzoni paolo.bolzoni.brown at gmail.com
Thu Mar 16 23:47:01 CET 2017


Dear list,

Today I wanted to play a bit with libgcrypt and I wanted
to make a small program to return the sha256 hash of a
string passed as argument.

The program compiles, links, and gives an output.
However, the output is different than what I get using
sha256sum from coreutils!

Here is what I see in my shell:
$ gcc -o ssha  ./hash.cpp -lgcrypt
$ ./ssha blablabla
a6898dd93b4c6a87e978aea8547fdc3901b7b94d96636e03d5a6194f4491c571
$ sha256sum <<< 'blablabla'
a5edca3a5b8fb54ae61d236a5274626ba6a38781573e02202000158faa707191  -
$

hash.cpp contains the code I copied in the bottom of the email.

What am I missing? Isn't expected to have the same hash code?

Yours faithfully,
Paolo


---------- >8
#include <stdio.h>
#include <gcrypt.h>

int main(int argc, char** argv) {
    if (argc < 2) return 1;

    gcry_md_hd_t context;
    gcry_md_open(&context, GCRY_MD_SHA256, 0);

    char* c = argv[1];
    while (*c != '\0') {
        ++c;
        gcry_md_putc(context, *c); }

    unsigned char* csha  = gcry_md_read(context, GCRY_MD_SHA256);
    for (int i = 0; i < 32; ++i) {
        printf("%02x", csha[i]); }
    printf("\n");

    gcry_md_close(context); }



More information about the Gnupg-users mailing list