JAVA中使用MD5加密实现密码加密

1.新建Md5.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package com.loger.md5;
 
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
 
import sun.misc.BASE64Encoder;
 
public class Md5 {
   /**利用MD5进行加密*/
  public String EncoderByMd5(String str) throws NoSuchAlgorithmException, UnsupportedEncodingException{
    //确定计算方法
    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 NoSuchAlgorithmException, UnsupportedEncodingException{
    if(EncoderByMd5(newpasswd).equals(oldpasswd))
      return true;
    else
      return false;
  }
}

2.新建测试类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package com.loger.md5;
 
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
 
public class MyTest {
   
  public static void main(String[] args) throws NoSuchAlgorithmException, UnsupportedEncodingException {   
    Md5 md5 = new Md5(); 
    String str = "apple";
    try {
      String newString = md5.EncoderByMd5(str);
      System.out.println(newString);
    } catch (NoSuchAlgorithmException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
     
    System.out.println(md5.EncoderByMd5("apple").equals("HzhwvidPbEmz4xoMZyiVfw=="));
     
  }
}

运行结果:

原文地址:https://www.cnblogs.com/cangqinglang/p/10133550.html