user3791463
user3791463

Reputation: 33

Simple Python inquiry - MD5 hashing

I'm trying write a little python script to hash some words. I'm using hashcat to verify my outputs and something is wrong and it should be very simple process to do.. but I can't identify what I have done incorrectly. Only the last hash of my outputs is getting hashed correctly. When using "123456" as a test for 5 lines in my sample file I get the following output:

f447b20a7fcbf53a5d5be013ea0b15af

f447b20a7fcbf53a5d5be013ea0b15af

f447b20a7fcbf53a5d5be013ea0b15af

f447b20a7fcbf53a5d5be013ea0b15af

e10adc3949ba59abbe56e057f20f883e

Can someone point out the error of my ways. Would be greatly appreciated.

import hashlib


my_file = open("sample.txt" , "r")

for line in my_file:
    try:
        hash_object = hashlib.md5(line)
        print(hash_object.hexdigest())

    except:
        print "Error"

my_file.close()

Upvotes: 3

Views: 640

Answers (2)

Alex
Alex

Reputation: 21766

You get a different hash for the first four lines because you include the carriage return is in the MD5 hash calculation. The last line does not have this carriage return and therefore returns a different value. Simply remove the carriage return using strip() and you will get the same hash for all five lines:

import hashlib


my_file = open("sample.txt" , "r")

for line in my_file:
    try:
        hash_object = hashlib.md5(line.strip())
        print(hash_object.hexdigest())

    except:
        print "Error"

my_file.close()

This gives as output:

e10adc3949ba59abbe56e057f20f883e
e10adc3949ba59abbe56e057f20f883e
e10adc3949ba59abbe56e057f20f883e
e10adc3949ba59abbe56e057f20f883e
e10adc3949ba59abbe56e057f20f883e

Upvotes: 2

Harshil Lodhi
Harshil Lodhi

Reputation: 7790

The problem with your code is that you are hashing the whole line i.e. "123456\n" which contains '\n' in the end.

The last line doesn't contain a '\n' that is why its hash is matching with the hash of "123456"

Try to trim the lines before hashing and you are good to go.

Change hash_object = hashlib.md5(line) to hash_object = hashlib.md5(line.strip()).

Upvotes: 1

Related Questions