In cryptography, MD5 (Message Digest version 5) and SHA (Secure Hash Algorithm) are two well-known message digest algorithms. They are also referred as cryptographic hash functions, which take arbitrary-sized data as input (message) and produce a fixed-length hash value. One of the most important properties of hash functions is, it’s infeasible to generate a message that has a given hash (secure one-way). Hash functions are frequently used to check data integrity such as checking integrity of a downloaded file against its publicly-known hash value. Another common usage is to encrypt user’s password in database.
The Java platform provides two implementation of hashing functions: MD5 (produces 128-bit hash value), SHA-1 (160-bit) and SHA-2 (256-bit). This tutorial demonstrates how to generate MD5 and SHA hash values from String or file using Java.
Here are general steps to generate a hash value from an input (message):
- First approach (suitable for small-sized message):
- Second approach (suitable for large-size message, i.e. large file):
Now, let’s see some examples in details.
1. Generating Hash from String
The following method takes a message and algorithm name as inputs and returns hexadecimal form of the calculated hash value:
The HashGenerationException is a custom exception (you can find this class in the attachment). TheconvertByteArrayToHexString() method is implemented as follows:
The hashString() is a general method. Here are four public utility methods that are specific to each algorithm (MD5, SHA-1 and SHA-256):
Hence we have the following utility class:
Here’s a test program:
If the input message is “admin” the test program produces the following output:
2. Generating Hash from File
To calculate hash value of a large file effectively, it’s recommended to repeatedly put a chunk of bytes to the message digest, until reaching end of file. Here’s such method:
Here are four public methods that are specific to each algorithm:
And here’s a test program: