JAVA自建工具类——使用MessageDigest将字符串转换为MD5

使用MessageDigest将字符串转换为MD5

 

import java.security.MessageDigest;

public class StringMD5 {
    public static String getMD5ofStr(String srcStr) throws Exception {
        if (srcStr == null)
            return null;
        byte[] strByte = srcStr.getBytes("UTF-8");
        return getMD5ofByte(strByte);
    }

    public static String getMD5ofByte(byte[] strByte) throws Exception {
        char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'a', 'b', 'c', 'd', 'e', 'f' };
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        byte[] bs = md5.digest(strByte);
        char[] str = new char[32];
        int k = 0;
        for (int i = 0; i < 16; ++i) {
            byte byte0 = bs[i];
            str[(k++)] = hexDigits[(byte0 >>> 4 & 0xF)];
            str[(k++)] = hexDigits[(byte0 & 0xF)];
        }
        return new String(str);
    }
}

 

posted @ 2022-08-12 12:00  山䂥进城  阅读(417)  评论(0)    收藏  举报