Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between crc32() implementations of <linux/crc32.h> and <zlib.h> in C

I am calling two functions on my char* s = "pratik" as:

User code:

#include <zlib.h>
int main()
{
    char *s = "pratik";
    printf("%x\n",crc32(0x80000000, s, strlen(s)));
    return 0;
}

Output: 66fa3c99

Kernel code:

#include <linux/crc32.h>

int main()
{
    char *s = "pratik";

    u32 checksum = crc32(0x80000000, s, strlen(s));
    printk("\nChecksum --> %x", checksum);

    return checksum;
}

Output:

Checksum --> d7389d3a

Why are the values of the checksums on the same strings different?

like image 528
Raunaq Kochar Avatar asked Nov 04 '16 06:11

Raunaq Kochar


People also ask

What is CRC32 in zlib?

zlib. crc32 (data[, value]) Computes a CRC (Cyclic Redundancy Check) checksum of data. The result is an unsigned 32-bit integer. If value is present, it is used as the starting value of the checksum; otherwise, a default value of 0 is used.

What is CRC32 used for?

CRC32 is an error-detecting function that uses a CRC32 algorithm to detect changes between source and target data. The CRC32 function converts a variable-length string into an 8-character string that is a text representation of the hexadecimal value of a 32 bit-binary sequence.

What is CRC32 Python?

crc32 computes CRC-32 on binary text data. By definition, CRC-32 refers to the 32-bit checksum of any piece of data. This method is used to compute 32-bit checksum of provided data. This algorithm is not a general hash algorithm. It should only be used as a checksum algorithm.


1 Answers

It appears that someone was disturbed by the fact that the standard Ethernet (PKZIP, ITU V.42 etc. etc.) CRC-32 does a pre- and post-exclusive-or with 0xffffffff. So the version in the Linux kernel leaves that out, and expects the application to do that. Go figure.

Anyway, you can get the same result as the (correct) zlib crc32(), using the (non-standard) Linux crc32() instead, thusly:

crc_final = crc32(crc_initial ^ 0xffffffff, buf, len) ^ 0xffffffff;

In fact, that exact same code would allow you to duplicate the Linux crc32() using the zlib crc32() as well.

like image 182
Mark Adler Avatar answered Oct 08 '22 16:10

Mark Adler