Saturday, August 1, 2009

Computing MD5 sum in Python

So, you're writing some Python code which requires computation of an MD5 sum of a given input file. Don't worry, it's quite easy. Following are two ways to achieve this.

Method one: compute the MD5 sum using Python's APIs:
infile = open("filename", 'rb')
content = infile.read()
infile.close()
m = hashlib.md5() # don't forget to "import hashlib"
m.update(content)
md5 = m.hexdigest() # now the md5 variable contains the MD5 sum

Method two: using the OS command `md5` on Linux, or the Windows command line utility available for download:
p = subprocess.Popen("md5 " + "filename", shell = True, stdout=subprocess.PIPE) # don't forget to "import subprocess"
md5 = p.stdout.readline().split() # now the md5 variable contains the MD5 sum
p.wait() # some clean up

That all folks.

3 comments:

  1. Great post! exactly what i needed

    r. atias

    ReplyDelete
  2. Was using the md5 module before..
    Thank you.

    http://vimalkumar.in

    ReplyDelete
  3. In newer versions you can do:

    hashlib.md5("password").hexdigest()

    Good post, though; it led me to what I needed.

    ReplyDelete