Quantcast
Channel: askyb.com » OpenSSL
Viewing all articles
Browse latest Browse all 12

OpenSSL RIPEMD Hashing Example in C++

$
0
0

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

  1. Here are the openssl RIPEMD sample source code.

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


    Example #2: ripemd_sample2.cpp

    #include <stdio.h>
    #include <string.h>
    #include <openssl/ripemd.h>
    
    int main() {
        unsigned char digest[RIPEMD160_DIGEST_LENGTH];
        const char* string = "hello world";
    
        RIPEMD160_CTX ctx;
        RIPEMD160_Init(&ctx);
        RIPEMD160_Update(&ctx, string, strlen(string));
        RIPEMD160_Final(digest, &ctx);
    
        char mdString[RIPEMD160_DIGEST_LENGTH*2+1];
        for (int i = 0; i < RIPEMD160_DIGEST_LENGTH; i++)
            sprintf(&mdString[i*2], "%02x", (unsigned int)digest[i]);
    
        printf("RIPEMD160 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 ripemd_sample1.cpp -o sample1 -lcrypto
    ~$ ./sample1
    RIPEMD160 digest: 98c615784ccb5fe5936fbc0cbe9dfdb408d92f0f
    ~$ gcc ripemd_sample2.cpp -o sample2 -lcrypto
    ~$ ./sample2
    RIPEMD160 digest: 98c615784ccb5fe5936fbc0cbe9dfdb408d92f0f
    Note: -lcrypto will include the crypto library from openssl

Viewing all articles
Browse latest Browse all 12

Trending Articles