Presenting output from md5.digest like md5sum from GNU textutils

Oleg Broytmann phd at phd.russ.ru
Mon May 29 14:40:04 CEST 2000


On Mon, 29 May 2000, [iso-8859-1] PЕl Sollie wrote:
> I am trying to write a script that is to save the checksum of all the
> specified files to a database. I'd like to convert the output I get
> from md5.digest to a human-readable format. Decimal values would be
> OK, but I'd be thrilled to get the same output as md5sum from GNU
> textutils.

   Attached. The actual algorith is Guido's.

Oleg.            (All opinions are mine and not of my employer)
---- 
    Oleg Broytmann      Foundation for Effective Policies      phd at phd.russ.ru
           Programmers don't die, they just GOSUB without RETURN.
-------------- next part --------------
#! /usr/local/bin/python
"""
   User wrapper for md5 builtin object

   Written by BroytMann, Jun 1997. Copyright (C) 1997 PhiloSoft Design
"""

from md5 import md5

class md5wrapper:
   def __init__(self, init=None):
      if init:
         self._md5 = md5(init)
      else:
         self._md5 = md5()

   def update(self, data):
      self._md5.update(data)

   def digest(self):
      return self._md5.digest()

   def __repr__(self):
      str = self.digest()
      return "%02x"*len(str) % tuple(map(ord, str))
         # This nice was suggested by Guido


   def md5file(self, f):
      if type(f) == type(''): # If f is string - use it as file's name
         infile = open(f, 'r')
      else:
         infile = f           # else assume it is opened file (fileobject) or
                              # "compatible" object (must has readline() method)

      try:
         while 1:
            buf = infile.read(16*1024)
            if not buf: break
            self.update(buf)

      finally:
         if type(f) == type(''): # If f was opened - close it
            infile.close()


if __name__ == "__main__":
   print "This must print exactly the string"
   print "Test: 900150983cd24fb0d6963f7d28e17f72"
   print "Test:", md5wrapper("abc")


More information about the Python-list mailing list