Generate SHA hash in C++ using OpenSSL library

Jon Duwok picture Jon Duwok · May 28, 2009 · Viewed 101.7k times · Source

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

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

Answer

brianegge picture brianegge · May 28, 2009

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;
}