MD5全称是Message-Digest Algorithm 5(信息-摘要算法)
//确定计算方法
MessageDigest md5 = MessageDigest.getInstance("MD5");
//jdk1.8新增Base64
String newstr = Base64.getEncoder().encodeToString(md5.digest(str.getBytes("utf-8")));
//1.8之前使用sum.misc.Base64Encoder(此类没有访问权限,在tr.jar中添加访问权限:sun/misc/*)
BASE64ENcoder base64 = new BASE64ENcoder();
base64.encode(md5.digest(str.getBytes("utf-8")));
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class MD5Demo {
public static void main(String[] args) {
String password = "admin12345";
try {
//确定md5加密算法
MessageDigest md = MessageDigest.getInstance("md5");
//通过md5计算摘要;返回的是字节数组,是不可清晰读取的,所以需要再次转换成可读字符串
byte [] bytes = md.digest(password.getBytes("UTF-8"));
System.out.println(Arrays.toString(bytes));
/**
如下对加密后的MD5值直接输出字符串是乱码“t堛1付NW斱?る�璢”,所以要用一个编码算法重新转成一个可读的字符串
String mdstr = new String(bytes);
System.out.println(mdstr);
*/
// a-z A-Z 0-9 / * BASE64编码算法,转成可读的字符串
/**
* jdk1.8版本,将将MD5值转成可读字符串
String str = Base64.getEncoder().encodeToString(bytes);
*/
//jdk1.8以前版本;将MD5值转成可读字符串
BASE64Encoder base64 = new BASE64Encoder();
String str = base64.encode(bytes);
System.out.println(str);
//还原成md5值
BASE64Decoder decoder = new BASE64Decoder();
byte[] bs = decoder.decodeBuffer(str);
System.out.println(Arrays.toString(bs));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
举例引用
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import sun.misc.BASE64Encoder;
public class testmd5 {
private static String savepasswd = "dIjjMbi2TleU2j+k6xCtXQ==";
public static void main(String[] args) {
System.out.println(login("admin12345"));
}
//判断所输入的密码经过md5加密后是否与原密文一致
private static boolean login(String password){
if(savepasswd.equals(md5(password))){
return true;
}else{
return false;
}
}
//计算md5的工具方法
private static String md5(String password){
try {
//确定md5加密算法
MessageDigest md = MessageDigest.getInstance("md5");
//通过md5计算摘要
byte [] bytes = md.digest(password.getBytes("UTF-8"));
//md5值转成可读字符串
BASE64Encoder base64 = new BASE64Encoder();
String str = base64.encode(bytes);
return str;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
}