在配置文件中,往往会有密码,例如mysql,redis等。如果直接将密码和url以明文的形式写在项目中,就会有泄露的风险。所以这里使用jasypt,用于配置文件密。
1.引入依赖(gradle|maven)
1
| implementation 'com.github.ulisesbocchio:jasypt-spring-boot-starter:2.1.0'
|
1 2 3 4 5
| <dependency> <groupId>com.github.ulisesbocchio</groupId> <artifactId>jasypt-spring-boot-starter</artifactId> <version>2.1.0</version> </dependency>
|
2.配置密钥(二选一,但是更建议通过参数,因为参数能取环境变量中的值,这样只能账户的拥有者能看到密钥,更加安全)
1 2
| -Djasypt.encryptor.password=vegetablest
|
1 2 3 4 5 6 7 8 9
| jasypt: encryptor: password: vegetablest
|
3.数据加密
- 命令式
1 2
| # cd ~/.gradle/caches/modules-2/files-2.1/org.jasypt/jasypt/1.9.2/ # java -cp ./jasypt-1.9.2.jar org.jasypt.intf.cli.JasyptPBEStringEncryptionCLI algorithm=PBEWithMD5AndDES password="vegetablest" input=your password
|
- 插件式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| # 如果对开发者可信,可以通过Maven插件进行 <build> <plugins> <plugin> <groupId>com.github.ulisesbocchio</groupId> <artifactId>jasypt-maven-plugin</artifactId> <version>3.0.3</version> <configuration> <path>file:src/main/resources/application.yml</path> </configuration> </plugin> </plugins> </build> # 用DEC()包裹需要加密的字符 # mvn jasypt:encrypt -Djasypt.encryptor.password="password"
|
- 编程式
1 2 3 4 5 6 7 8 9 10 11 12
| public class PasswdTest extends BaseTest {
@Autowired private StringEncryptor encryptor;
@Test public void contextLoads() { String esHost = encryptor.encrypt("https://192.168.2.10:9200"); System.out.println("esHost = " + "ENC(" + esHost + ")"); } }
|
4.使用
在spring boot配置文件中就能通过ENC()包括起来的形式配置自己的敏感配置了,就像下边那样
1 2 3 4
| map: service: key: ENC(iLB3vWEUOXOfEUjyCfCO9LVUaHShs3I1pWA22TBahY+s3LR2KHqXS+8wP+32336u) url: https://restapi.amap.com/v3/geocode/regeo?key={key}&location={location}
|