Python equivalent of Perl Digest::MD5 functions
<p>As part of a work project I am porting a Perl library to Python.  I'm comfortable with Python, much (much) less so with Perl.</p>

<p>The perl code uses <a href="https://metacpan.org/pod/Digest::MD5" rel="nofollow">Digest::MD5</a>.  This module has three functions:</p>

<ul>
<li><code>md5($data)</code>  takes in data and spits out md5 digest in <em>binary</em></li>
<li><code>md5_hex($data)</code> takes in data and spits out md5 digest in <em>hex</em></li>
<li><code>md5_base64($data)</code> takes in data and spits out md5 digest in base64 encoding</li>
</ul>

<p>I can replicate md5_hex with something like this:</p>

<pre><code>import hashlib
string = 'abcdefg'
print(hashlib.md5(string.encode()).hexdigest())
</code></pre>

<p>Which works fine (same inputs give same outputs at least).  I can't seem to get anything to match for the other two functions.  </p>

<p>It doesn't help that string encodings are really not something I've done much with.  I've been interpreting the perl functions as saying they take an md5 digest and then re-encode in binary or base64, something like this:</p>

<pre><code>import hashlib
import base64
string = 'abcdefg'
md5_string = hashlib.md5(string.encode()).hexdigest()
print(base64.b64encode(md5_string))
</code></pre>

<p>but maybe that's wrong?  I'm sure there's something fundamental I'm just missing.  </p>

<p>The Perl doc is here:
<a href="https://metacpan.org/pod/Digest::MD5" rel="nofollow">https://metacpan.org/pod/Digest::MD5</a></p>

<p>The first one would simply be calling <code>.digest</code> method on the <code>md5</code>:</p>

<pre><code>&gt;&gt;&gt; from hashlib import md5
&gt;&gt;&gt; s = 'abcdefg'
&gt;&gt;&gt; md5(s.encode()).digest()
b'z\xc6l\x0f\x14\x8d\xe9Q\x9b\x8b\xd2d1,Md'
</code></pre>

<p>And <code>md5_base64</code> is the digest but base64-encoded:</p>

<pre><code>&gt;&gt;&gt; base64.b64encode(md5(s.encode()).digest())
b'esZsDxSN6VGbi9JkMSxNZA=='
</code></pre>

<p>However, Perl doesn't return the hash padded, thus to be compatible, you'd strip the <code>=</code> padding characters:</p>

<pre><code>&gt;&gt;&gt; base64.b64encode(md5(s.encode()).digest()).strip(b'=')
b'esZsDxSN6VGbi9JkMSxNZA'
</code></pre>

python string perl encoding md5