title: Calculate MD5 of a string in C++
body: <p>I have a nice example of memory mapped files that calculates the MD5 hash of a file. That works fine with no problems.</p>
  
  <p>I would like to change it to calculate the MD5 hash of a string.</p>
  
  <p>So the example is:</p>
  
  <p>(include <code>#include &lt;openssl/md5.h&gt;</code> to run this code, and also boost stuff if you want to run the one with the file)</p>
  
  <pre><code>unsigned char result[MD5_DIGEST_LENGTH];
  boost::iostreams::mapped_file_source src(path);
  MD5((unsigned char*)src.data(), src.size(), result);
  
  std::ostringstream sout;
  sout&lt;&lt;std::hex&lt;&lt;std::setfill('0');
  for(long long c: result)
  {
      sout&lt;&lt;std::setw(2)&lt;&lt;(long long)c;
  }
  return sout.str();
  </code></pre>
  
  <p>The change I made is:</p>
  
  <pre><code>std::string str("Hello");
  unsigned char result[MD5_DIGEST_LENGTH];
  MD5((unsigned char*)str.c_str(), str.size(), result);
  
  std::ostringstream sout;
  sout&lt;&lt;std::hex&lt;&lt;std::setfill('0');
  for(long long c: result)
  {
      sout&lt;&lt;std::setw(2)&lt;&lt;(long long)c;
  }
  return sout.str();
  </code></pre>
  
  <p>But this produces the result:</p>
  
  <pre><code>8b1a9953c4611296a827abf8c47804d7
  </code></pre>
  
  <p>While the command <code>$ md5sum &lt;&lt;&lt; Hello</code> gives the result:</p>
  
  <pre><code>09f7e02f1290be211da707a266f153b3
  </code></pre>
  
  <p>Why don't the results agree? Which one is wrong?</p>
  
  <p>Thanks.</p>
  
  <hr>
  
  <p>EDIT:</p>
  
  <p>So I got the right answer which is ticked down there. The correct way to call <code>md5sum</code> from terminal is:</p>
  
  <pre><code>$ printf '%s' "Hello" | md5sum
  </code></pre>
  
  <p>To avoid the new line being included.</p>