The SHA-256 standard is used in document integrity checks. It’s preferred over the SHA-1 standard, since the latter has been shown to produce the same hash for different documents.
In this tutorial, we’ll explore SHA-256 hash generation using the sha256sum command.
2. Generate SHA-256 Hashes for Files
We can use the sha256sum command in two modes, binary and text (the default). On Linux, both modes generate the same SHA-256 hash, so the default mode is used throughout this article.
Let’s create a text file with some simple text in it, and use this to demonstrate how the command works:
$ echo -n "https://baeldung.com" > data.txt
We’re using the -n option to instruct echo not to output the trailing newline (\n).
Then we’ll create the sha-256 hash for the above file:
$ sha256sum data.txt a971e147ef8f411b4a2476bba1de26b9a9a84553c43a90204f662ca72ee93910 data.txt
This generated output consists of:
- the hash sum, the first 65 characters
- an asterisk (only in binary mode)
- the path to the file or just the name of the file
We can also generate the hash for a file in a directory:
$ sha256sum /path/to/data.txt > checksum
Then use the cat command to display the contents:
$ cat checksum 86c5ceb27e1bf441130299c0209e5f35b88089f62c06b2b09d65772274f12057 /path/to/data.txt
3. Verify File Integrity
We’ll use the hash stored in the checksum file to verify the integrity of the data.txt file that we hashed:
$ sha256sum --check checksum data.txt: OK
Next, we’ll modify the information contained in data.txt to simulate a failed test. We’ll use the sed command to replace “https” with “http”:
$ sed -i 's/https/http/' data.txt
Finally, we’ll check the file’s integrity again:
$ sha256sum --check checksum data.txt: FAILED sha256sum: WARNING: 1 computed checksum did NOT match
3.1. Dealing With Multiple Files
Let’s add another entry in the checksum file for another file. We’ll do this by adding a simple text to a new file, generating the digest for that new file, and appending it to the checksum file:
$ echo "https://google.com" > data2.txt sha256sum data2.txt >> checksum
Now if we do integrity tests for all the entries in the checksum file, it will process each one of the entries, telling us which files fail the test, and which pass:
$ sha256sum --check checksum data.txt: FAILED data2.txt: OK sha256sum: WARNING: 1 computed checksum did NOT match
In this article, we learned how to use the sha256sum command to check the integrity of files by generating an SHA-256 hash digest. Then we stored the output in a file, and used it to check for file integrity.
Finally, we demonstrated how to test the integrity of multiple files.