MD5工具类

来源:互联网 发布:淘宝兼职客服一般多少 编辑:程序博客网 时间:2024/05/20 17:27
1.import java.security.MessageDigest;   2.import java.security.NoSuchAlgorithmException;   3.  4./**  5. * MD5工具类  6. *   7. * @author 宋陆  8. * @date 2013-10-8  9. * @version 1.0  10. */  11.public class Md5Util {   12.  13.    /**  14.     * Md5.  15.     *  16.     * @param value the value  17.     * @return the string  18.     */  19.    public static String md5(String value) {   20.        try {   21.            MessageDigest md = MessageDigest.getInstance("md5");   22.            byte[] e = md.digest(value.getBytes());   23.            return toHex(e);   24.        }   25.        catch (NoSuchAlgorithmException e) {   26.            e.printStackTrace();   27.            return value;   28.        }   29.    }   30.       31.    /**  32.     * Md5.  33.     *  34.     * @param bytes the bytes  35.     * @return the string  36.     */  37.    public static String md5(byte[] bytes){   38.        try {   39.            MessageDigest md = MessageDigest.getInstance("md5");   40.            byte[] e = md.digest(bytes);   41.            return toHex(e);   42.        }   43.        catch (NoSuchAlgorithmException e) {   44.            e.printStackTrace();   45.            return "";   46.        }   47.    }   48.       49.    /**  50.     * To hex.  51.     *  52.     * @param bytes the bytes  53.     * @return the string  54.     */  55.    private static String toHex(byte bytes[]){   56.        StringBuilder hs = new StringBuilder();   57.        String stmp = "";   58.        for (int n = 0; n < bytes.length; n++) {   59.            stmp = Integer.toHexString(bytes[n] & 0xff);   60.            if (stmp.length() == 1)   61.                hs.append("0").append(stmp);   62.            else  63.                hs.append(stmp);   64.        }   65.        return hs.toString();   66.    }   67.}