MD5,即”Message-Digest Algorithm 5(信息-摘要算法)”;
MD5将任意长度的“字节串”变换成一个128bit的大整数,并且它是一个不可逆的字符串变换算法;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException; public class Utility {
static MessageDigest messageDigest;
static String pwd;
public static String getMD5(String plainText) {
try {
//生成一个MD5加密计算摘要
messageDigest = MessageDigest.getInstance("MD5");
//用明文跟新消息摘要
messageDigest.update(plainText.getBytes());
//digest()最后确定返回md5 hash值,返回值为8位字符串。因为md5 hash值是16位的hex值,实际上就是8位的字符
//BigInteger函数则将8位的字符串转换成16位hex值,用字符串来表示;得到字符串形式的hash值 ,其中1代表正数,0代表0,-1代表负数
pwd = new BigInteger(1, messageDigest.digest()).toString(16); } catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return pwd;
}
}
测试123456 的MD5 为 E10ADC3949BA59ABBE56E057F20F883E