发布于 1年前

Spring Boot使用Jasypt加密配置文件

Jasypt Spring Boot为Spring Boot项目的属性提供了加密支持。有三种方式集成jasypt-spring-boot到Spring boot应用中。

jasypt-spring-boot-starter

如果Spring Boot项目中使用了@SpringBootApplication或者@EnableAutoConfiguration,在项目里添加jasypt-spring-boot-starter依赖会自动对项目中整个属性(包括系统属性,环境属性, 命令行参数, application.properties, yaml)启动加密。

Maven依赖如下:

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

jasypt-spring-boot

如果项目里没有使用@SpringBootApplication或者@EnableAutoConfiguration,可以手动在Configuration类上添加注解@EnableEncryptableProperties,来在整个环境的属性启用属性加密。

Maven依赖如下:

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

使用:

@Configuration
@EnableEncryptableProperties
public class MyApplication {
    ...
}

指定加密属性文件

前面两种方法都会在整个环境中启动属性加密。如果想指定加密文件,可以使用@EncryptablePropertySource指定。

Maven依赖:

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

@EncryptablePropertySource指定文件:

@Configuration
@EncryptablePropertySource(name = "EncryptedProperties", value = "classpath:encrypted.properties")
public class MyApplication {
    ...
}

@EncryptablePropertySources指定多个文件:

@Configuration
@EncryptablePropertySources({@EncryptablePropertySource("classpath:encrypted.properties"),
                                 @EncryptablePropertySource("classpath:encrypted2.properties")})
public class MyApplication {
    ...
}

如果项目里使用@SpringBootApplication,可以使用@PropertySource指定加密的文件:

@SpringBootApplication
@EnableEncryptableProperties
@PropertySource(name="EncryptedProperties", value = "classpath:encrypted.properties")
public class MyApplication {
        ...
}

使用

生成密文

使用jasypt jar包生成密文:

 java -cp ~/.m2/repository/org/jasypt/jasypt/1.9.2/jasypt-1.9.2.jar  org.jasypt.intf.cli.JasyptPBEStringEncryptionCLI input="contactspassword" password=supersecretz algorithm=PBEWithMD5AndDES

命令输出如下:

----ENVIRONMENT-----------------
Runtime: Oracle Corporation Java HotSpot(TM) 64-Bit Server VM 24.45-b08
----ARGUMENTS-------------------
algorithm: PBEWithMD5AndDES
input: contactspassword
password: supersecretz
----OUTPUT----------------------
XcBjfjDDjxeyFBoaEPhG14wEzc6Ja+Xx+hNPrJyQT88=

jasypt需要设置用于加密明文的密钥password,它会对input内容加密。

配置文件中使用密文

xxx=ENC(密文)

启动spring boot应用需要--jasypt.encryptor.password配置前面用来加密明文的密码。

java -jar target/jasypt-spring-boot-demo-0.0.1-SNAPSHOT.jar --jasypt.encryptor.password=supersecretz
©2020 edoou.com   京ICP备16001874号-3