Compute the md5 hash of a byte array. - Java Security

Java examples for Security:MD5

Description

Compute the md5 hash of a byte array.

Demo Code


//package com.java2s;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Main {
    public static void main(String[] argv) {
        byte[] arg = new byte[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 };
        System.out.println(computeMd5OfByteArray(arg));
    }/*  w ww .j ava 2 s .c  o m*/

    /**
     * Lower case Hex Digits.
     */
    private static final String HEX_DIGITS = "0123456789abcdef";
    /**
     * Byte mask.
     */
    private static final int BYTE_MSK = 0xFF;
    /**
     * Hex digit mask.
     */
    private static final int HEX_DIGIT_MASK = 0xF;
    /**
     * Number of bits per Hex digit (4).
     */
    private static final int HEX_DIGIT_BITS = 4;

    /**
     * Compute the md5 hash of a byte array.
     *
     * @param arg
     * the raw byte array to be encoded
     * @return a 32-character hexadecimal number
     * @throws UnsupportedOperationException
     * in the case MD5 MessageDigest is not supported, you
     * shouldn't bother catching this exception
     */
    public static String computeMd5OfByteArray(final byte[] arg)
            throws UnsupportedOperationException {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(arg);
            byte[] res = md.digest();
            return toHexString(res);
        } catch (NoSuchAlgorithmException ex) {
            throw new UnsupportedOperationException(ex);
        }
    }

    /**
     * Compute a String in HexDigit from the input.
     *
     * @param byteArray
     * a row byte array
     * @return a hex String
     */
    private static String toHexString(final byte[] byteArray) {
        StringBuilder sb = new StringBuilder(byteArray.length * 2);
        for (int i = 0; i < byteArray.length; i++) {
            int b = byteArray[i] & BYTE_MSK;
            sb.append(HEX_DIGITS.charAt(b >>> HEX_DIGIT_BITS)).append(
                    HEX_DIGITS.charAt(b & HEX_DIGIT_MASK));
        }
        return sb.toString();
    }
}

Related Tutorials