1. 程式人生 > >記用spring boot 實現簡單AES加密演算法

記用spring boot 實現簡單AES加密演算法

這個寫了好幾個月了,拿出來記一下。
業務需求:資料庫中的使用者名稱密碼明文儲存在配置檔案中,不是十分安全。所以將資料庫中的使用者名稱密碼使用AES對稱加密放入配置檔案中,達到加密效果。同時也不想使用tomcat等中介軟體等太繁重,就使用了spring boot 輕量級框架。個人比較菜,輕噴。
關於如何搭建spring boot專案其他的人說的很詳細 參考初識Spring Boot框架

入口類程式碼

@Controller
@SpringBootApplication
@EnableAutoConfiguration
public class Aesdemo1Application {

    public
static void main(String[] args) { SpringApplication.run(Aesdemo1Application.class, args); } }

執行時只要執行main方法 或者打包後java -jar 即可(寫成.bat檔案 點選執行方便簡單)

@Controller
public class GetKeyController {
    @GetMapping("/getkey")
        public String greetingForm(Model model) {
            model.addAttribute("passwordBean"
, new PasswordBean()); return "index"; } @PostMapping("/getkey") public String greetingSubmit(@ModelAttribute PasswordBean passwordBean) { String s1 = AESUtil.encrypt(passwordBean.getPassword(), passwordBean.getVar1()); passwordBean.setVar2(s1); return
"result"; } }

啟動後有這裡還有一個控制器類
瀏覽器地址輸入 http://localhost:8080/getkey 即可跳轉到greetingForm 方法,賦入PasswordBean屬性後 跳轉到index.html
PasswordBean 是自己定義的bean類 裡面有password var1 var2 3個屬性

index.html程式碼

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>Title</title>
</head>
<body>
<form action="#" th:action="@{/getkey}" th:object="${passwordBean}" method="post">
    <p>密碼: <input type="text" th:field="*{password}" /></p>
    <p>加密字元: <input type="text" th:field="*{var1}" /></p>
    <p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
</form>
</body>
</html>

注意使用了thymeleaf框架 所以必須引入

輸入要加密的和鹽即可獲得通過post方法到result即可獲得加密後字串

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>Title</title>
</head>
<body>
<h1>Result</h1>
<p th:text="'密碼: ' + ${passwordBean.password}" />
<p th:text="'加密字元: ' + ${passwordBean.var1}" />
<p th:text="'加密後字元: ' + ${passwordBean.var2}" />
<a href="/getkey">Submit another message</a>
</body>
</html>

簡單吧 spring boot就是這麼方便