Springboot实现密码的加密解密

时间:2022-01-04 02:20:54

现今对于大多数公司来说,信息安全工作尤为重要,就像京东,阿里巴巴这样的大公司来说,信息安全是最为重要的一个话题,举个简单的例子:

Springboot实现密码的加密解密

就像这样的密码公开化,很容易造成一定的信息的泄露。所以今天我们要讲的就是如何来实现密码的加密和解密来提高数据的安全性。

在这首先要引入springboot融合mybatis的知识,如果有这方面不懂得同学,就要首先看一看这方面的知识:

推荐大家一个比较好的博客: 程序猿dd-翟永超 http://blog.didispace.com/springbootmybatis/

为了方便大家的学习,我直接将源代码上传:

1.pom.xml

?
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
<project xmlns="http://maven.apache.org/pom/4.0.0" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xsi:schemalocation="http://maven.apache.org/pom/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelversion>4.0.0</modelversion>
 <groupid>com.ninemax</groupid>
 <artifactid>spring-login-test</artifactid>
 <version>0.0.1-snapshot</version>
 <packaging>war</packaging>
 
   <parent>
    <groupid>org.springframework.boot</groupid>
    <artifactid>spring-boot-starter-parent</artifactid>
    <version>1.3.2.release</version>
    <relativepath/>
  </parent>
 
  <properties>
    <project.build.sourceencoding>utf-8</project.build.sourceencoding>
    <java.version>1.8</java.version>
  </properties>
 
  <dependencies>
    
    <dependency>
      <groupid>org.springframework.boot</groupid>
      <artifactid>spring-boot-starter</artifactid>
    </dependency>
 
    <dependency>
      <groupid>org.springframework.boot</groupid>
      <artifactid>spring-boot-starter-test</artifactid>
      <scope>test</scope>
    </dependency>
 
    <dependency>
      <groupid>org.mybatis.spring.boot</groupid>
      <artifactid>mybatis-spring-boot-starter</artifactid>
      <version>1.1.1</version>
    </dependency>
 
    <dependency>
      <groupid>org.springframework.boot</groupid>
      <artifactid>spring-boot-starter-web</artifactid>
    </dependency>
 
    <dependency>
      <groupid>commons-dbcp</groupid>
      <artifactid>commons-dbcp</artifactid>
    </dependency>
 
    <dependency>
      <groupid>com.oracle</groupid>
      <artifactid>ojdbc14</artifactid>
      <version>10.2.0.3.0</version>
    </dependency>
    
    
     <dependency>
      <groupid>org.springframework.boot</groupid>
      <artifactid>spring-boot-starter-thymeleaf</artifactid>
    </dependency>
    
    
  </dependencies>
 
  <build>
    <plugins>
      <plugin>
        <groupid>org.springframework.boot</groupid>
        <artifactid>spring-boot-maven-plugin</artifactid>
      </plugin>
      <plugin>
        <groupid>org.apache.maven.plugins</groupid>
        <artifactid>maven-surefire-plugin</artifactid>
        <configuration>
          <skip>true</skip>
        </configuration>
      </plugin>
    </plugins>
  </build>
  
 
</project>

2. apptest.java

?
1
2
3
4
5
6
7
8
9
10
11
12
package com;
 
import org.springframework.boot.springapplication;
import org.springframework.boot.autoconfigure.springbootapplication;
 
@springbootapplication
public class apptest {
   public static void main(string[] args) {
     springapplication.run(apptest.class, args);
   }
   
}

3.user.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
package com.entity;
 
public class user {
 
  private string username;
  private string password;
  
  public string getusername() {
    return username;
  }
  public void setusername(string username) {
    this.username = username;
  }
  public string getpassword() {
    return password;
  }
  public void setpassword(string password) {
    this.password = password;
  }
  @override
  public string tostring() {
    return "user [username=" + username + ", password=" + password + "]";
  }
 
}

4.usercontroller.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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package com.controller;
 
import java.security.securerandom;
 
import javax.crypto.cipher;
import javax.crypto.secretkey;
import javax.crypto.secretkeyfactory;
import javax.crypto.spec.deskeyspec;
import javax.servlet.http.httpservletrequest;
 
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.stereotype.controller;
import org.springframework.web.bind.annotation.requestmapping;
 
import com.dao.userdao;
import com.entity.user;
 
@controller
public class usercontroller {
 
   @autowired
   private userdao userdao;
   
   @requestmapping("/regist")
   public string regist() {
     return "regist";
   }
   
   @requestmapping("/login")
   public string login() {
     return "login";
   }
    
   @requestmapping("/success")
   public string success(httpservletrequest request) {
     string username = request.getparameter("username");
     string password = request.getparameter("password");
     
     userdao.save(username, password);
     return "success";
   }
   
   @requestmapping("/loginsuccess")
   public string successlogin(httpservletrequest request) {
     string username = request.getparameter("username");
     string password = request.getparameter("password"); ///123456
     user user = userdao.findbyuname(username);
       if(user.getpassword().equals(password)) {
         return "successlogin";
       }
       return "failure";
   }
}

5.userdao.java

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package com.dao;
 
import org.apache.ibatis.annotations.insert;
import org.apache.ibatis.annotations.mapper;
import org.apache.ibatis.annotations.param;
import org.apache.ibatis.annotations.select;
 
import com.entity.user;
 
@mapper
public interface userdao {
   @insert("insert into login_nine values(#{username}, #{password})")
   void save(@param("username")string username,@param("password")string password);
   
   @select("select * from login_nine where username= #{username}")
   user findbyuname(@param("username")string username);
}

6.application.properties

?
1
2
3
4
spring.datasource.url=jdbc:oracle:thin:@10.236.4.251:1521:orcl
spring.datasource.username=hello
spring.datasource.password=lisa
spring.datasource.driver-class-name=oracle.jdbc.driver.oracledriver

7.还有一些静态html

(1.)regist.html

 

?
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
30
31
32
33
<!doctype html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>注册</title>
 
<style type="text/css">
  h1 {
   text-align:center;
   font-size:35px;
   color:red;
  }
  div {
   text-align:center;
  }
  div input {
   margin:10px;
  }
</style>
</head>
<body>
   <h1>注册账号</h1>
   <div>
   <form action="success" method="post">
                 用户名<input type="text" name="username"/> <br/>
                 密码<input type="password" name = "password"/> <br/>
      <input type="submit" value="提交"/>  
      <input type="reset"/>
              
   </form>
   </div>
</body>
</html>

(2.)login.html

?
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
30
31
32
33
34
<!doctype html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>登录</title>
 
<style type="text/css">
  h1 {
   text-align:center;
   font-size:35px;
   color:red;
  }
  div {
   text-align:center;
  }
  div input {
   margin:10px;
  }
  
</style>
</head>
<body>
   <h1>欢迎登录</h1>
   <div>
   <form action="loginsuccess" method="post">
                 请输入用户名<input type="text" name="username"/> <br/>
                 请输入密码<input type="password" name = "password"/> <br/>
      <input type="submit" value="提交"/>  
      <input type="reset"/>   <br/>
      <a href="/regist" rel="external nofollow" >注册账号</a>        
   </form>
   </div>
</body>
</html>

(3.)success.html

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!doctype html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>注册成功</title>
<style type="text/css">
  h1 {
   text-align:center;
   font-size:60px;
   color:green;
  }
  span {
   font-size:30px;
   color:green;
  }
</style>
</head>
<body>
<h1>注册成功</h1>
<a href="/login" rel="external nofollow" >返回登录</a>
</body>
</html>

(4.)failure.html

?
1
2
3
4
5
6
7
8
9
10
11
<!doctype html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>登录失败</title>
 
</head>
<body>
     登录失败
</body>
</html>

(5.)successlogin.html

?
1
2
3
4
5
6
7
8
9
10
<!doctype html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>成功</title>
</head>
<body>
   success
</body>
</html>

代码的格式如下:

Springboot实现密码的加密解密

完成了这一步的话首先运行一下apptest看是否出错,如果有错,自己找原因,这里就不和大家讨论了,写了这么多,才要要进入正题了

本文采取的是eds的加密解密方法,方法也很简单,不用添加额外的jar包,只需要在usercontroller上做出简单的修改就可以了:

*****usercontroller.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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package com.controller;
 
import java.security.securerandom;
 
import javax.crypto.cipher;
import javax.crypto.secretkey;
import javax.crypto.secretkeyfactory;
import javax.crypto.spec.deskeyspec;
import javax.servlet.http.httpservletrequest;
 
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.stereotype.controller;
import org.springframework.web.bind.annotation.requestmapping;
 
import com.dao.userdao;
import com.entity.user;
 
@controller
public class usercontroller {
 
   @autowired
   private userdao userdao;
   
   @requestmapping("/regist")
   public string regist() {
     return "regist";
   }
   
   @requestmapping("/login")
   public string login() {
     return "login";
   }
   
   /**
    * eds的加密解密代码
    */
   private static final byte[] des_key = { 21, 1, -110, 82, -32, -85, -128, -65 };
    @suppresswarnings("restriction")
    public static string encryptbaseddes(string data) {
      string encrypteddata = null;
      try {
        // des算法要求有一个可信任的随机数源
        securerandom sr = new securerandom();
        deskeyspec deskey = new deskeyspec(des_key);
        // 创建一个密匙工厂,然后用它把deskeyspec转换成一个secretkey对象
        secretkeyfactory keyfactory = secretkeyfactory.getinstance("des");
        secretkey key = keyfactory.generatesecret(deskey);
        // 加密对象
        cipher cipher = cipher.getinstance("des");
        cipher.init(cipher.encrypt_mode, key, sr);
        // 加密,并把字节数组编码成字符串
        encrypteddata = new sun.misc.base64encoder().encode(cipher.dofinal(data.getbytes()));
      } catch (exception e) {
        // log.error("加密错误,错误信息:", e);
        throw new runtimeexception("加密错误,错误信息:", e);
      }
      return encrypteddata;
    }
    @suppresswarnings("restriction")
    public static string decryptbaseddes(string cryptdata) {
      string decrypteddata = null;
      try {
        // des算法要求有一个可信任的随机数源
        securerandom sr = new securerandom();
        deskeyspec deskey = new deskeyspec(des_key);
        // 创建一个密匙工厂,然后用它把deskeyspec转换成一个secretkey对象
        secretkeyfactory keyfactory = secretkeyfactory.getinstance("des");
        secretkey key = keyfactory.generatesecret(deskey);
        // 解密对象
        cipher cipher = cipher.getinstance("des");
        cipher.init(cipher.decrypt_mode, key, sr);
        // 把字符串进行解码,解码为为字节数组,并解密
        decrypteddata = new string(cipher.dofinal(new sun.misc.base64decoder().decodebuffer(cryptdata)));
      } catch (exception e) {
        throw new runtimeexception("解密错误,错误信息:", e);
      }
      return decrypteddata;
    }
    
   @requestmapping("/success")
   public string success(httpservletrequest request) {
     string username = request.getparameter("username");
     string password = request.getparameter("password");
     string s1 = encryptbaseddes(password);
     userdao.save(username, s1);
     return "success";
   }
   
   @requestmapping("/loginsuccess")
   public string successlogin(httpservletrequest request) {
     string username = request.getparameter("username");
     string password = request.getparameter("password"); ///123456
     user user = userdao.findbyuname(username);
       if(decryptbaseddes(user.getpassword()).equals(password)) {
         return "successlogin";
       }
       return "failure";
   }
}

此时,直接运行apptest.java,然后在浏览器输入地址:localhost:8080/regist 注册新的账号(我输入的是用户名:小明 密码:123456),如图

Springboot实现密码的加密解密

此时查看数据库信息

Springboot实现密码的加密解密

你就会发现密码实现了加密。

当然,下次登陆的时候直接输入相应的账号和密码即可完成登录,实现了解码的过程。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:http://www.cnblogs.com/baiyp/archive/2017/11/15/7833610.html