I am trying to use the crc32_combine
function from zlib in Python.
Although various other zlib functions are available,
this one isn't part of the "batteries included" standard library.
I've tried two approaches: a port from the C code to Python and
calling zlib from Python with ctypes. Both give me different results,
although not the result I'm expecting.
I'm presenting the ctypes code since I think this executes faster and has a
smaller chance for additional programmer errors.
The algorithm can combine two CRC32 hashes when the length of the data of the second hash is provided. crc32_combine is defined as follows:
crc32(crc32(0, seq1, len1), seq2, len2) == crc32_combine(
crc32(0, seq1, len1), crc32(0, seq2, len2), len2)
This is the output:
Expected CRC: 45E57586
Combined CRC: 567EE4E4
The second line is always different when ran with Python 3.5.1 on win32. Not with Python 2, but the result is never what I expect either. Put the zlib1.dll in the same directory as the script to try it out.
import zlib
def crc32_combine_ctypes(crc1, crc2, len2):
import ctypes
from ctypes import util
lib = util.find_library('zlib1')
_zlib = ctypes.CDLL(lib)
assert _zlib._name, "Can't find zlib"
_zlib.crc32_combine.argtypes = [
ctypes.c_ulong, ctypes.c_ulong, ctypes.c_ulong]
_zlib.crc32_combine.restype = ctypes.c_ulong
return _zlib.crc32_combine(crc1, crc2, len2)
testfile = "zlib1.dll"
with open(testfile, "rb") as tf:
data = tf.read()
print("Expected CRC: %0.8X" % (zlib.crc32(data) & 0xFFFFFFFF))
cut = len(data) // 2 - 100
p1 = data[0:cut]
p2 = data[cut:]
crc1 = zlib.crc32(p1)
crc2 = zlib.crc32(p2)
len1 = len(p1)
len2 = len(p2)
combined = crc32_combine_ctypes(crc1, crc2, len2)
print("Combined CRC: %0.8X" % (combined & 0xFFFFFFFF))
What am I doing wrong?