前段时间要个md5加密的工具类,网上找了一些,好多不合适,于是自己写了个工具类。在此把该工具类的代码留下,方便后续查询。下面直接上代码。
一、代码
package com.tomtop.core.util;
import java.security.MessageDigest;
/**
* MD5Utils
* @author ZENG.XIAO.YAN
* @date 2017年8月22日 下午4:38:48
* @version v1.0
*/
public class MD5Utils {
/**
* MD5加密方法
* @param str 明文
* @return 密文(32位)
*/
public static String getMD5(String str) throws Exception{
/** 创建加密对象 */
MessageDigest md = MessageDigest.getInstance("MD5");
/** 加密 */
md.update(str.getBytes("utf-8"));
/** 获取加密后的内容 (16位的字符数组) */
byte[] md5Bytes = md.digest();
/*System.out.println("加密前:" + Arrays.toString(str.getBytes()));
System.out.println("加密后:" + Arrays.toString(md5Bytes));*/
String res = "";
/** 把加密后字节数组转化成32位字符串 (把每一位转化成16进制的两位) */
for (int i = 0; i < md5Bytes.length; i++){
int temp = md5Bytes[i] & 0xFF;
/** 把temp值转化成16进制的两位数,如果不够两位前面补零 */
if (temp <= 0xF){
res += "0";
}
res += Integer.toHexString(temp);
}
return res;
}
/*public static void main(String[] args) throws Exception {
System.out.println(MD5Utils.getMD5("123456"));
}*/
}x
1
package com.tomtop.core.util; 2
3
import java.security.MessageDigest;4
5
/**6
* MD5Utils7
* @author ZENG.XIAO.YAN8
* @date 2017年8月22日 下午4:38:489
* @version v1.010
*/11
12
public class MD5Utils {13
14
/**15
* MD5加密方法16
* @param str 明文17
* @return 密文(32位)18
*/19
public static String getMD5(String str) throws Exception{20
/** 创建加密对象 */21
MessageDigest md = MessageDigest.getInstance("MD5");22
/** 加密 */23
md.update(str.getBytes("utf-8"));24
/** 获取加密后的内容 (16位的字符数组) */25
byte[] md5Bytes = md.digest();26
/*System.out.println("加密前:" + Arrays.toString(str.getBytes()));27
System.out.println("加密后:" + Arrays.toString(md5Bytes));*/28
String res = "";29
/** 把加密后字节数组转化成32位字符串 (把每一位转化成16进制的两位) */30
for (int i = 0; i < md5Bytes.length; i++){31
int temp = md5Bytes[i] & 0xFF;32
/** 把temp值转化成16进制的两位数,如果不够两位前面补零 */33
if (temp <= 0xF){34
res += "0";35
}36
res += Integer.toHexString(temp);37
}38
return res;39
}40
41
/*public static void main(String[] args) throws Exception {42
System.out.println(MD5Utils.getMD5("123456"));43
}*/44
}