Uwe Ziegenhagen
Uwe Ziegenhagen

Reputation: 694

Hashing a time-string: Why not receive same results?

Why does the following code not generate at least a few identical MD5 strings:

import hashlib
import time

hasher = hashlib.md5()

def calcHash():
        localtime   = time.localtime()
        timeString  = time.strftime("%Y-%m-%d-%H-%M-%S", localtime)
        print(timeString)
        hasher.update(timeString.encode('utf-8'))
        print("Calculated: " + hasher.hexdigest())

for i in range(1,10):
        calcHash()

I am feeding not the time stamp, but the generated string to the hasher. I'd expect identical MD5 hashes if I feed the same string twice to the hasher.

2015-04-26-09-50-24 Calculated: 52cae4a4231c812e5b79102a55721282 2015-04-26-09-50-24 Calculated: 0329298a8a18246fc1fc2f9878252dcf 2015-04-26-09-50-24 Calculated: 3db4562ca628a76c863f1308b8c41b04 2015-04-26-09-50-24 Calculated: 51c482a637405897cd5d91f2145e424f 2015-04-26-09-50-24 Calculated: 297eb85857fc85533a785fb13c200bdc 2015-04-26-09-50-24 Calculated: 4288a660c70ee9ed40a8e7611176af91 2015-04-26-09-50-24 Calculated: 4b998d607dba97578447d21cd82f6f33 2015-04-26-09-50-24 Calculated: 45b93b13df62be5e3616ee89b7e803cc 2015-04-26-09-50-24 Calculated: 0dbce249b10195b2a28b1825032e455c

Upvotes: 1

Views: 34

Answers (1)

gzm0
gzm0

Reputation: 14842

You are not resetting the hasher. Therefore, the subsequent hashes are the hashes of the accumulated strings.

Change to:

def calcHash():
        hasher = hashlib.md5()
        localtime   = time.localtime()
        timeString  = time.strftime("%Y-%m-%d-%H-%M-%S", localtime)
        print(timeString)
        hasher.update(timeString.encode('utf-8'))
        print("Calculated: " + hasher.hexdigest())

Upvotes: 4

Related Questions