spring boot 对配置文件加密

配置文件中的数据库账户、密码不能明文展示。否则代码泄露的话,数据库就被人删除跑路了。

首先引入依赖

<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>2.1.2</version>
</dependency>

  

编写测试代码

@Test
	public void testDecrypt(){
		BasicTextEncryptor textEncryptor = new BasicTextEncryptor();
		//加密所需的salt(盐)
		textEncryptor.setPassword("bad_boy");
		//要加密的数据(数据库的用户名或密码)
		String username = textEncryptor.encrypt("root");
		String password = textEncryptor.encrypt("123456");
		System.out.println("username: " + username);
		System.out.println("password:" + password);
	}

  

将加密后的数据填写到配置文件中

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/wcscanner?characterEncoding=utf-8&useSSL=false&allowPublicKeyRetrieval=true
    username: ENC(JWkISjb1dfh+x1AMNIqr/Q==)
    password: ENC(rMP11CKRnw+s1vM/iTgF1FdS+XylskGiM3fZqMeaOFM=)

  

加密配置

jasypt:
  encryptor:
    password:
    algorithm: PBEWithMD5AndDES

  

运行时增加秘钥变量

--jasypt.encryptor.password=bad_boy

java -jar foo.jar --jasypt.encryptor.password=bad_boy

愉快运行即可。

解密代码

 

posted @ 2022-06-16 12:55  妇愁者纞萌  阅读(566)  评论(0编辑  收藏  举报