How to Calculate CRC32 Checksum in Java

Cyclic Redundancy Check (CRC) is an error detection technique commonly used to detect any changes to raw data. CRC checksum is a short fixed length data derived from a larger block of data. If there is a change in original raw data, the computed CRC checksum will differ from the CRC checksum received from the source. This technique is used to detect data errors when a file is read from a storage system. Each file stored in the file system also has the checksum stored along with the content. If the checksum is different when calculated on the file content, we know that the file on the disk is corrupted.

There are differences between CRC checksums and common hash functions such as MD5 and SHA1. CRC checksums are simpler and faster to compute. However they are not cryptographically secure. Hence CRC checksums are used in data error detection while hash functions are used in encryption algorithms.

CRC32 algorithm returns a 32-bit checksum value from the input data. It is very easy to calculate CRC32 checksum of a given string in Java. The following example program generates CRC32 checksum using the built-in class java.util.zip.CRC32.

Java Source Code for CRC32 Checksum Calculation

import java.util.zip.CRC32;

// Calculates CRC32 checksum for a string
public class CRC32Generator {

    public static void main(String[] args) {
        String input = "Hello World!";
        CRC32 crc = new CRC32();
        crc.update(input.getBytes());
        System.out.println("input:"+input);
        System.out.println("CRC32:"+crc.getValue());
    }
}

Here is the output of the program,

input:Hello World!
CRC32:472456355

Do you have a programming problem that you are unable to solve? Please send us your problem and we will publish the solution! Please email us.

Leave a Reply