springboot使用jasypt对配置文件中的账号密码进行加密

使用的springboot 版本为2.0.0.RELEASE

1.引入依赖

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

2.生成加密后的密文

import org.jasypt.util.text.BasicTextEncryptor;
import org.junit.Test;

public class PassworkEncryTest {

	@Test
	public void generateKey() {
		BasicTextEncryptor encryptor = new BasicTextEncryptor();
		encryptor.setPassword("abcdef.");//密钥
		String mysqlUatName = encryptor.encrypt("test");//用户名
		String mysqlUatPassword = encryptor.encrypt("test123");//密码
		System.out.println("mysqlUatName:"+mysqlUatName);
		System.out.println("mysqlUatPassword:"+mysqlUatPassword);

		
	}
}

输出结果为:

mysqlUatName:8y35VY0H4c60IgnGXI8oCg== mysqlUatPassword:Q+XdWGkzX7HH7WEM0PO2bQ==

3 修改配置文件

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: ENC(8y35VY0H4c60IgnGXI8oCg==)
    password: ENC(Q+XdWGkzX7HH7WEM0PO2bQ==)
    url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&serverTimezone=UTC
  

jasypt:
  encryptor:
    password: abcdef.
    algorithm:  PBEWithMD5AndDES
    iv-generator-classname: org.jasypt.iv.NoIvGenerator
经验分享 程序员 微信小程序 职场和发展