Generate SHA hash in C++ using OpenSSL library


Question

How can I generate SHA1 or SHA2 hashes using the OpenSSL libarary?

I searched google and could not find any function or example code.

1
67
3/14/2015 4:51:46 PM

From the command line, it's simply:

printf "compute sha1" | openssl sha1

You can invoke the library like this:

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

int main()
{
    unsigned char ibuf[] = "compute sha1";
    unsigned char obuf[20];

    SHA1(ibuf, strlen(ibuf), obuf);

    int i;
    for (i = 0; i < 20; i++) {
        printf("%02x ", obuf[i]);
    }
    printf("\n");

    return 0;
}

73
5/20/2013 7:12:55 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon