Java MD5 String md5Hex(String data)

Here you can find the source of md5Hex(String data)

Description

Calculate MD5 hash of a string and output in hexadecimal format.

License

GNU General Public License

Parameter

Parameter Description
data arbitrary String

Return

MD5 hash of data, string of length 32 with characters in range [0-9a-f]

Declaration

public static String md5Hex(String data) 

Method Source Code

//package com.java2s;
// License: GPL. For details, see LICENSE file.

import java.nio.charset.StandardCharsets;

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

public class Main {
    private static final char[] HEX_ARRAY = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
            'e', 'f' };

    /**/*from  w  w w .  j a  v a 2s .com*/
     * Calculate MD5 hash of a string and output in hexadecimal format.
     * @param data arbitrary String
     * @return MD5 hash of data, string of length 32 with characters in range [0-9a-f]
     */
    public static String md5Hex(String data) {
        byte[] byteData = data.getBytes(StandardCharsets.UTF_8);
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
        byte[] byteDigest = md.digest(byteData);
        return toHexString(byteDigest);
    }

    /**
     * Converts a byte array to a string of hexadecimal characters.
     * Preserves leading zeros, so the size of the output string is always twice
     * the number of input bytes.
     * @param bytes the byte array
     * @return hexadecimal representation
     */
    public static String toHexString(byte[] bytes) {

        if (bytes == null) {
            return "";
        }

        final int len = bytes.length;
        if (len == 0) {
            return "";
        }

        char[] hexChars = new char[len * 2];
        for (int i = 0, j = 0; i < len; i++) {
            final int v = bytes[i];
            hexChars[j++] = HEX_ARRAY[(v & 0xf0) >> 4];
            hexChars[j++] = HEX_ARRAY[v & 0xf];
        }
        return new String(hexChars);
    }
}

Related

  1. md5File(File f)
  2. md5file(File file)
  3. md5FromFile(File file)
  4. md5fromFile(String path)
  5. md5Hex(String data)
  6. md5Hex(String message)
  7. md5Hex(String message)
  8. md5Hex(String message)
  9. md5Hex(String message)