Java MD5 String md5hex(String source)

Here you can find the source of md5hex(String source)

Description

Returns a hex string representing the MD5 encoded source.

License

Open Source License

Declaration

public static String md5hex(String source) 

Method Source Code

//package com.java2s;

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

public class Main {
    /** Used by {@link #hexlate} and {@link #unhexlate}. */
    protected static final String XLATE = "0123456789abcdef";

    /**//from  w w  w.ja v a  2  s.co  m
     * Returns a hex string representing the MD5 encoded source.
     *
     * @exception RuntimeException thrown if the MD5 codec was not available in this JVM.
     */
    public static String md5hex(String source) {
        return hexlate(md5(source));
    }

    /**
     * Generates a string from the supplied bytes that is the HEX encoded representation of those
     * bytes.  Returns the empty string for a <code>null</code> or empty byte array.
     *
     * @param bytes the bytes for which we want a string representation.
     * @param count the number of bytes to stop at (which will be coerced into being <= the length
     * of the array).
     */
    public static String hexlate(byte[] bytes, int count) {
        if (bytes == null) {
            return "";
        }

        count = Math.min(count, bytes.length);
        char[] chars = new char[count * 2];

        for (int i = 0; i < count; i++) {
            int val = bytes[i];
            if (val < 0) {
                val += 256;
            }
            chars[2 * i] = XLATE.charAt(val / 16);
            chars[2 * i + 1] = XLATE.charAt(val % 16);
        }

        return new String(chars);
    }

    /**
     * Generates a string from the supplied bytes that is the HEX encoded representation of those
     * bytes.
     */
    public static String hexlate(byte[] bytes) {
        return (bytes == null) ? "" : hexlate(bytes, bytes.length);
    }

    /**
     * Encodes the supplied source text into an MD5 hash.
     */
    public static byte[] md5(String source) {
        return digest("MD5", source);
    }

    /**
     * Helper function for {@link #md5hex} and {@link #sha1hex}.
     */
    protected static byte[] digest(String codec, String source) {
        try {
            MessageDigest digest = MessageDigest.getInstance(codec);
            return digest.digest(source.getBytes());
        } catch (NoSuchAlgorithmException nsae) {
            throw new RuntimeException(codec + " codec not available");
        }
    }
}

Related

  1. md5Hex(String message)
  2. md5Hex(String message)
  3. md5Hex(String message)
  4. md5Hex(String message)
  5. md5Hex(String s)
  6. md5Hex(String str)
  7. md5raw(String data)
  8. md5Representation(String data)
  9. md5Signature(TreeMap params, String secret)