0

Good morning, So, I created a MD5 hash from a TXT file. After changing the file content inserting new values, I tried to create a MD5 hash again, but the value didn't change. What could I do?

My code:

from hashlib import md5

open_file = open('N0003966.290', 'r', encoding='ISO-8859-1')
file = open_file.read().lower().rstrip('\n\r ').strip('\n\r')

m = md5()
m.update(b'file')
print(m.hexdigest())

I need to follow some requirements to build this hash, such as:

  • The encoding rule must be 'ISO-8859-1'
  • All the characters must be lowercase
  • New line characters and carriage return characters must NOT be considered on hash building

4 Answers4

2

You are calling update on the string 'file' rather than the content of the file. Do this instead:

from hashlib import md5

open_file = open('N0003966.290', 'r', encoding='ISO-8859-1')
file_content = open_file.read().lower().rstrip('\n\r ').strip('\n\r')

m = md5()
m.update(file_content.encode('ISO-8859-1'))
print(m.hexdigest())

Also note I replace your variable file by file_content (it is bad practice to override a built-in name).

DevShark
  • 8,558
  • 9
  • 32
  • 56
1
m.update(b'file')

This line is the problem. You're calling the function on the string 'file' represented as bytes (see this question, for example, for more on what that means), not on the data within the file.

If you replace it with

m.update(file)

you should get the results you want (although, as DevShark points out, you should also change the name of that variable to something that doesn't already have its own meaning).

Community
  • 1
  • 1
Chris H
  • 790
  • 9
  • 19
0
m.update(file.encode('ISO-8859-1'))
gipsy
  • 3,859
  • 1
  • 13
  • 21
0

This code works in python 2.7 too.

from hashlib import md5

open_file = open('a.txt', 'r')
file = open_file.read().lower().rstrip('\n\r ').strip('\n\r')

m = md5()
m.update(file)
print(m.hexdigest())

m.update(b'file') is the place where you got error replace it with m.update(file).

Karthikeyan KR
  • 1,134
  • 1
  • 17
  • 38