Hashing and Java Implementation

In today's post, I would like to discuss about hashing and how it can be implemented in programming language, in which I would use Java for this purpose. Hashing, though, can be easily implemented using any other programming languages.

Hashing is a process whereby one input, processed using specific algorithm, will produce another output that is unique for that input. For an algorithm to be considered secure as a hashing algorithm, there are several characteristics has to be met:
  1. For every input I, it must produce output O that is unique for virtually every set of I (no collision).
  2. For every output O, there should virtually no way, or virtually very hard, to compute back the value of input I (one-way function).
  3. For every input I, the length of the output O must be always the same regardless of the length of the input I.
There are several algorithms available out there on hashing. Below are some of the algorithms:
  • MD5 (no longer recommended)
  • SHA-1 (no longer recommended)
  • SHA-2 (SHA-224, SHA-256, SHA-348, and SHA-512)
  • SHA-3 (Keccak)
There are many other hashing algorithms available in the wild. Now that we know what hashing is, let's move on how to implement this in Java. In this example, I will use SHA-512 as the hashing algorithm.

Java provides a build-in class called MessageDigest. This class can be easily used to compute the message digest of an input with specific algorithm. MessageDigest class resides inside the java.security package, hence you have to import this package before using the MessageDigest class.

Below is an example on how to call the create the object of MessageDigest specifying the algorithm to use (i.e.:SHA-512).



After having the object of MessageDigest, calculating the hash value is pretty much straight forward. We just need to tell the object what is the data to hash and call the digest method which returns the hash value in byte array. See below.





As seen above, you need to give the data to be hashed into the update method. The hashData variable then be used to store the hash value, returned by the digest method call. The input that I used is from a variable named firstInput. In this blog, I am using TWO (2) variables as input, shown below:




Here is the output of the hash value of the firstInput encoded in Base64.

When changing the input to the secondInput variable, here is the output.

As you can see, the length of the output of both input values is the same. This is one property of a good hash function. Additionally, with different input values, the output is different as well. Here is the complete source code I used for this example.

















That's it for now hope this helps anyone getting started with Hashing in Java.

Cheers.


Comments

Popular posts from this blog

Kisah Nyata Seorang Anak Bernama Andoy dari Filipina

National Library of Indonesia

Needlefish Attack