记用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代码


<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>Titletitle>
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即可获得加密后字符串


<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>Titletitle>
head>
<body>
<h1>Resulth1>
<p th:text="'密码: ' + ${passwordBean.password}" />
<p th:text="'加密字符: ' + ${passwordBean.var1}" />
<p th:text="'加密后字符: ' + ${passwordBean.var2}" />
<a href="/getkey">Submit another messagea>
body>
html>

简单吧 spring boot就是这么方便

你可能感兴趣的:(密码学,spring,boot)