JAVA代码实现MD5加密

参数
str_original 原始字符串
isToUpperCase 是否字母大写

public String MD5(String str_original, boolean isToUpperCase) {
    MessageDigest md;
    try {
        md = MessageDigest.getInstance("MD5");
        md.update((str_original).getBytes("UTF-8"));
        byte[] md5Byte = md.digest();
        return bytesToHex(md5Byte, isToUpperCase);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return "";
}

//二进制转十六进制  
@SuppressLint("DefaultLocale")
public static String bytesToHex(byte[] bytes, boolean isToUpperCase) {  
    StringBuffer hexStr = new StringBuffer("");  
    int num;  
    for (int i = 0; i < bytes.length; i++) {  
        num = bytes[i];  
         if(num < 0) {  
             num += 256;  
        }  
        if(num < 16){  
            hexStr.append("0");  
        }  
        hexStr.append(Integer.toHexString(num));  
    } 
    if (isToUpperCase) {
        return hexStr.toString().toUpperCase();  
    } else {
        return hexStr.toString();
    }
}

猜你喜欢

转载自blog.csdn.net/qql7267/article/details/79390907