Unix / Linux: Generate MD5 Checksum

The md5sum command can be used to generate MD5 checksums for a string or a file. This is installed by default on most Unix and Linux distributions.

Generate MD5 Checksum for a String

To generate a MD5 checksum for a string, use the following syntax:

Note the use of the “-n” option for the echo command. Without that option, a trailing newline (“\n”) will be added to the string and the MD5 hash will be totally different.

The MD5 algorithm is a hash function and not an encryption function, so the MD5 checksum will always be the same for the same input. We can verify this by checking the MD5 checksum using python.

Generate MD5 Checksum for a File

To generate a MD5 checksum for a file, we just need to pass the location of the file to the md5sum utility.

Be careful when checking the MD5 checksums of a text file. The format of text files are different on Unix/Linux and Windows. The newline character on Unix/Linux is ‘\n’ (linefeed) but on Windows it’s ‘\r\n’ (carriage return, linefeed). So, the MD5 checksums of text files generated on Windows will be different.

Extract MD5 Checksum without Filename

If you notice, the output of the md5sum command includes the hash or checksum and also two other fields. The first is a character indicating type (‘*’ for binary, ‘ ‘ for text). The second field is the name of the input file. To retrive just the checksum, use one of the following options.

On Bash shell:

For other shells, use either the cut or awk commands to extract just the MD5 hash.

The MD5 hash value will be stored in the $md5hash variable.

Verify MD5 Checksum

To verify MD5 checksums, first store all the file checksums into a file called MD5SUM. For example, if we have 2 files: foo1 and foo2, extract the MD5 checkums using the following syntax:

To verify the MD5 checksums, use the “-c” option and pass the file that holds the MD5 checksums to md5sum utility.

If you are only interested in errors, use the “--quiet” option. Let’s say that the file foo2 has been modified, the output will be similar to the one shown below.

Without the “--quiet” option, the status of every file will be printed out including the successfully verified ones.

ibrahim = { interested_in(unix, linux, android, open_source, reverse_engineering); coding(c, shell, php, python, java, javascript, nodejs, react); plays_on(xbox, ps4); linux_desktop_user(true); }