Java MD5 String md5(String str)

Here you can find the source of md5(String str)

Description

encode By MD5

License

Apache License

Parameter

Parameter Description
str a parameter

Return

String

Declaration

public static String md5(String str) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.security.MessageDigest;

public class Main {
    /**/*from   www . ja va2s  .  c  o  m*/
     * Used to build output as Hex
     */
    private static final char[] DIGITS_LOWER = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c',
            'd', 'e', 'f' };

    /**
     * encode By MD5
     * 
     * @param str
     * @return String
     */
    public static String md5(String str) {
        if (str == null) {
            return null;
        }
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.update(str.getBytes());
            return new String(encodeHex(messageDigest.digest()));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Converts an array of bytes into an array of characters representing the hexadecimal values of each byte in order.
     * The returned array will be double the length of the passed array, as it takes two characters to represent any
     * given byte.
     * 
     * @param data a byte[] to convert to Hex characters
     * @return A char[] containing hexadecimal characters
     */
    protected static char[] encodeHex(final byte[] data) {
        final int l = data.length;
        final char[] out = new char[l << 1];
        // two characters form the hex value.
        for (int i = 0, j = 0; i < l; i++) {
            out[j++] = DIGITS_LOWER[(0xF0 & data[i]) >>> 4];
            out[j++] = DIGITS_LOWER[0x0F & data[i]];
        }
        return out;
    }
}

Related

  1. md5(String str)
  2. md5(String str)
  3. md5(String str)
  4. MD5(String str)
  5. MD5(String str)
  6. md5(String str)
  7. MD5(String str)
  8. MD5(String string)
  9. md5(String string)