Springboot實(shí)現(xiàn)密碼的加密解密
現(xiàn)今對于大多數(shù)公司來說,信息安全工作尤為重要,就像京東,阿里巴巴這樣的大公司來說,信息安全是最為重要的一個(gè)話題,舉個(gè)簡單的例子:

就像這樣的密碼公開化,很容易造成一定的信息的泄露。所以今天我們要講的就是如何來實(shí)現(xiàn)密碼的加密和解密來提高數(shù)據(jù)的安全性。
在這首先要引入springboot融合mybatis的知識(shí),如果有這方面不懂得同學(xué),就要首先看一看這方面的知識(shí):
推薦大家一個(gè)比較好的博客: 程序猿DD-翟永超 http://blog.didispace.com/springbootmybatis/
為了方便大家的學(xué)習(xí),我直接將源代碼上傳:
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>
2. AppTest.java
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
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
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
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
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.還有一些靜態(tài)HTML
(1.)regist.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>注冊賬號(hào)</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
<!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" >注冊賬號(hào)</a>
</form>
</div>
</body>
</html>
(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>
(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>
(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>
代碼的格式如下:

完成了這一步的話首先運(yùn)行一下AppTest看是否出錯(cuò),如果有錯(cuò),自己找原因,這里就不和大家討論了,寫了這么多,才要要進(jìn)入正題了
本文采取的是EDS的加密解密方法,方法也很簡單,不用添加額外的jar包,只需要在UserController上做出簡單的修改就可以了:
*****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;
@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算法要求有一個(gè)可信任的隨機(jī)數(shù)源
SecureRandom sr = new SecureRandom();
DESKeySpec deskey = new DESKeySpec(DES_KEY);
// 創(chuàng)建一個(gè)密匙工廠,然后用它把DESKeySpec轉(zhuǎn)換成一個(gè)SecretKey對象
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey key = keyFactory.generateSecret(deskey);
// 加密對象
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE, key, sr);
// 加密,并把字節(jié)數(shù)組編碼成字符串
encryptedData = new sun.misc.BASE64Encoder().encode(cipher.doFinal(data.getBytes()));
} catch (Exception e) {
// log.error("加密錯(cuò)誤,錯(cuò)誤信息:", e);
throw new RuntimeException("加密錯(cuò)誤,錯(cuò)誤信息:", e);
}
return encryptedData;
}
@SuppressWarnings("restriction")
public static String decryptBasedDes(String cryptData) {
String decryptedData = null;
try {
// DES算法要求有一個(gè)可信任的隨機(jī)數(shù)源
SecureRandom sr = new SecureRandom();
DESKeySpec deskey = new DESKeySpec(DES_KEY);
// 創(chuàng)建一個(gè)密匙工廠,然后用它把DESKeySpec轉(zhuǎn)換成一個(gè)SecretKey對象
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey key = keyFactory.generateSecret(deskey);
// 解密對象
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.DECRYPT_MODE, key, sr);
// 把字符串進(jìn)行解碼,解碼為為字節(jié)數(shù)組,并解密
decryptedData = new String(cipher.doFinal(new sun.misc.BASE64Decoder().decodeBuffer(cryptData)));
} catch (Exception e) {
throw new RuntimeException("解密錯(cuò)誤,錯(cuò)誤信息:", 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";
}
}
此時(shí),直接運(yùn)行Apptest.java,然后在瀏覽器輸入地址:localhost:8080/regist 注冊新的賬號(hào)(我輸入的是用戶名:小明 密碼:123456),如圖

此時(shí)查看數(shù)據(jù)庫信息

你就會(huì)發(fā)現(xiàn)密碼實(shí)現(xiàn)了加密。
當(dāng)然,下次登陸的時(shí)候直接輸入相應(yīng)的賬號(hào)和密碼即可完成登錄,實(shí)現(xiàn)了解碼的過程。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- SpringBoot使用AES對JSON數(shù)據(jù)加密和解密的實(shí)現(xiàn)方法
- springboot使用國產(chǎn)加密算法方式,sm2和sm3加解密demo
- Springboot接口返回參數(shù)及入?yún)SA加密解密的過程詳解
- SpringBoot實(shí)現(xiàn)接口參數(shù)加密解密的示例代碼
- 關(guān)于Springboot數(shù)據(jù)庫配置文件明文密碼加密解密的問題
- springboot實(shí)現(xiàn)敏感字段加密存儲(chǔ)解密顯示功能
- springboot實(shí)現(xiàn)注冊加密與登錄解密功能(demo)
- SpringBoot接口加密解密統(tǒng)一處理
- 在SpringBoot中通過jasypt進(jìn)行加密解密的方法
- SpringBoot實(shí)現(xiàn)國密SM4加密解密的使用示例
相關(guān)文章
Java將Word文檔轉(zhuǎn)換為PDF文件的幾種常用方法總結(jié)
這篇文章主要介紹了Java將Word文檔轉(zhuǎn)換為PDF文件的四種常用方法,分別使用ApachePOI+iText、Aspose.Words?for?Java、Docx4j和JODConverter,這些庫各有優(yōu)點(diǎn),但在使用時(shí)需要注意庫與Java環(huán)境的兼容性、安裝所需依賴、轉(zhuǎn)換速度和資源消耗,需要的朋友可以參考下2024-10-10
spring-boot-starter-web更換默認(rèn)Tomcat容器的方法
Spring Boot支持容器的自動(dòng)配置,默認(rèn)是Tomcat,當(dāng)然我們也是可以進(jìn)行修改的。下面小編給大家?guī)砹藄pring-boot-starter-web更換默認(rèn)Tomcat容器的方法,感興趣的朋友跟隨小編一起看看吧2019-04-04
SpringBoot如何使用@Aspect注解實(shí)現(xiàn)AOP
這篇文章主要介紹了SpringBoot如何使用@Aspect注解實(shí)現(xiàn)AOP問題,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-07-07
史上最簡單的MyBatis動(dòng)態(tài)SQL入門示例代碼
動(dòng)態(tài)sql,可以根據(jù)用戶對字段選擇和輸入,動(dòng)態(tài)生成一條sql執(zhí)行。接下來通過本文給大家分享MyBatis動(dòng)態(tài)SQL入門示例代碼,一起看看吧2017-03-03
詳解Java面試官最愛問的volatile關(guān)鍵字
這篇文章主要介紹了詳解Java面試官最愛問的volatile關(guān)鍵字,小編覺得還是挺不錯(cuò)的,具有一定借鑒價(jià)值,需要的朋友可以參考下2018-01-01
java?數(shù)組實(shí)現(xiàn)學(xué)生成績統(tǒng)計(jì)教程
這篇文章主要介紹了java?數(shù)組實(shí)現(xiàn)學(xué)生成績統(tǒng)計(jì)教程,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-12-12

