Find the MD5 hash value of a string in java

Java Examples
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 Message Digest 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.math.*;
//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");


   //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());


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

Post a Comment

Thank you for vising

Previous Post Next Post