我们在使用MD5 在线加密的时候,会发现下面情况,大小写的区别就不说啦,那么16位和32位有啥区别呢,其实16 位实际上是从 32 位字符串中,取中间的第 9 位到第 24 位的部分,就是str.substring(8, 24);

 

我们看看在java中是怎么实现的

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

public class MD5Util {

    /**
     * MD5加密字符串
     *
     * @param str
     * @return
     */
    public static String getMD5(String str) {
        if (EmptyUtil.isNotEmpty(str)) {
            try {
                MessageDigest md = MessageDigest.getInstance("MD5");
                md.update(str.getBytes());
                byte b[] = md.digest();
                int i;
                StringBuffer buf = new StringBuffer("");
                for (int offset = 0; offset < b.length; offset++) {
                    i = b[offset];
                    if (i < 0)
                        i += 256;
                    if (i < 16)
                        buf.append("0");
                    buf.append(Integer.toHexString(i));
                }
                return buf.toString();
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
        }
        return "";
    }


    /**
     * 获取32位大写
     *
     * @param str
     * @return
     */
    public static String getMD5_32_upper(String str) {
        if (EmptyUtil.isNotEmpty(str))
            return getMD5(str).toUpperCase();
        return "";
    }


    /**
     * 获取32位小写
     *
     * @param str
     * @return
     */
    public static String getMD5_32_lower(String str) {
        if (EmptyUtil.isNotEmpty(str))
            return getMD5(str).toLowerCase();
        return "";
    }


    /**
     * 获取16位大写
     *
     * @param str
     * @return
     */
    public static String getMD5_16_upper(String str) {
        if (EmptyUtil.isNotEmpty(str))
            return getMD5(str).substring(8, 24).toUpperCase();
        return "";
    }


    /**
     * 获取16位小写
     *
     * @param str
     * @return
     */
    public static String getMD5_16_lower(String str) {
        if (EmptyUtil.isNotEmpty(str))
            return getMD5(str).substring(8, 24).toLowerCase();
        return "";
    }


}