在日常开发中,我们一般会把账号密码以及一些用到的各种第三方服务的access_key都放入yml文件中,这时就有必要对yml文件进行加密处理了,
jasypt是一款简单的对yml加密的工具
1.依赖
<dependency>
<groupid>com.github.ulisesbocchio</groupid>
<artifactid>jasypt-spring-boot-starter</artifactid>
<version>2.1.0</version>
</dependency>2.yml文件
server:
port: 80
spring:
application:
name: demo
# =========================== ↓↓↓↓↓↓ 配置数据源 ↓↓↓↓↓↓ ===========================
datasource:
url: jdbc:mysql://127.0.0.1:3306/demo?allowmultiqueries=true&useunicode=true&characterencoding=utf8&zerodatetimebehavior=converttonull&usessl=false # mysql在高版本需要指明是否进行ssl连接 解决则加上 &usessl=false
name: demo
username: jasypt_zack(wfv3a0rfjzkupplrriseyg==)
password: jasypt_zack(wfv3a0rfjzkupplrriseyg==)
platform: mysql
driver-class-name: com.mysql.jdbc.driver
# 配置加密密钥
jasypt:
encryptor:
property:
prefix: jasypt_zack( # todo 加密前缀
suffix: ) # todo 加密后缀
password: panghu # todo 加密密钥
这里的username和password都是以及加密完成的
需要用到密钥来进行解密,但是这个解密不需要我们来操作,我们只需要把原始值进行加密后填入就行了
3.加密操作
/**
* <p> jasypt 加密/解密 测试类$ </p>
* @description : 【 注:每次加密后的密码都不同,但根据密钥都能解析成原本的密码 】
*/
@runwith(springrunner.class)
@springboottest(classes = demoapplication.class)
public class jasypttest {
@autowired
stringencryptor jasyptstringencryptor;
@test
public void encrypt() throws exception {
system.out.println("加密: " + jasyptstringencryptor.encrypt("root"));
}
@test
public void decrypt() throws exception {
system.out.println("解密: " + jasyptstringencryptor.decrypt("n/+f2b9sznk4mudsp24upw=="));
}
// ================ ↓↓↓↓↓↓ 下面为无需加载spring容器方式 ↓↓↓↓↓↓ ================
@test
public void test() {
// 对应配置文件中配置的加密密钥
system.setproperty("jasypt.encryptor.password", "panghu");
stringencryptor stringencryptor = new defaultlazyencryptor(new standardenvironment());
system.out.println("加密: " + stringencryptor.encrypt("root"));
system.out.println("解密: " + stringencryptor.decrypt("np9pjxccufbzme5j4pl1aw=="));
}
}总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论