Search code examples
pythonmd5hashlib

Python creating md5 hashes from a list or text


when it's a string in the script it generates it correctly like:

result = hashlib.md5(b"12345")
print(result.hexdigest())

this is: 827ccb0eea8a706c4c34a16891f84e7b as it should be but when it comes to read a word from a list or a text it doesnt give the correct md5 hash. I tried to strip "\n" but it didnt work. What should i do? What would you do if you were to generate md5 hashes from a text?

import hashlib

result = hashlib.md5()

with open("text.txt", mode="r", encoding="utf-8") as f:
    for line in f:
        line.strip("\n")

        result.update(line.encode())
        result_md5 = result.hexdigest()


        print(result.hexdigest())

output is: 4528e6a7bb9341c36c425faf40ef32c3

b6cef2a8d7cd668164035a08af6eab17

f44b0df2bb9752914ceac919ae4ca5e5

text file:

pass
12345
password

expected output is:

1a1dc91c907325c69271ddf0c944bc72
827ccb0eea8a706c4c34a16891f84e7b
5f4dcc3b5aa765d61d8327deb882cf99

Solution

  • You want an MD5 hash independently for each line.

    import hashlib
    
    with open("text.txt", mode="r", encoding="utf-8") as f:
        for line in f:
            line = line.rstrip("\r\n")
            result = hashlib.md5(line.encode())
            print(result.hexdigest())