Java MD5 Encode MD5Encode(String str)

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

Description

Make an MD5 Hash from a particular string.

License

Open Source License

Parameter

Parameter Description
str - the string to be hashed.

Exception

Parameter Description
UnsupportedEncodingException an exception

Return

md5 - the resulting hash

Declaration

public static String MD5Encode(String str) throws UnsupportedEncodingException 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.io.UnsupportedEncodingException;

import java.net.URLEncoder;
import java.security.MessageDigest;

public class Main {
    protected static final char HEXCODE[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D',
            'E', 'F' };

    /**/*  www  .ja  v a  2  s .  co  m*/
     * Make an MD5 Hash from a particular string.
     * @param str - the string to be hashed.
     * @return md5 - the resulting hash
     * @throws UnsupportedEncodingException
     */
    public static String MD5Encode(String str) throws UnsupportedEncodingException {
        String returnVal = null;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte mdArr[] = md.digest(str.getBytes("UTF-16"));
            returnVal = toHexString(mdArr);
        } catch (Exception e) {
            returnVal = URLEncoder.encode(str, "UTF-8").replaceAll("\\*", "x");
        }
        return returnVal;
    }

    /**
     * Convert a collection of bytes from an MD5 hash to a string.
     * @param bytes the bytes to be converted
     * @return the resulting string
     */
    protected static String toHexString(byte bytes[]) {
        char chars[] = new char[bytes.length * 2];

        for (int i = 0; i < bytes.length; ++i) {
            chars[2 * i] = HEXCODE[(bytes[i] & 0xF0) >>> 4];
            chars[2 * i + 1] = HEXCODE[bytes[i] & 0x0F];
        }
        return new String(chars);
    }
}

Related

  1. MD5Encode(String s)
  2. Md5Encode(String source)
  3. md5Encode(String source)
  4. MD5Encode(String sourceString)
  5. md5Encode(String src)
  6. md5Encode(String strPlain)
  7. MD5Encoder(String s, String charset)
  8. md5encoding(String data)
  9. md5Encoding(String s)