0

So I need to compute a CRC32 checksum of an ELF file, and I'm just struggling with C a bit. First thing I need to figure out is the best way to get the data into the checksum algorithm. If the ELF file is arbitrary size, and I'm trying to read it in binary, what's the best way to store that data so I can give it to the checksum formula? Thanks.

Here's what I have as of now.

#include <stdio.h>
#include <stdint.h>

typedef uint32_t crc;

#define WIDTH  (8 * sizeof(crc))
#define TOPBIT (1 << (WIDTH - 1))
#define POLYNOMIAL 0x04C11DB7


crc crc32(uint32_t const message[], int nBytes)
{
    int byte;
    crc  remainder = 0;
    for (byte = 0; byte < nBytes; ++byte)
    {
        remainder ^= (message[byte] << (WIDTH - 8));

        uint32_t bit;
        for (bit = 8; bit > 0; --bit)
        {
            if (remainder & TOPBIT)
            {
                remainder = (remainder << 1) ^ POLYNOMIAL;
            }
            else
            {
                remainder = (remainder << 1);
            }
        }
    }
    printf("%X",remainder);
    return (remainder);
}




int main(int argc, char* argv[])
{

   FILE *elf; 


   elf=fopen(argv[1],"rb");

   uint32_t buffer[10000];

   fread(buffer,sizeof(char),sizeof(buffer),elf);

   crc32(buffer,10000);
}

It outputs a hex value, but its definitely wrong. I'm guessing its definitely not reading in the file correctly.

  • Just copy the code [from here](https://rosettacode.org/wiki/CRC-32#Library) or use the one built into zlib. – selbie Oct 20 '18 at 03:24
  • There are many possible CRC-32's. How do you know the result is wrong? Do you have examples with the correct CRC-32? Is your input exactly 10000 bytes long? If not, you are incorrectly ignoring the result of `fread()`, which is the number of bytes read. – Mark Adler Oct 20 '18 at 21:47
  • So fread outputs the amount of data read, but I think I'm a little confused because isn't the 3rd argument in fread the amount of elements to read at the specified size? So don't I need to know the size in order to even use fread in the first place? Thanks for the help.... Also yes I have an example of the intended CRC output. It's just not what I'm getting. And no, the 10000 was just a placeholder because I don't know how to take an arbitrary length. I get different values based on the size I use. – Ethan Burke Oct 20 '18 at 22:18
  • Step 1: Put the example and the expected CRC of the sample in the question. – Mark Adler Oct 21 '18 at 16:22
  • No, you don't need to know the size of the input to use `fread()`. It will read, in your example, up to 10,000 bytes. If the input is shorter than that, it will return the size of the input. Normally `fread()` is used in a loop, reading chunks from the file until it has all been read. The last `fread()` will generally return less than the chunk size. – Mark Adler Oct 21 '18 at 16:25

0 Answers0