When you transfer a large file across a network, download a software patch, or copy data to an external hard drive, there is always a risk that a few bytes of data might become corrupted during the transit. If you are dealing with a text document, a corrupted byte might just mean a misspelled word. If you are dealing with a compiled software binary, a corrupted byte will cause the entire application to crash. To cryptographically verify that a file has not been altered or corrupted in any way, you can use the Linux cksum command.
How the cksum Command Works
The cksum utility reads the raw binary contents of a file and uses a mathematical algorithm to calculate a Cyclic Redundancy Check (CRC) value. This value is a unique fingerprint for that specific file. If even a single byte of data inside the file changes, the resulting CRC fingerprint will change dramatically.
To calculate the checksum of a file, simply type the command followed by the filename:
cksum important_backup.tar.gz
The command will output three distinct pieces of information separated by spaces:
3819203817 1048576 important_backup.tar.gz
- 3819203817: This is the CRC checksum (the unique fingerprint).
- 1048576: This is the exact byte count (size) of the file.
- important_backup.tar.gz: The name of the file you checked.
How to Verify File Integrity
The primary use case for cksum is verifying a file after a transfer.
- Before transferring a critical file from Server A, run
cksumon it and write down the resulting CRC number. - Transfer the file to Server B via SCP, FTP, or a USB drive.
- Log into Server B and run
cksumon the newly transferred file.
If the CRC number on Server B perfectly matches the CRC number from Server A, you can be 100% mathematically certain that the file transferred flawlessly. If the numbers differ, the file was corrupted in transit and you must transfer it again.
Calculating Checksums for Multiple Files
If you are backing up an entire directory of critical configuration files and you want to record the fingerprints for all of them simultaneously, you can pass multiple arguments to the command, or use wildcards.
cksum *.conf > checksum_records.txt
This command will calculate the unique CRC fingerprint for every single .conf file in your current directory and save the resulting list into a text file called checksum_records.txt. You can keep this record safe, and if a server is ever compromised, you can re-run the cksum command to see if any configuration files were secretly modified by an attacker.