Frage

I have a list of ids that I want to append with the string 'text'. I want to check if any of the ids (after being appended with the 'text' string) equals to the string 'text_compare'.

What the weird thing is that the string before the hashing takes place are equal, but after the hashing takes place, the hashing seem to not have produced the same results. Below are my code. You can test it on the Python command-line.

import hashlib
h = hashlib.sha512()

text = 'beruk makye'
text_compare = '3beruk makye'
text_compare_hash = h.update(text_compare)
text_compare_hash = h.hexdigest()

ids = [1,2,3]
texts = []
bool_text = []
bool_text_hash = []

for id in ids:
    texts.append(str(id) + text)

for t in texts:
    if t == text_compare:
        bool_text.append(True)
    else:
        bool_text.append(False)

for t in texts:
    h.update(t)
    t_hash = str(h.hexdigest())
    if t_hash == text_compare_hash:
        bool_text_hash.append(True)
    else:
        bool_text_hash.append(False)

print ids
# [1, 2, 3]
print texts
# ['1beruk makye', '2beruk makye', '3beruk makye']
print bool_text
# [False, False, True]
print bool_text_hash
# [False, False, False]
War es hilfreich?

Lösung

Your issue is that you are re-using the same hash object, so you just keeping adding to it. Each time you should instantiate a new sha512() object. The code below works correctly.

import hashlib
h = hashlib.sha512()

text = 'beruk makye'
text_compare = '3beruk makye'
text_compare_hash = h.update(text_compare)
text_compare_hash = h.hexdigest()

ids = [1,2,3]
texts = []
bool_text = []
bool_text_hash = []

for id in ids:
    texts.append(str(id) + text)

for i in texts:
    hash = hashlib.sha512(i).hexdigest()
    print i, hash, hash == text_compare_hash

Andere Tipps

The problem here is that h is already created and later you add strings to it, by calling update() method.

To fix that, you can eg. re-initialize h as new sha512 hash:

# ...
for t in texts:
    h = hashlib.sha512()  # <--- here
    h.update(t)
    t_hash = str(h.hexdigest())
    if t_hash == text_compare_hash:
        bool_text_hash.append(True)
    else:
        bool_text_hash.append(False)
# ...

You are missing this line: h = hashlib.sha512()

right before h.update(t)

If you check the python docs (http://docs.python.org/2/library/hashlib.html) it explains that update will return the digest of all the strings given to the hashlib so far. So in your case the strings you are hashing are:

loop1: '1beruk makye'

loop2: '1beruk makye2beruk makye'

loop3: '1beruk makye2beruk makye3beruk makye'

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top