23/08/2011 22:54

Java md5 example with MessageDigest

Overview OF MD5
Message-Digest algorithm 5 is cryptographic hash function with a 128-bit hash value. As an internet standard (RFC:1321),MD5 has been employed in a wide variety of security applications, and is also commonly used to check the integrity of files.The 128-bit (16-byte) MD5 hashes are typically represented as a sequence of 32 hexadecimal digits. The following demonstrates a 43-byte ASCII input and the corresponding MD5 hash:

MD5 in Java
This is a quick tip for implementing md5 encryption in java. 
1. We use the MessageDigest class in the java.security package 
2. some string manipulation to turn the plain text into a byte array. 
3. The digest is then updated from the bytes from the byte array and a hash computation is conducted upon them. 


The below snippet is used to understand the implemtation of MD5 in java programming.
package demoapplication;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Implementation {

    public static void main(String arg[]) {
        System.out.println("Started");
        System.out.println("Using BigInteger = "+getMd5Digest("password"));
        System.out.println("Using HexaDecimal conversion = "+getMd5Digest("password", 0));
        System.out.println("End");
    }

    static synchronized String getMd5Digest(String input) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] messageDigest = md.digest(input.getBytes());
            BigInteger number = new BigInteger(1, messageDigest);
            return number.toString(16);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    static synchronized String getMd5Digest(String input, int x) {
        byte[] defaultBytes = input.getBytes();
        try {
            MessageDigest algorithm = MessageDigest.getInstance("MD5");
            algorithm.reset();
            algorithm.update(defaultBytes);
            byte messageDigest[] = algorithm.digest();

            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < messageDigest.length; i++) {
                String hex = Integer.toHexString(0xFF & messageDigest[i]);
                if (hex.length() == 1)
                    hexString.append('0');

                hexString.append(hex);
            }
            input = hexString + "";
        } catch (NoSuchAlgorithmException nsae) {
        }
        return input;
    }
}


* MD5 - Message-Digest algorithm 5
* RFD - Request for Comments

—————

Back


Contact

ShareYourKnowledge