MD5加密主要有两种实现方式,一种是采用jdk的MessageDigest类实现,另外一种是采用Apache commons-codec-1.10.jar实现
方式一:jdk加密
//paintText代表明文,cipeherText 代表密文
public static String jdkMd5(String plainText) throws Exception{
MessageDigest md=MessageDigest.getInstance("MD5");
String salt="abc";//这里是盐值,为了避免出现数据库泄露,账号密码等信息被破解的问题,采用了盐值加密,只要盐值不泄露,一般比较安全,盐值具体为多少自己定,如果不理解为什么要采用盐值,请看我的另外一篇帖子。
byte[] bytes = md.digest((plainText+salt).getBytes());
StringBuffer cipeherText = new StringBuffer("");
for (int b : bytes) {
if (b < 0)
b += 256;
if (b < 16)
cipeherText.append("0");
cipeherText.append(Integer.toHexString(b));
}
return cipeherText.toString().toUpperCase();
}
方式二:commons-codec加密
public static String commonMd5(StringpaintText){
String salt="abc";//同样也采用盐值加密,原理同上,
return DigestUtils.md5Hex(str+salt).toUpperCase();
}
以上两种方式在明文和盐值相同的情况下,加密后的密文是一样的,请任选一种