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();
    }
}  

 

posted @ 2018-02-27 17:06  萧熊猫  阅读(228)  评论(0编辑  收藏  举报