Springboot实现密码的加密解密

Springboot实现密码的加密解密,第1张

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

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

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

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

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

@H_502_0@1.pom.xml

<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>
@H_502_0@2. AppTest.java

package com;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplicationpublic class AppTest {   public static voID main(String[] args) {     SpringApplication.run(AppTest.class,args);   }   }
@H_502_0@3.User.java

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 + "]";  }}
@H_502_0@4.UserController.java

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;@Controllerpublic 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";   }}
@H_502_0@5.UserDao.java

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;@Mapperpublic 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);}
@H_502_0@6.application.propertIEs

spring.datasource.url=jdbc:oracle:thin:@10.236.4.251:1521:orclspring.datasource.username=hellospring.datasource.password=lisaspring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
@H_502_0@7.还有一些静态HTML

@H_502_0@(1.)regist.HTML

@H_502_0@

<!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>
@H_502_0@(2.)login.HTML

<!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>
@H_502_0@(3.)success.HTML

<!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>
@H_502_0@(4.)failure.HTML

<!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>
@H_502_0@(5.)successLogin.HTML

<!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>
@H_502_0@代码的格式如下:

@H_502_0@

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

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

@H_502_0@*****UserController.java

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;@Controllerpublic 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,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";   }}
@H_502_0@此时,直接运行Apptest.java,然后在浏览器输入地址:localhost:8080/regist 注册新的账号(我输入的是用户名:小明 密码:123456),如图

@H_502_0@此时查看数据库信息

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

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

@H_502_0@以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。

总结

以上是内存溢出为你收集整理的Springboot实现密码的加密解密全部内容,希望文章能够帮你解决Springboot实现密码的加密解密所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1227430.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-05
下一篇 2022-06-05

发表评论

登录后才能评论

评论列表(0条)

保存