Search Tutorials


Wednesday, 17 April 2013

Implementation of MD5 or SHA Algorithm in Java

This is a general Java program to implement Hash Algorithm which can be used in Android as well. Generate Hash of any message by using your given Algorithm. Just pass message in generateHash(String message) method to generate hash.

import java.math.BigInteger;

public class JavaMD5Hash {

    public static void main(String[] args) {
            System.out.println("For null " + generateHash(""));

            System.out.println("For simple text "+ generateHash("This is my text"));
            System.out.println("For simple numbers " + generateHash("12345"));
    public static String generateHash(String input) {
        String md5 = null;
        if(null == input) return null;
        try {
        //Create MessageDigest object for MD5 or pass SHA-1
        MessageDigest digest = MessageDigest.getInstance("MD5");
        //Update input string in message digest
        digest.update(input.getBytes(), 0, input.length());

        //Converts message digest value in base 16 (hex)
        md5 = new BigInteger(1, digest.digest()).toString(16);

        } catch (NoSuchAlgorithmException e) {

        return md5;

Pass your algorithm name("SHA-1", "MD5", "SHA-256", or "SHA-512") as a parameter in MessageDigest.getInstance(String algoName) and get the hash result. Algorithm name is not case sensitive, so you can pass mD5 or Md5.

Output Result:-

Implementation of MD5 or SHA Algorithm in Java

Set algorithm or make it dynamic and than run on command prompt. Share and comment if you like this post.

Related Programs:-

★ Java code to send and receive Text or Image File

★ Encrypt and Decrypt a message using Transposition Cipher

★ Encrypt and Decrypt a message using PlayFair Cipher

★ Calculate compression ratio

★ Java code to implement RSA Algorithm

No comments:

Post a Comment

back to top