Quantcast
Viewing latest article 2
Browse Latest Browse All 12

OpenSSL SHA1 Hashing Example in C++

This tutorial will guide you on how to hash a string by using OpenSSL’s SHA1 hash function. This tutorial will create two C++ example files which will compile and run in Ubuntu environment.

  1. Here are the openssl SHA1 sample source code.

    Example #1: sha1_sample1.cpp
    #include <stdio.h>
    #include <string.h>
    #include <openssl/sha.h>
    
    int main()
    {
        unsigned char digest[SHA_DIGEST_LENGTH];
        char string[] = "hello world";
        
        SHA1((unsigned char*)&string, strlen(string), (unsigned char*)&digest);    
    
        char mdString[SHA_DIGEST_LENGTH*2+1];
    
        for(int i = 0; i < SHA_DIGEST_LENGTH; i++)
             sprintf(&mdString[i*2], "%02x", (unsigned int)digest[i]);
    
        printf("SHA1 digest: %s\n", mdString);
    
        return 0;
    }


    Example #2: sha1_sample2.cpp

    #include <stdio.h>
    #include <string.h>
    #include <openssl/sha.h>
    
    int main() {
        unsigned char digest[SHA_DIGEST_LENGTH];
        const char* string = "hello world"; 
    
        SHA_CTX ctx;
        SHA1_Init(&ctx);
        SHA1_Update(&ctx, string, strlen(string));
        SHA1_Final(digest, &ctx);
    
        char mdString[SHA_DIGEST_LENGTH*2+1];
        for (int i = 0; i < SHA_DIGEST_LENGTH; i++)
            sprintf(&mdString[i*2], "%02x", (unsigned int)digest[i]);
    
        printf("SHA1 digest: %s\n", mdString);
    
    
        return 0;
    }

  2. Let’s try to compile both sample cpp files and you should observe the following output screenshot.
    ~$ gcc sha1_sample1.cpp -o sample1 -lcrypto
    ~$ ./sample1
    SHA1 digest: 2aae6c35c94fcfb415dbe95f408b9ce91ee846ed
    ~$ gcc sha1_sample2.cpp -o sample2 -lcrypto
    ~$ ./sample2
    SHA1 digest: 2aae6c35c94fcfb415dbe95f408b9ce91ee846ed
    Note: -lcrypto will include the crypto library from openssl

Viewing latest article 2
Browse Latest Browse All 12

Trending Articles