MD5加密与比较
1.直接上代码
public class TestMd5Case {
public static void main(String[] args) throws Exception {
Md5 md5 = new Md5();
String str = "apple";
try {
String newString = md5.EncoderByMd5(str);
System.out.println(newString);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
System.out.println(md5.EncoderByMd5("apple").equals("HzhwvidPbEmz4xoMZyiVfw=="));
}
}
public class Md5 {
/*利用MD5进行加密*/
public String EncoderByMd5(String str) throws Exception{
//确定计算方法
MessageDigest md5 = MessageDigest.getInstance("MD5");
BASE64Encoder base64en = new BASE64Encoder();
//加密后的字符串
String newstr = base64en.encode(md5.digest(str.getBytes("utf-8")));
return newstr;
}
/**判断用户密码是否正确 newpasswd 用户输入的密码 oldpasswd 正确密码*/
public boolean checkpassword(String newpasswd,String oldpasswd) throws Exception{
return EncoderByMd5(newpasswd).equals(oldpasswd);
}
}
补充:一般通过MD5进行加密保存数据的时候,为了防止同一数据加密出来的密文一样,一般会取一个个盐值来作为被加密的一部分,这个盐值是这条数据的唯一标识