Find the MD5 hash value of a string in java

Posted By: Achchuthan Yogarajah - 6:59 PM

Share

& Comment

Here is the example is show quick way to calculate the MD5 hash of a string. I know things with Java have to be well structured and since MD5 is a hashing algorithm it is fairly logical to be in the security package. On the other hand i think a quick md5 method should be in the String class but that’s just my humble oppinion. Anyways here is how it’s done the Java way.

So what you have to do it to create an instance of the MessageDigest class with the algorithm of MD5, then convert your string to a byte sequence, feed it to the instance that will return a new byte sequence with the MD5 value and convert it accordingly to what we want (here just the hex representation). So let’s get our hands dirty.


Source code of MD5 Generator

import java.security.*;
import java.math.*;
import java.io.*;
//Programme to find the MD5 hash value of a string and to output the value
public class MD5 {
    public static void main(String args[]) throws Exception{
        String s="ATX";
        MessageDigest m=MessageDigest.getInstance("MD5");
        m.update(s.getBytes(),0,s.length());

 try{

   //To print the hash value in hexadecimal
   System.out.println("MD5 in hex: "+new BigInteger(1,m.digest()).toString(16));
   
   //To print the hash value in decimal
   System.out.println("MD5 in decimal: "+new BigInteger(1,m.digest()).toString(10));
   
   //To print the hash value in binary
   System.out.println("MD5 in binary: "+new BigInteger(1,m.digest()).toString(2));
   //Close the output stream
      }catch (Exception e){//Catch exception if any
   System.err.println("Error: " + e.getMessage());
   }
    }
}

Output of this code :

MD5 in hex: 35e60d78c674c52c3c6d2258135855e3
MD5 in decimal: 281949768489412648962353822266799178366
MD5 in binary: 11010100000111011000110011011001100011110000000010110010000001001
110100110000000000010011001100011101100111110000100001001111110

About Achchuthan Yogarajah

I’m passionate about Web Development and Programming and I go to extreme efforts to meet my passion. I’m a believer of learning the fundamentals first. I try to understand everything little bit more than the average.

0 comments :

Post a Comment

Thank you for vising Java90.blogspot.com

Copyright © 2016 Java Examples ACHCHUTHAN.ORG. Designed by Templateism .