0

I found this code online for calculating md5:

#include<openssl/evp.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<iostream>

unsigned char *getMd5Hash(unsigned char *data, size_t dataLen, int *mdLen)
{
    unsigned char *md = NULL;
    EVP_MD_CTX *ctx = NULL;
    const EVP_MD *mdType = EVP_md5();
    *mdLen = EVP_MD_size(mdType);
    md = (unsigned char *) malloc(*mdLen);
    ctx = EVP_MD_CTX_create();
    EVP_MD_CTX_init(ctx);
    EVP_DigestInit_ex(ctx, mdType, NULL);
    EVP_DigestUpdate(ctx, data, dataLen);
    EVP_DigestFinal_ex(ctx, md, NULL);
    EVP_MD_CTX_cleanup(ctx);
    EVP_MD_CTX_destroy(ctx);
    return md;
}


int main()
{
    char data[1024];
    unsigned char *md;
    int i = 0, mdLen = 0;
    memset(&data, 0, 1024);
    std::cout<<"Enter string: ";
    std::cin>>data;
    md = getMd5Hash((unsigned char *)data, strlen(data), &mdLen);
    for(i = 0; i < mdLen; i++) {
        printf("%02x",md[i]);
    } printf("\n");
    return 0;
}

And I built it.

g++ aaa.cpp -lcrypto

However, the result of this code is different from the result of md5sum of Linux bash:

$ ./a.out
Enter string: aaa
47bce5c74f589f4867dbd57e9ca9f808

$ echo -e "aaa"|md5sum
5c9597f3c8245907ea71a89d9d39d08e  -

Where does this difference come from?

ar2015
  • 5,558
  • 8
  • 53
  • 110
  • possible duplicate of [bash, md5sum behaves strange](http://stackoverflow.com/questions/22886492/bash-md5sum-behaves-strange) – John Kugelman Mar 25 '15 at 22:45
  • 1
    Try this: change `char data[1024]` to `std::string data`, remove the `memset()`, change `std::cin>>data` to `std::getline(std::cin, data)`, and change `getMd5Hash((unsigned char *)data, strlen(data), &mdLen)` to `getMd5Hash((unsigned char *) data.c_str(), data.length(), &mdLen)`. – Remy Lebeau Mar 25 '15 at 22:56
  • @RemyLebeau I got it in C and made a nasty conversion to C++ very quickly. I agree with your points. – ar2015 Mar 25 '15 at 23:23

1 Answers1

2

Try echo -n. You're also hashing the end of line marker.

$ echo -e "aaa" | md5sum 
5c9597f3c8245907ea71a89d9d39d08e  -
$ echo -n "aaa" | md5sum 
47bce5c74f589f4867dbd57e9ca9f808  -
David Schwartz
  • 179,497
  • 17
  • 214
  • 278
  • Yes that's it. Now both are the same. But why didnt I see new line when I saved the data on file: `echo "aaa">data` and opening by gedit? – ar2015 Mar 25 '15 at 22:46
  • By convention text files in UNIX are supposed to have a trailing newline. It doesn't cause an extra blank line to appear. Instead, an editor might indicate if the trailing newline is *missing* (e.g., vim's "noeol" status marker). – John Kugelman Mar 25 '15 at 22:48
  • @ar2015 What did `ls -l data` show? Was it three bytes or more? – David Schwartz Mar 25 '15 at 23:16