package test;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MD5Encryption {
private MD5Encryption() {
}
public static String getEncryption(String originString)
throws UnsupportedEncodingException {
String result = "";
if (originString != null) {
try {
// 指定加密的方式为MD5
MessageDigest md = MessageDigest.getInstance("MD5");
// 进行加密运算
byte bytes[] = md.digest(originString.getBytes("ISO8859-1"));
for (int i = 0; i < bytes.length; i++) {
// 将整数转换成十六进制形式的字符串 这里与0xff进行与运算的原因是保证转换结果为32位
String str = Integer.toHexString(bytes[i] & 0xFF);
if (str.length() == 1) {
str += "F";
}
result += str;
}
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
return result;
}
}
测试
package test;
import java.io.UnsupportedEncodingException;
public class Test {
public static void main(String[] args) throws UnsupportedEncodingException {
String password=MD5Encryption.getEncryption("hello1234");
System.out.println(password);
}
}
加密后的字符串位32位
算法是hexString(md5(password明文.getBytes("ISO8859-1")))。
明文hello1234运算出来为
9a1996efc97181f0aee18321aa3b3b12
DigestUtils工具类
也可以使用org.apache.commons.codec.digest.DigestUtils.md5Hex
和org.springframework.util.DigestUtils.md5DigestAsHex方便操作
本文出自 “点滴积累” 博客,请务必保留此出处http://tianxingzhe.blog.51cto.com/3390077/1740223