Python compare md5 hash
<p>I'm using the following code I found on stackoverflow which suggested is an effective way to get the md5 hash of the contents of a text file and comparing with the generated md5 hash I got from <a href="http://www.miraclesalad.com/webtools/md5.php" rel="nofollow">http://www.miraclesalad.com/webtools/md5.php</a></p>

<p>However.. it isn't returned the same md5 hash and I'm not sure where I've gone wrong. The file contents is an exact match of the text I used to generate the md5 hash so it should match but it's not returning that same match.</p>

<p>Basically, I wanted to generate a md5 hash of some text and compare it with the contents of a text file to see if it matches.</p>

<pre><code>def md5Checksum(filePath):
    with open(filePath, 'rb') as fh:
        m = hashlib.md5()
        while True:
            data = fh.read(8192)
            if not data:
                break
            m.update(data)
        return m.hexdigest()
</code></pre>

<p>If I create a text file with the contents "test" and also go to <a href="http://www.miraclesalad.com/webtools/md5.php" rel="nofollow">http://www.miraclesalad.com/webtools/md5.php</a> and type in "test" and generate a hash then compare both they are both different.</p>

<p>The hash I'm getting back is always the same no matter the contents of the file.</p>

<p>code to compare hash</p>

<pre><code>filetext = 'LOCATIONTOFILE.txt'
filemd5 = '098f6bcd4621d373cade4e832627b4f6'
if not filemd5 == md5Checksum(filetxt):
</code></pre>

<p>I've tried printing the data and both data are exactly the same too.</p>

<p>hash of <code>test</code> from website: 098f6bcd4621d373cade4e832627b4f6</p>

<p>hash of text file with the contents <code>test</code> d41d8cd98f00b204e9800998ecf8427e</p>

<p><strong>UPDATE</strong></p>

<p>Fixed the issue thanks to Adam Smith.</p>

<p>It was a ident typo and so wasn't returning the updated hashlib.</p>

<p>On windows, I did the following to reproduce.</p>

<pre><code>C:\Users\adsmith\tmp&gt;echo test&gt;test.txt
</code></pre>

<p>Then in Python:</p>

<pre><code>&gt;&gt;&gt; import hashlib
&gt;&gt;&gt; a = hashlib.md5()
&gt;&gt;&gt; b = hashlib.md5()
&gt;&gt;&gt; with open("test.txt", "rb") as fh:
...     data = fh.read()
...     a.update(data)
...
&gt;&gt;&gt; with open("test.txt", "rb") as fh:
...     data = fh.read().strip()
...     b.update(data)
...
&gt;&gt;&gt; print(a.hexdigest(), "\n", b.hexdigest())
'9f06243abcb89c70e0c331c61d871fa7'  # from b'test\r\n'
'098f6bcd4621d373cade4e832627b4f6'  # from b'test'
</code></pre>

<p>The issue is clearly caused by the line terminator in your file. This should also be a warning not to use lower-level constructs like <code>file.read(bytecount)</code> unless you have to!</p>

<pre><code>&gt;&gt;&gt; open("test.txt", 'rb').read()
# b'test\r\n'
</code></pre>

python hash md5sum