This tutorial will guide you on how to hash a string by using OpenSSL’s SHA224 hash function. This tutorial will create two C++ example files which will compile and run in Ubuntu environment.
- Here are the openssl SHA224 sample source code.
Example #1: sha224_sample1.cpp#include <stdio.h> #include <string.h> #include <openssl/sha.h> int main() { unsigned char digest[SHA224_DIGEST_LENGTH]; char string[] = "hello world"; SHA224((unsigned char*)&string, strlen(string), (unsigned char*)&digest); char mdString[SHA224_DIGEST_LENGTH*2+1]; for(int i = 0; i < SHA224_DIGEST_LENGTH; i++) sprintf(&mdString[i*2], "%02x", (unsigned int)digest[i]); printf("SHA224 digest: %s\n", mdString); return 0; }
Example #2: sha224_sample2.cpp#include <stdio.h> #include <string.h> #include <openssl/sha.h> int main() { unsigned char digest[SHA224_DIGEST_LENGTH]; const char* string = "hello world"; SHA256_CTX ctx; SHA224_Init(&ctx); SHA224_Update(&ctx, string, strlen(string)); SHA224_Final(digest, &ctx); char mdString[SHA224_DIGEST_LENGTH*2+1]; for (int i = 0; i < SHA224_DIGEST_LENGTH; i++) sprintf(&mdString[i*2], "%02x", (unsigned int)digest[i]); printf("SHA224 digest: %s\n", mdString); return 0; }
- Let’s try to compile both sample cpp files and you should observe the following output screenshot.
Note: -lcrypto will include the crypto library from openssl~$ gcc sha224_sample1.cpp -o sample1 -lcrypto
~$ ./sample1
SHA224 digest: 2f05477fc24bb4faefd86517156dafdecec45b8ad3cf2522a563582b
~$ gcc sha224_sample2.cpp -o sample2 -lcrypto
~$ ./sample2
SHA224 digest: 2f05477fc24bb4faefd86517156dafdecec45b8ad3cf2522a563582b