get md5 checksum of an byte array - Java Security

Java examples for Security:MD5

Description

get md5 checksum of an byte array

Demo Code


import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Main{
    public static void main(String[] argv) throws Exception{
        byte[] input = new byte[]{34,35,36,37,37,37,67,68,69};
        System.out.println(getMD5(input));
    }//w  w  w  .  j a va2 s.c  o m
    private static Logger log = Logger.getLogger(RainbowduinoHelper.class
            .getName());
    /**
     * get md5 checksum of an byte array
     * @param input
     * @return
     */
    public static String getMD5(byte[] input) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] messageDigest = md.digest(input);
            BigInteger number = new BigInteger(1, messageDigest);
            String hashtext = number.toString(16);
            // Now we need to zero pad it if you actually want the full 32 chars.
            while (hashtext.length() < 32) {
                hashtext = "0" + hashtext;
            }
            return hashtext;
        } catch (NoSuchAlgorithmException e) {
            log.log(Level.WARNING, "Failed to calculate MD5 sum: {0}", e);
            return "";
        }
    }
}

Related Tutorials