第一步:pom.xml
中引入依赖
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>2.0.0</version>
</dependency>
第二步:加盐(三种方式)
1.yml中
jasypt:
encryptor:
password: ${JASYPT_ENCRYPTOR_PASSWORD:}
在环境变量中配置 JASYPT_ENCRYPTOR_PASSWORD =xxx (xxx根据自己的密钥设置)
2.在Program arguments 中设置 --jasypt.encryptor.password=xxx
3.在vm arguments 中设置 -Djasypt.encryptor.password=xxx
第三步:编写测试
package com.org;
import org.jasypt.encryption.StringEncryptor;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class EncryptorTest {
@Autowired
private StringEncryptor encryptor;
@Test
public void encry() {
String username = encryptor.encrypt("UserName");
String password = encryptor.encrypt("Password");
System.out.println(username);
//获取加密的name 7VNwO00NWlgoqduTFjh9+NQrFnw/92Uu 在DB配置中替换
System.out.println(password);
//获取加密的password 3g8eMXCA6UwoB3bqtfY5cOjJQRymvc8b 在DB配置中替换
}
}
第四步:替换DB配置信息
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://xx.x.x.xx:3306/zxxxx
username: ENC(7VNwO00NWlgoqduTFjh9+NQrFnw/92Uu)
password: ENC(3g8eMXCA6UwoB3bqtfY5cOjJQRymvc8b)
到这一步就OK了,如果需要自定义密文的前后缀,可如下设置:
jasypt:
encryptor:
property:
prefix: "ENC@["
suffix: "]"
更详细文档请参考:https://github.com/ulisesbocchio/jasypt-spring-boot