// MD5加密
private static String md5sum(String unsignedStr) {
try {
MessageDigest md5 = MessageDigest.getInstance("MD5");
byte[] secretBytes = md5.digest(unsignedStr.getBytes());
return bytesToHex(secretBytes);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return "";
}
// 二进制转为十六进制字符串
public static String bytesToHex(byte[] bytes) {
StringBuilder md5str = new StringBuilder();
// 把数组每一字节换成16进制连成md5字符串
int digital;
for (byte aByte : bytes) {
digital = aByte;
if (digital < 0) {
digital += 256;
}
if (digital < 16) {
md5str.append("0");
}
md5str.append(Integer.toHexString(digital));
}
return md5str.toString().toLowerCase();
}
使用方法如下:
md5sum("要加密的字符串");
评论(0)