官网:https://github.com/ulisesbocchio/jasypt-spring-boot
1.pom.xml 添加依赖
<!-- 配置文件加密 --> <dependency> <groupId>com.github.ulisesbocchio</groupId> <artifactId>jasypt-spring-boot-starter</artifactId> <version>2.1.0</version> </dependency>
2.yml配置文件中添加配置
# jasypt加密的密匙
jasypt:
encryptor:
password: dcsyun2021
3.对字段加密
@Autowired private StringEncryptor encryptor; @Test public void encryptTest() { String url = encryptor.encrypt("jdbc:mysql://192.168.3.60:3307/wiswater-new?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8");
String name = encryptor.encrypt("root"); String password = encryptor.encrypt("123456"); System.out.println("database url: " + url);
// XRX8eZnUDhD/fQDpa7E4gy7h8ubM/Eem1jawU014onz2dZFmW+6toVajsHigh+6GqPOizyN8JvYmDFgN9OEVW6kSjDecuRjC7fjIpZerV3O0vXd7HlsQWcJDolDXckNQlme6YiC4OBeH6JHrkmKeK/rMJqmLZj4TJ4XI/8c3jm8=
System.out.println("database name: " + name); // Gnyix1PvbDWdKgrhGcWX8A== System.out.println("database password: " + password); // TVXsdy+PU7Yt2Ye5n/0CXA== }
4.修改yml文件
spring:
# 数据库相关配置
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
# 这里加上后缀用来防止mysql乱码,serverTimezone=GMT%2b8设置时区
url: ENC(XRX8eZnUDhD/fQDpa7E4gy7h8ubM/Eem1jawU014onz2dZFmW+6toVajsHigh+6GqPOizyN8JvYmDFgN9OEVW6kSjDecuRjC7fjIpZerV3O0vXd7HlsQWcJDolDXckNQlme6YiC4OBeH6JHrkmKeK/rMJqmLZj4TJ4XI/8c3jm8=)
username: ENC(Gnyix1PvbDWdKgrhGcWX8A==)
password: ENC(TVXsdy+PU7Yt2Ye5n/0CXA==)
5.为了避免jasypt加密的密匙泄露,可以使用命令方式
java -jar xxx.jar -D jasypt.encryptor.password=dcsyun2021
或者自己重新创建一个Bean
@Bean("encryptorBean") public StringEncryptor stringEncryptor() { SimpleGCMConfig config = new SimpleGCMConfig(); config.setSecretKeyPassword("chupacabras"); config.setSecretKeyIterations(1000); config.setSecretKeySalt("HrqoFr44GtkAhhYN+jP8Ag=="); config.setSecretKeyAlgorithm("PBKDF2WithHmacSHA256"); return new SimpleGCMStringEncryptor(config); }
地址:https://github.com/ulisesbocchio/jasypt-spring-boot#demo-app