Sunday, April 25, 2010

Python: MD5/SHA Signature Class

Problem Statement:
Get a class to use it for calculatin signatures of file.

Solution Code:
class Hashes:
'''
Helps in retruning the foloowing signatures of a file:
md5()
sha1()
sha256()
sha512()
'''
def __init__(self, filepath):
self._filepath = filepath
def md5(self):
import md5
try:
fileobj = file(self._filepath, 'rb')
except Exception,msg:
raise
return md5.new(fileobj.read()).hexdigest()
def sha1(self):
import sha
try:
fileobj = file(self._filepath, 'rb')
except Exception,msg:
raise
return sha.new(fileobj.read()).hexdigest()
def sha512(self):
import hashlib
try:
fileobj = file(self._filepath, 'rb')
except Exception,msg:
raise
(hashlib.sha512()).update(fileobj.read())
return (hashlib.sha512()).hexdigest()
def sha256(self):
import hashlib
try:
fileobj = file(self._filepath, 'rb')
except Exception,msg:
raise
(hashlib.sha256()).update(fileobj.read())
return (hashlib.sha256()).hexdigest()

hash = Hashes("C:\\Windows\\system32\\notepad.exe")
hash.sha1()

No comments: