2016-05-15 4 views
2

Die folgenden ausgeführt wird auf Python 2.4 und erzeugt die folgende hash: a1e48607773b80c62b80af2b6358c4faPython hashlib MD5 Inkonsistenz von Python 2.x zu Python 3?

#!/usr/bin/python 
import md5 
id=76561198302409766 
temp = "" 
for i in range(8): 
     temp += chr((id & 0xFF)) 
     id >>= 8 
m = md5.new("BE"+temp) 
print m.hexdigest() 

Dies ist der umgewandelte Code für Python 3:

#!/usr/local/bin/python3.3 -B 
import hashlib 
id = 76561198302409766 
print ("Python 2.4 output: a1e48607773b80c62b80af2b6358c4fa") 
m = hashlib.md5() 
temp = "" 
for i in range(8): 
    temp += chr((id & 0xFF)) 
    id >>= 8 
m.update("BE".encode('utf-8')+temp.encode('utf-8')) 
print ("%s" % m.hexdigest()) 

Dies erzeugt eine völlig andere Hash. Was kann ich tun, um es zu reparieren, so dass es den gleichen Hash wie das vorherige Skript erzeugt?

+0

Diese beiden Codes sind übrigens nicht identisch. Sie codieren 'temp'. – ozgur

Antwort

2

Konvertieren Sie es richtig.

import hashlib 
id = 76561198302409766 
print ("Python 2.4 output: a1e48607773b80c62b80af2b6358c4fa") 
m = hashlib.md5() 
temp = bytearray() 
for i in range(8): 
    temp.append(id & 0xFF) 
    id >>= 8 
m.update(b"BE" + temp) 
print ("%s" % m.hexdigest()) 

...

$ python3 hash.py 
Python 2.4 output: a1e48607773b80c62b80af2b6358c4fa 
a1e48607773b80c62b80af2b6358c4fa 

Oder es richtig an erster Stelle schreiben.

import hashlib 
import struct 

id = 76561198302409766 
print ("Python 2.4 output: a1e48607773b80c62b80af2b6358c4fa") 
m = hashlib.md5() 
temp = struct.pack('<Q', id) 
m.update(b"BE" + temp) 
print ("%s" % m.hexdigest()) 

...

$ python2 hash2.py 
Python 2.4 output: a1e48607773b80c62b80af2b6358c4fa 
a1e48607773b80c62b80af2b6358c4fa 
$ python3 hash2.py 
Python 2.4 output: a1e48607773b80c62b80af2b6358c4fa 
a1e48607773b80c62b80af2b6358c4fa