uahakan uahakan - 6 months ago 44
Java Question

CRC32 - change initial value

I want to calculate CRC32 value of a byte array with an initial CRC value in Java, same as in this Python script:

import zlib

def getCrc32():
with open("", mode='rb') as file:
fileContent =
crcVal = zlib.crc32(fileContent,10)

if __name__ == "__main__":

But in Java, I can not get the same result with the following code:

RandomAccessFile f = new RandomAccessFile("", "r");
byte[] b = new byte[(int) f.length()];
CRC32 c2 = new CRC32();
System.out.println((int) c2.getValue());

How can I calculate CRC32 with an inital value in Java ?


You can't, at least not directly. The Java class does not provide a means for setting the current CRC value. (The reset() method should take an argument for that, but alas, it does not.)

It is possible however to derive the four message bytes that would set the CRC to a give a desired value. You could do a reset() and then an update() with those four bytes to set the CRC to what you want. The spoof code can do that for you.

spoof is a bit of overkill for this, but you can derive from that code what is needed. Really all you need is Ax + b, where A is a constant 32x32 bit matrix, x is the desired CRC, and b is a 32-bit constant, and the result is the 32 bits (four bytes) to feed in order to get the desired CRC. The matrix multiplication and vector addition are done modulo 2, where exclusive-or replaces addition and the and operator replaces multiplication.