MD5 is 128 bit hash digest calculated by Message Digest Method 5 algorithm. It is not so secure as SHA-256 algorithm but significantly faster. It is still widely used as thumbprint to verify data integrity and detect accidental data corruption. Here is c++ example how to calculate MD5 hash of string using openssl API. Templates of MD5 hash functions are defined in evp.h openssl include file.
#include <stdio.h> #include <string.h> #include <openssl/evp.h> int main(int n, char ** s) { char md5hex[EVP_MAX_MD_SIZE * 2 + 1]; if(n<2) { printf("Please specify argument string to calculate MD5 checksum\n"); return -1; } EVP_MD_CTX * pEvpContext; pEvpContext = EVP_MD_CTX_create(); unsigned char unMdValue[EVP_MAX_MD_SIZE]; // Initialization // Calculate MD5 for given string // Save MD5 into temp variable EVP_MD_CTX_destroy(pEvpContext); // Copy the digest from the temp variable into the return value // if the size is bigger than the return buffer size, just exit for ( unsigned int i = 0; i < uiMdLength; i++ ) |
Compilation:
# g++ -o md5 md5.cpp -lssl -lcrypto |
Execution:
# ./md5 "String to calculate MD% hash" Line: String to calculate MD% hash Its MD5: 82ccf9d87f24070dd945aa5daf41f8a8 |
Compare with md5sum command:
# echo -n "String to calculate MD% hash" | md5sum 82ccf9d87f24070dd945aa5daf41f8a8 – |
Now Go example.
import ( "crypto/md5" "fmt" "os" ) func main() { |
Compilation:
C:\projects\Go\hash>go build md5.go |
Execution:
C:\projects\Go\hash>md5 “String to calculate MD% hash” 82ccf9d87f24070dd945aa5daf41f8a8 |