SHA hashing Implementation in JAVA

Secure Hashing Algorithm (SHA) is a family of cryptographic hash functions. Hashing in general is used in cryptographic programming to ensure validity of data. A hash function takes data input in bytes and performs specific operations on the data to return an array of bytes of specific length. This returned array of bytes is not possible to be back calculated in order to get the original data. This property helps to securely compare data without any information about the data itself.


At first we need to import some classes, Java has a pre-built "security" library which includes the "MessageDigest" class to implement the SHA hashing functions. Moreover we need to import the "NoSuchAlgorithmException" class for error handling and also static import "UTF_8" from "StandardCharsets" for converting the input string to bytes.


Now, we have to write a method for generating the SHA hash. This method will take an input string and return the hash of that string in form of an array of bytes.

In the above code we have assumed the hash algorithm to be "SHA-256" as it is the most widely used algorithm among the SHA hash functions. But you can change it to other algorithms like "SHA-512" or "MD5".


The above function returns an array of bytes. We have to convert the the bytes to hexadecimal in order to make it human readable.


At last we can invoke the above functions from the main method to get our SHA hash.


The Complete Program :


Sample Outputs :

Comments