''' There are various snippets of code in here for doing various hash and crc checking. I wrote none of them, mostly because I was relatively unconcerned with the detail of CRC16 and CRC31. Proper credits have been preserved. Per's SFV is a simple Simple File Verificator that you can use to verify that a file has not changed. Copyright (C) 2006 Per Myren Distributed under the GPL v2 modified by jason moiron to remove wx cruft and to allow file objects as arguments to CheckSum() usage: CheckSum(file_or_filename).getfilecrc() ''' import zlib, md5, struct, binascii, os class CRC32: def __init__(self, s=''): self.value = zlib.crc32(s) def update(self, s): self.value = zlib.crc32(s, self.value) def digest(self): return struct.pack('>I',self.value) class _CRC16: def __init__(self, s=''): self.value = crc16(s) def update(self, s): self.value = crc16(s, self.value) def digest(self): return struct.pack('>I',self.value) class CheckSum: def __init__(self, filename): self.filename = filename def _getCheckSum(self, filename, checksumtype): try: if isinstance(filename, file): f = filename elif isinstance(filename, str): f = file(filename, 'rb') while True: x = f.read(65536) if not x: #f.close() return checksumtype.digest() checksumtype.update(x) except (IOError, OSError): return "No such file" def getfilemd5(self): return binascii.hexlify(self._getCheckSum(self.filename, md5.new())) def getfilecrc(self): return binascii.hexlify(self._getCheckSum(self.filename, CRC32())) """ Modified from: http://news.hping.org/comp.lang.python.archive/18112.html Original License: crc16 by Bryan G. Olson, 2005 This module is free software and may be used and distributed under the same terms as Python itself. """ from array import array def crc16(string, value=0xffff): "Modified the default of 'value' so no inversion is necessary" for ch in string: value = crc16table[ord(ch) ^ (value & 0xff)] ^ (value >> 8) return value # CRC-16 poly: p(x) = x**16 + x**15 + x**2 + 1 # top bit implicit, reflected poly = 0xa001 crc16table = array('H') for byte in range(256): crc = 0 for bit in range(8): if (byte ^ crc) & 1: crc = (crc >> 1) ^ poly else: crc >>= 1 byte >>= 1 crc16table.append(crc)