运行

运行时配置解密秘钥
-Djasypt.encryptor.password=
在idea中运行

命令行启动和docker中运行参见
https://www.cnblogs.com/zz0412/p/jasypt-001.html

Spring Boot: How to encrypt properties in application.properties

Sometimes you don’t want your properties to stay as plain text in application.properties file. Maybe you are connecting to a database and you have to write your database password in application.properties. In this tutorial, I am going to use Jasypt library for that purpose. Jasypt (Java Simplified Encryption) is a java library which allows the developer to add basic encryption capabilities to his/her projects with minimum effort, and without the need of having deep knowledge on how cryptography works.

Let’s begin,
First, add the related dependency to the project. I am using maven, so I will add the maven dependency to my pom.xml

<!-- https://mvnrepository.com/artifact/com.github.ulisesbocchio/jasypt-spring-boot-starter -->

  1. <dependency>
  2. <groupId>com.github.ulisesbocchio</groupId>
  3. <artifactId>jasypt-spring-boot-starter</artifactId>
  4. <version>2.0.0</version>
  5. </dependency>

In the application.properties (or yaml), we will write our encrypted properties between parenthesis and put ENC keyword before it. Like;

MyProperty=ENC(23ClLWiedLx8v6XT6Wk+Bg==)
 

How to generate those encrpyted values? We will use Jasypt for that! Go to http://www.jasypt.org/ and download the latest version. When you are done, go into jasypt\bin and use the encrypt.sh or encrypt.bat to encrypt your variables. There are several algorithms to pick but I will leave it as default and only give my property value and secret to encrpyt it.

We only need to add @EnableConfigurationProperties annotation to our application and jasypt will automaticly detect encrypted values and decrypt them before they are being used. The CommandLineRunner I have added below is just to test the decryption mechanism.

@EnableEncryptableProperties
@SpringBootApplication
public class JasyptExampleApplication {

public static void main(String[] args) {
    SpringApplication.run(JasyptExampleApplication.class, args);
  }
  
  @Component
  public class MyRunner implements CommandLineRunner {
    
    @Value("${myProperty}")
    private String myProperty;

@Override
    public void run(String... args) throws Exception {
      System.out.println("My property is = " + myProperty);
    }
    
  }
}

 

But if you run your code like this, you will get the below error:

Error creating bean with name 'demo.JasyptExampleApplication$MyRunner': Injection of autowired dependencies failed; nested exception is java.lang.IllegalStateException: Required Encryption configuration property missing: jasypt.encryptor.password

This is because Jasypt needs to know the secret(password) to decrypt the property. We can tell this to our program several ways:
1- We can give it as a command line argument when running the application;
–jasypt.encryptor.password=MY_SECRET
2- We can set it as an environment variable, this is also useful when you are running your application on Tomcat. You can give it to Tomcat’s setenv.sh file;
export CATALINA_OPTS=”-Djasypt.encryptor.password=MY_SECRET”
You can also unset the environment variable after running the application, so there will be no doorway left behind, at least in a human-readable sense.
3- You can give it in application.properties but this might be the dumbest way as it has no difference with giving the property as plain text.
If you know a better way, write a comment below!

Now let’s look at the final output:

2018-04-25 14:03:26.413 INFO 10028 --- [ main] c.u.j.EncryptablePropertySourceConverter : Converting PropertySource configurationProperties [org.springframework.boot.context.properties.source.ConfigurationPropertySourcesPropertySource] to AOP Proxy
2018-04-25 14:03:26.413 INFO 10028 --- [ main] c.u.j.EncryptablePropertySourceConverter : Converting PropertySource commandLineArgs [org.springframework.core.env.SimpleCommandLinePropertySource] to EncryptableEnumerablePropertySourceWrapper
2018-04-25 14:03:26.414 INFO 10028 --- [ main] c.u.j.EncryptablePropertySourceConverter : Converting PropertySource systemProperties [org.springframework.core.env.MapPropertySource] to EncryptableMapPropertySourceWrapper
2018-04-25 14:03:26.414 INFO 10028 --- [ main] c.u.j.EncryptablePropertySourceConverter : Converting PropertySource systemEnvironment [org.springframework.boot.env.SystemEnvironmentPropertySourceEnvironmentPostProcessor$OriginAwareSystemEnvironmentPropertySource] to EncryptableMapPropertySourceWrapper
2018-04-25 14:03:26.414 INFO 10028 --- [ main] c.u.j.EncryptablePropertySourceConverter : Converting PropertySource random [org.springframework.boot.env.RandomValuePropertySource] to EncryptablePropertySourceWrapper
2018-04-25 14:03:26.415 INFO 10028 --- [ main] c.u.j.EncryptablePropertySourceConverter : Converting PropertySource applicationConfig: [classpath:/application.properties] [org.springframework.boot.env.OriginTrackedMapPropertySource] to EncryptableMapPropertySourceWrapper
2018-04-25 14:03:26.468 INFO 10028 --- [ main] c.u.j.r.DefaultLazyPropertyResolver : Property Resolver custom Bean not found with name 'encryptablePropertyResolver'. Initializing Default Property Resolver
2018-04-25 14:03:26.470 INFO 10028 --- [ main] c.u.j.d.DefaultLazyPropertyDetector : Property Detector custom Bean not found with name 'encryptablePropertyDetector'. Initializing Default Property Detector
2018-04-25 14:03:26.472 INFO 10028 --- [ main] c.u.j.encryptor.DefaultLazyEncryptor : String Encryptor custom Bean not found with name 'jasyptStringEncryptor'. Initializing Default String Encryptor
2018-04-25 14:03:26.478 INFO 10028 --- [ main] c.u.j.encryptor.DefaultLazyEncryptor : Encryptor config not found for property jasypt.encryptor.algorithm, using default value: PBEWithMD5AndDES
2018-04-25 14:03:26.479 INFO 10028 --- [ main] c.u.j.encryptor.DefaultLazyEncryptor : Encryptor config not found for property jasypt.encryptor.keyObtentionIterations, using default value: 1000
2018-04-25 14:03:26.479 INFO 10028 --- [ main] c.u.j.encryptor.DefaultLazyEncryptor : Encryptor config not found for property jasypt.encryptor.poolSize, using default value: 1
2018-04-25 14:03:26.479 INFO 10028 --- [ main] c.u.j.encryptor.DefaultLazyEncryptor : Encryptor config not found for property jasypt.encryptor.providerName, using default value: null
2018-04-25 14:03:26.479 INFO 10028 --- [ main] c.u.j.encryptor.DefaultLazyEncryptor : Encryptor config not found for property jasypt.encryptor.providerClassName, using default value: null
2018-04-25 14:03:26.479 INFO 10028 --- [ main] c.u.j.encryptor.DefaultLazyEncryptor : Encryptor config not found for property jasypt.encryptor.saltGeneratorClassname, using default value: org.jasypt.salt.RandomSaltGenerator
2018-04-25 14:03:26.480 INFO 10028 --- [ main] c.u.j.encryptor.DefaultLazyEncryptor : Encryptor config not found for property jasypt.encryptor.stringOutputType, using default value: base64
2018-04-25 14:03:26.934 INFO 10028 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2018-04-25 14:03:26.948 INFO 10028 --- [ main] demo.JasyptExampleApplication : Started JasyptExampleApplication in 1.264 seconds (JVM running for 2.06)
My property is MBcoder

As you can see it picked up the PBEWithMD5AndDES algorithm as default value and with the given password, MY_SECRET, it successfully decrypted myProperty
I hope this article was useful, see you another time!
http://mbcoder.com/spring-boot-how-to-encrypt-properties-in-application-properties/

使用Jasypt对SpringBoot配置文件加密

引入jasypt

  1. <dependency>
  2. <groupId>com.github.ulisesbocchio</groupId>
  3. <artifactId>jasypt-spring-boot-starter</artifactId>
  4. <version>2.0.0</version>
  5. </dependency>

生成要加密的字符串

将数据库的用户名和密码进行加密

  1. public static void main(String[] args) {
  2. BasicTextEncryptor textEncryptor = new BasicTextEncryptor();
  3. //加密所需的salt(盐)
  4. textEncryptor.setPassword("G0CvDz7oJn6");
  5. //要加密的数据(数据库的用户名或密码)
  6. String username = textEncryptor.encrypt("root");
  7. String password = textEncryptor.encrypt("root123");
  8. System.out.println("username:"+username);
  9. System.out.println("password:"+password);
  10. }

输出信息为:

  1. username:i8QgEN4uOy2E1rHzrpSTYA==
  2. password:6eaMh/RX5oXUVca9ignvtg==

或者使用Maven下载好的jar包加密\Maven\org\jasypt\jasypt\1.9.2\jasypt-1.9.2.jar

  1. java -cp jasypt-1.9.2.jar org.jasypt.intf.cli.JasyptPBEStringEncryptionCLI password=G0CvDz7oJn6 algorithm=PBEWithMD5AndDES input=root

输出信息为:

  1. ----ENVIRONMENT-----------------
  2. Runtime: Oracle Corporation Java HotSpot(TM) 64-Bit Server VM 25.171-b11
  3. ----ARGUMENTS-------------------
  4. input: root
  5. algorithm: PBEWithMD5AndDES
  6. password: G0CvDz7oJn6
  7. ----OUTPUT----------------------
  8. Gvkoz+sbFWiRe3ECtizV1A==

拷贝-OUTPUT-下的结果即可

配置properties文件

将生成的加密串配置ENC(加密串)到application.properties中

  1. # 加密所需的salt(盐)
  2. jasypt.encryptor.password=G0CvDz7oJn6
  3. # 默认加密方式PBEWithMD5AndDES,可以更改为PBEWithMD5AndTripleDES
  4. # jasypt.encryptor.algorithm=PBEWithMD5AndDES
  5. spring.datasource.username=ENC(6eaMh/RX5oXUVca9ignvtg==)
  6. spring.datasource.password=ENC(6eaMh/RX5oXUVca9ignvtg==)

加密方式对应的类为BasicTextEncryptor和StrongTextEncryptor

  1. public BasicTextEncryptor() {
  2. super();
  3. this.encryptor = new StandardPBEStringEncryptor();
  4. this.encryptor.setAlgorithm("PBEWithMD5AndDES");
  5. }
  6. public StrongTextEncryptor() {
  7. super();
  8. this.encryptor = new StandardPBEStringEncryptor();
  9. this.encryptor.setAlgorithm("PBEWithMD5AndTripleDES");
  10. }
 
类图

部署时配置salt(盐)值

为了防止salt(盐)泄露,反解出密码.可以在项目部署的时候使用命令传入salt(盐)值

  1. java -jar -Djasypt.encryptor.password=G0CvDz7oJn6 xxx.jar

或者在服务器的环境变量里配置,进一步提高安全性

  1. 打开/etc/profile文件
  2. vim /etc/profile
  3. 文件末尾插入
  4. export JASYPT_PASSWORD = G0CvDz7oJn6
  5. 编译
  6. source /etc/profile
  7. 运行
  8. java -jar -Djasypt.encryptor.password=${JASYPT_PASSWORD} xxx.jar

官方地址 : https://github.com/ulisesbocchio/jasypt-spring-boot

作者:风静花犹落
链接:https://www.jianshu.com/p/323ec96c46d2
来源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

http://www.jasypt.org/encrypting-texts.html

Jasypt Spring Boot provides Encryption support for property sources in Spring Boot Applications.
There are 3 ways to integrate jasypt-spring-boot in your project:

  • Simply adding the starter jar jasypt-spring-boot-starter to your classpath if using @SpringBootApplication or @EnableAutoConfiguration will enable encryptable properties across the entire Spring Environment
  • Adding jasypt-spring-boot to your classpath and adding @EnableEncryptableProperties to your main Configuration class to enable encryptable properties across the entire Spring Environment
  • Adding jasypt-spring-boot to your classpath and declaring individual encryptable property sources with @EncrytablePropertySource

What's new?

Update 1/8/2019: Version 2.1.1 Release Including Asymmetric Encryption
and support for JSB96 with IV Generators (Thanks @melloware!!)

Update 7/17/2018: Version 2.1.0 Release Including Filters

Update 3/17/2018: Version 2.0.0 has been released supporting Spring Boot 2.0.X.RELEASE. SemVer adopted.

Update 7/18/2015: jasypt-spring-boot is now in Maven Central!

What to do First?

Use one of the following 3 methods (briefly explained above):

  1. Simply add the starter jar dependency to your project if your Spring Boot application uses @SpringBootApplication or @EnableAutoConfiguration and encryptable properties will be enabled across the entire Spring Environment (This means any system property, environment property, command line argument, application.properties, yaml properties, and any other custom property sources can contain encrypted properties):

    1. <dependency>
    2. <groupId>com.github.ulisesbocchio</groupId>
    3. <artifactId>jasypt-spring-boot-starter</artifactId>
    4. <version>2.1.1</version>
    5. </dependency>
  2. IF you don't use @SpringBootApplication or @EnableAutoConfiguration Auto Configuration annotations then add this dependency to your project:

    1. <dependency>
    2. <groupId>com.github.ulisesbocchio</groupId>
    3. <artifactId>jasypt-spring-boot</artifactId>
    4. <version>2.1.1</version>
    5. </dependency>

    And then add @EnableEncryptableProperties to you Configuration class. For instance:

    1. @Configuration
    2. @EnableEncryptableProperties
    3. public class MyApplication {
    4. ...
    5. }

And encryptable properties will be enabled across the entire Spring Environment (This means any system property, environment property, command line argument, application.properties, yaml properties, and any other custom property sources can contain encrypted properties)

  1. IF you don't use @SpringBootApplication or @EnableAutoConfiguration Auto Configuration annotations and you don't want to enable encryptable properties across the entire Spring Environment, there's a third option. First add the following dependency to your project:

    1. <dependency>
    2. <groupId>com.github.ulisesbocchio</groupId>
    3. <artifactId>jasypt-spring-boot</artifactId>
    4. <version>2.0.0</version>
    5. </dependency>

    And then add as many @EncryptablePropertySource annotations as you want in your Configuration files. Just like you do with Spring's @PropertySource annotation. For instance:

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

Conveniently, there's also a @EncryptablePropertySources annotation that one could use to group annotations of type @EncryptablePropertySource like this:

  1. @Configuration
  2. @EncryptablePropertySources({@EncryptablePropertySource("classpath:encrypted.properties"),
  3. @EncryptablePropertySource("classpath:encrypted2.properties")})
  4. public class MyApplication {
  5. ...
  6. }

Also, note that as of version 1.8, @EncryptablePropertySource supports YAML files

Custom Environment

As of version 1.7 1.15, a 4th method of enabling encryptable properties exists for some special cases. A custom ConfigurableEnvironment class is provided: EncryptableEnvironment StandardEncryptableEnvironment and StandardEncryptableServletEnvironment that can be used with SpringApplicationBuilder to define the custom environment this way:

  1. new SpringApplicationBuilder()
  2. .environment(new StandardEncryptableEnvironment())
  3. .sources(YourApplicationClass.class).run(args);

This method would only require using a dependency for jasypt-spring-bootNotice that EncryptableEnvironment is just a wrapper, so you have to provide the actual Environment implementation, in this case StandardServletEnvironment. No starter jar dependency is required. This method is useful for early access of encrypted properties on bootstrap. While not required in most scenarios could be useful when customizing Spring Boot's init behavior or integrating with certain capabilities that are configured very early, such as Logging configuration. For a concrete example, this method of enabling encryptable properties is the only one that works with Spring Properties replacement in logback-spring.xml files, using the springProperty tag. For instance:

  1. <springProperty name="user" source="db.user"/>
  2. <springProperty name="password" source="db.password"/>
  3. <appender name="db" class="ch.qos.logback.classic.db.DBAppender">
  4. <connectionSource
  5. class="ch.qos.logback.core.db.DriverManagerConnectionSource">
  6. <driverClass>org.postgresql.Driver</driverClass>
  7. <url>jdbc:postgresql://localhost:5432/simple</url>
  8. <user>${user}</user>
  9. <password>${password}</password>
  10. </connectionSource>
  11. </appender>

This mechanism could be used for instance (as shown) to initialize Database Logging Appender that require sensitive credentials to be passed. Alternatively, if a custom StringEncryptor is needed to be provided, a second constructor EncryptableEnvironment(ConfigurableEnvironment, StringEncryptor) is available for that purpose.

How everything Works?

This will trigger some configuration to be loaded that basically does 2 things:

  1. It registers a Spring post processor that decorates all PropertySource objects contained in the Spring Environment so they are "encryption aware" and detect when properties are encrypted following jasypt's property convention.
  2. It defines a default StringEncryptor that can be configured through regular properties, system properties, or command line arguments.

Where do I put my encrypted properties?

When using METHODS 1 and 2 you can define encrypted properties in any of the PropertySource contained in the Environment. For instance, using the @PropertySource annotation:

  1. @SpringBootApplication
  2. @EnableEncryptableProperties
  3. @PropertySource(name="EncryptedProperties", value = "classpath:encrypted.properties")
  4. public class MyApplication {
  5. ...
  6. }

And your encrypted.properties file would look something like this:

  1. secret.property=ENC(nrmZtkF7T0kjG/VodDvBw93Ct8EgjCA+)

Now when you do environment.getProperty("secret.property") or use @Value("${secret.property}") what you get is the decrypted version of secret.property.
When using METHOD 3 (@EncryptablePropertySource) then you can access the encrypted properties the same way, the only difference is that you must put the properties in the resource that was declared within the @EncryptablePropertySourceannotation so that the properties can be decrypted properly.

Password-based Encryption Configuration

Jasypt uses an StringEncryptor to decrypt properties. For all 3 methods, if no custom StringEncryptor (see the Custom Encryptor section for details) is found in the Spring Context, one is created automatically that can be configured through the following properties (System, properties file, command line arguments, environment variable, etc.):

Key Required Default Value
jasypt.encryptor.password True -
jasypt.encryptor.algorithm False PBEWithMD5AndDES
jasypt.encryptor.keyObtentionIterations False 1000
jasypt.encryptor.poolSize False 1
jasypt.encryptor.providerName False SunJCE
jasypt.encryptor.providerClassName False null
jasypt.encryptor.saltGeneratorClassname False org.jasypt.salt.RandomSaltGenerator
jasypt.encryptor.ivGeneratorClassname False org.jasypt.salt.NoOpIVGenerator
jasypt.encryptor.stringOutputType False base64
jasypt.encryptor.proxyPropertySources False false

The only property required is the encryption password, the rest could be left to use default values. While all this properties could be declared in a properties file, the encryptor password should not be stored in a property file, it should rather be passed as system property, command line argument, or environment variable and as far as its name is jasypt.encryptor.password it'll work.

The last property, jasypt.encryptor.proxyPropertySources is used to indicate jasyp-spring-boot how property values are going to be intercepted for decryption. The default value, false uses custom wrapper implementations of PropertySourceEnumerablePropertySource, and MapPropertySource. When true is specified for this property, the interception mechanism will use CGLib proxies on each specific PropertySource implementation. This may be useful on some scenarios where the type of the original PropertySource must be preserved.

The property jasypt.encryptor.ivGeneratorClassname defaults to NoOpIVGenerator for backwards compatibility. However, if you would like to use the newer algorithms in Java 8+ (e.g. PBEWITHHMACSHA512ANDAES_256) you must set this value to org.jasypt.salt.RandomIVGenerator.

Use you own Custom Encryptor

For custom configuration of the encryptor and the source of the encryptor password you can always define your own StringEncryptor bean in your Spring Context, and the default encryptor will be ignored. For instance:

  1. @Bean("jasyptStringEncryptor")
  2. public StringEncryptor stringEncryptor() {
  3. PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();
  4. SimpleStringPBEConfig config = new SimpleStringPBEConfig();
  5. config.setPassword("password");
  6. config.setAlgorithm("PBEWithMD5AndDES");
  7. config.setKeyObtentionIterations("1000");
  8. config.setPoolSize("1");
  9. config.setProviderName("SunJCE");
  10. config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator");
  11. config.setIvGeneratorClassName("org.jasypt.salt.NoOpIVGenerator");
  12. config.setStringOutputType("base64");
  13. encryptor.setConfig(config);
  14. return encryptor;
  15. }

Notice that the bean name is required, as jasypt-spring-boot detects custom String Encyptors by name as of version 1.5. The default bean name is:

jasyptStringEncryptor

But one can also override this by defining property:

jasypt.encryptor.bean

So for instance, if you define jasypt.encryptor.bean=encryptorBean then you would define your custom encryptor with that name:

  1. @Bean("encryptorBean")
  2. public StringEncryptor stringEncryptor() {
  3. ...
  4. }

Custom Property Detector, Prefix, Suffix and/or Resolver

As of jasypt-spring-boot-1.10 there are new extensions points. EncryptablePropertySource now uses EncryptablePropertyResolver to resolve all properties:

  1. public interface EncryptablePropertyResolver {
  2. String resolvePropertyValue(String value);
  3. }

Implementations of this interface are responsible of both detecting and decrypting properties. The default implementation, DefaultPropertyResolver uses the before mentioned StringEncryptor and a new EncryptablePropertyDetector.

Provide a Custom EncryptablePropertyDetector

You can override the default implementation by providing a Bean of type EncryptablePropertyDetector with name encryptablePropertyDetector or if you wanna provide your own bean name, override property jasypt.encryptor.property.detector-bean and specify the name you wanna give the bean. When providing this, you'll be responsible for detecting encrypted properties. Example:

  1. private static class MyEncryptablePropertyDetector implements EncryptablePropertyDetector {
  2. @Override
  3. public boolean isEncrypted(String value) {
  4. if (value != null) {
  5. return value.startsWith("ENC@");
  6. }
  7. return false;
  8. }
  9.  
  10. @Override
  11. public String unwrapEncryptedValue(String value) {
  12. return value.substring("ENC@".length());
  13. }
  14. }
  1. @Bean(name = "encryptablePropertyDetector")
  2. public EncryptablePropertyDetector encryptablePropertyDetector() {
  3. return new MyEncryptablePropertyDetector();
  4. }

Provide a Custom Encrypted Property prefix and suffix

If all you want to do is to have different prefix/suffix for encrypted properties, you can keep using all the default implementations and just override the following properties in application.properties (or application.yml):

  1. jasypt:
  2. encryptor:
  3. property:
  4. prefix: "ENC@["
  5. suffix: "]"

Provide a Custom EncryptablePropertyResolver

You can override the default implementation by providing a Bean of type EncryptablePropertyResolver with name encryptablePropertyResolver or if you wanna provide your own bean name, override property jasypt.encryptor.property.resolver-bean and specify the name you wanna give the bean. When providing this, you'll be responsible for detecting and decrypting encrypted properties. Example:

  1. class MyEncryptablePropertyResolver implements EncryptablePropertyResolver {
  2.  
  3. private final PooledPBEStringEncryptor encryptor;
  4.  
  5. public MyEncryptablePropertyResolver(char[] password) {
  6. this.encryptor = new PooledPBEStringEncryptor();
  7. SimpleStringPBEConfig config = new SimpleStringPBEConfig();
  8. config.setPasswordCharArray(password);
  9. config.setAlgorithm("PBEWithMD5AndDES");
  10. config.setKeyObtentionIterations("1000");
  11. config.setPoolSize(1);
  12. config.setProviderName("SunJCE");
  13. config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator");
  14. config.setIvGeneratorClassName("org.jasypt.salt.NoOpIVGenerator");
  15. config.setStringOutputType("base64");
  16. encryptor.setConfig(config);
  17. }
  18.  
  19. @Override
  20. public String resolvePropertyValue(String value) {
  21. if (value != null && value.startsWith("{cipher}")) {
  22. return encryptor.decrypt(value.substring("{cipher}".length()));
  23. }
  24. return value;
  25. }
  26. }
  1. @Bean(name="encryptablePropertyResolver")
  2. EncryptablePropertyResolver encryptablePropertyResolver(@Value("${jasypt.encryptor.password}") String password) {
  3. return new MyEncryptablePropertyResolver(password.toCharArray());
  4. }

Notice that by overriding EncryptablePropertyResolver, any other configuration or overrides you may have for prefixes, suffixes, EncryptablePropertyDetector and StringEncryptor will stop working since the Default resolver is what uses them. You'd have to wire all that stuff yourself. Fortunately, you don't have to override this bean in most cases, the previous options should suffice.

But as you can see in the implementation, the detection and decryption of the encrypted properties are internal to MyEncryptablePropertyResolver

Using Filters

jasypt-spring-boot:2.1.0 introduces a new feature to specify property filters. The filter is part of the EncryptablePropertyResolver API and allows you to determine which properties or property sources to contemplate for decryption. This is, before even examining the actual property value to search for, or try to, decrypt it. For instance, by default, all properties which name start with jasypt.encryptor are excluded from examination. This is to avoid circular dependencies at load time when the library beans are configured.

DefaultPropertyFilter properties

By default, the DefaultPropertyResolver uses DefaultPropertyFilter, which allows you to specify the following string pattern lists:

  • jasypt.encryptor.property.filter.include-sources: Specify the property sources name patterns to be included for decryption
  • jasypt.encryptor.property.filter.exclude-sources: Specify the property sources name patterns to be EXCLUDED for decryption
  • jasypt.encryptor.property.filter.include-names: Specify the property name patterns to be included for decryption
  • jasypt.encryptor.property.filter.exclude-names: Specify the property name patterns to be EXCLUDED for decryption

Provide a custom EncryptablePropertyFilter

You can override the default implementation by providing a Bean of type EncryptablePropertyFilter with name encryptablePropertyFilter or if you wanna provide your own bean name, override property jasypt.encryptor.property.filter-bean and specify the name you wanna give the bean. When providing this, you'll be responsible for detecting properties and/or property sources you want to contemplate for decryption. Example:

  1. class MyEncryptablePropertyFilter implements EncryptablePropertyFilter {
  2.  
  3. public boolean shouldInclude(PropertySource<?> source, String name) {
  4. return name.startsWith('encrypted.');
  5. }
  6. }
  1. @Bean(name="encryptablePropertyFilter")
  2. EncryptablePropertyFilter encryptablePropertyFilter() {
  3. return new MyEncryptablePropertyFilter();
  4. }

Notice that for this mechanism to work, you should not provide a custom EncryptablePropertyResolver and use the default resolver instead. If you provide custom resolver, you are responsible for the entire process of detecting and decrypting properties.

Asymmetric Encryption

jasypt-spring-boot:2.1.1 introduces a new feature to encrypt/decrypt properties using asymmetric encryption with a pair of private/public keys in DER or PEM formats.

Config Properties

The following are the configuration properties you can use to config asymmetric decryption of properties;

Key Default Value Description
jasypt.encryptor.privateKeyString null private key for decryption in String format
jasypt.encryptor.privateKeyLocation null location of the private key for decryption in spring resource format
jasypt.encryptor.privateKeyFormat DER Key format. DER or PEM

You should either use privateKeyString or privateKeyLocation, the String format takes precedence if set. To specify a private key in DER format with privateKeyString, please encode the key bytes to base64.

Note that jasypt.encryptor.password still takes precedences for PBE encryption over the asymmetric config.

Sample config

DER key as string

  1. jasypt:
  2. encryptor:
  3. privateKeyString: MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCtB/IYK8E52CYMZTpyIY9U0HqMewyKnRvSo6s+9VNIn/HSh9+MoBGiADa2MaPKvetS3CD3CgwGq/+LIQ1HQYGchRrSORizOcIp7KBx+Wc1riatV/tcpcuFLC1j6QJ7d2I+T7RA98Sx8X39orqlYFQVysTw/aTawX/yajx0UlTW3rNAY+ykeQ0CBHowtTxKM9nGcxLoQbvbYx1iG9JgAqye7TYejOpviOH+BpD8To2S8zcOSojIhixEfayay0gURv0IKJN2LP86wkpAuAbL+mohUq1qLeWdTEBrIRXjlnrWs1M66w0l/6JwaFnGOqEB6haMzE4JWZULYYpr2yKyoGCRAgMBAAECggEAQxURhs1v3D0wgx27ywO3zeoFmPEbq6G9Z6yMd5wk7cMUvcpvoNVuAKCUlY4pMjDvSvCM1znN78g/CnGF9FoxJb106Iu6R8HcxOQ4T/ehS+54kDvL999PSBIYhuOPUs62B/Jer9FfMJ2veuXb9sGh19EFCWlMwILEV/dX+MDyo1qQaNzbzyyyaXP8XDBRDsvPL6fPxL4r6YHywfcPdBfTc71/cEPksG8ts6um8uAVYbLIDYcsWopjVZY/nUwsz49xBCyRcyPnlEUJedyF8HANfVEO2zlSyRshn/F+rrjD6aKBV/yVWfTEyTSxZrBPl4I4Tv89EG5CwuuGaSagxfQpAQKBgQDXEe7FqXSaGk9xzuPazXy8okCX5pT6545EmqTP7/JtkMSBHh/xw8GPp+JfrEJEAJJl/ISbdsOAbU+9KAXuPmkicFKbodBtBa46wprGBQ8XkR4JQoBFj1SJf7Gj9ozmDycozO2Oy8a1QXKhHUPkbPQ0+w3efwoYdfE67ZodpFNhswKBgQDN9eaYrEL7YyD7951WiK0joq0BVBLK3rwO5+4g9IEEQjhP8jSo1DP+zS495t5ruuuuPsIeodA79jI8Ty+lpYqqCGJTE6muqLMJDiy7KlMpe0NZjXrdSh6edywSz3YMX1eAP5U31pLk0itMDTf2idGcZfrtxTLrpRffumowdJ5qqwKBgF+XZ+JRHDN2aEM0atAQr1WEZGNfqG4Qx4o0lfaaNs1+H+knw5kIohrAyvwtK1LgUjGkWChlVCXb8CoqBODMupwFAqKL/IDImpUhc/t5uiiGZqxE85B3UWK/7+vppNyIdaZL13a1mf9sNI/p2whHaQ+3WoW/P3R5z5uaifqM1EbDAoGAN584JnUnJcLwrnuBx1PkBmKxfFFbPeSHPzNNsSK3ERJdKOINbKbaX+7DlT4bRVbWvVj/jcw/c2Ia0QTFpmOdnivjefIuehffOgvU8rsMeIBsgOvfiZGx0TP3+CCFDfRVqjIBt3HAfAFyZfiP64nuzOERslL2XINafjZW5T0pZz8CgYAJ3UbEMbKdvIuK+uTl54R1Vt6FO9T5bgtHR4luPKoBv1ttvSC6BlalgxA0Ts/AQ9tCsUK2JxisUcVgMjxBVvG0lfq/EHpL0Wmn59SHvNwtHU2qx3Ne6M0nQtneCCfR78OcnqQ7+L+3YCMqYGJHNFSard+dewfKoPnWw0WyGFEWCg==

DER key as a resource location

  1. jasypt:
  2. encryptor:
  3. privateKeyLocation: classpath:private_key.der

PEM key as string

  1. jasypt:
  2. encryptor:
  3. privateKeyFormat: PEM
  4. privateKeyString: |-
  5. -----BEGIN PRIVATE KEY-----
  6. MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCtB/IYK8E52CYM
  7. ZTpyIY9U0HqMewyKnRvSo6s+9VNIn/HSh9+MoBGiADa2MaPKvetS3CD3CgwGq/+L
  8. IQ1HQYGchRrSORizOcIp7KBx+Wc1riatV/tcpcuFLC1j6QJ7d2I+T7RA98Sx8X39
  9. orqlYFQVysTw/aTawX/yajx0UlTW3rNAY+ykeQ0CBHowtTxKM9nGcxLoQbvbYx1i
  10. G9JgAqye7TYejOpviOH+BpD8To2S8zcOSojIhixEfayay0gURv0IKJN2LP86wkpA
  11. uAbL+mohUq1qLeWdTEBrIRXjlnrWs1M66w0l/6JwaFnGOqEB6haMzE4JWZULYYpr
  12. 2yKyoGCRAgMBAAECggEAQxURhs1v3D0wgx27ywO3zeoFmPEbq6G9Z6yMd5wk7cMU
  13. vcpvoNVuAKCUlY4pMjDvSvCM1znN78g/CnGF9FoxJb106Iu6R8HcxOQ4T/ehS+54
  14. kDvL999PSBIYhuOPUs62B/Jer9FfMJ2veuXb9sGh19EFCWlMwILEV/dX+MDyo1qQ
  15. aNzbzyyyaXP8XDBRDsvPL6fPxL4r6YHywfcPdBfTc71/cEPksG8ts6um8uAVYbLI
  16. DYcsWopjVZY/nUwsz49xBCyRcyPnlEUJedyF8HANfVEO2zlSyRshn/F+rrjD6aKB
  17. V/yVWfTEyTSxZrBPl4I4Tv89EG5CwuuGaSagxfQpAQKBgQDXEe7FqXSaGk9xzuPa
  18. zXy8okCX5pT6545EmqTP7/JtkMSBHh/xw8GPp+JfrEJEAJJl/ISbdsOAbU+9KAXu
  19. PmkicFKbodBtBa46wprGBQ8XkR4JQoBFj1SJf7Gj9ozmDycozO2Oy8a1QXKhHUPk
  20. bPQ0+w3efwoYdfE67ZodpFNhswKBgQDN9eaYrEL7YyD7951WiK0joq0BVBLK3rwO
  21. 5+4g9IEEQjhP8jSo1DP+zS495t5ruuuuPsIeodA79jI8Ty+lpYqqCGJTE6muqLMJ
  22. Diy7KlMpe0NZjXrdSh6edywSz3YMX1eAP5U31pLk0itMDTf2idGcZfrtxTLrpRff
  23. umowdJ5qqwKBgF+XZ+JRHDN2aEM0atAQr1WEZGNfqG4Qx4o0lfaaNs1+H+knw5kI
  24. ohrAyvwtK1LgUjGkWChlVCXb8CoqBODMupwFAqKL/IDImpUhc/t5uiiGZqxE85B3
  25. UWK/7+vppNyIdaZL13a1mf9sNI/p2whHaQ+3WoW/P3R5z5uaifqM1EbDAoGAN584
  26. JnUnJcLwrnuBx1PkBmKxfFFbPeSHPzNNsSK3ERJdKOINbKbaX+7DlT4bRVbWvVj/
  27. jcw/c2Ia0QTFpmOdnivjefIuehffOgvU8rsMeIBsgOvfiZGx0TP3+CCFDfRVqjIB
  28. t3HAfAFyZfiP64nuzOERslL2XINafjZW5T0pZz8CgYAJ3UbEMbKdvIuK+uTl54R1
  29. Vt6FO9T5bgtHR4luPKoBv1ttvSC6BlalgxA0Ts/AQ9tCsUK2JxisUcVgMjxBVvG0
  30. lfq/EHpL0Wmn59SHvNwtHU2qx3Ne6M0nQtneCCfR78OcnqQ7+L+3YCMqYGJHNFSa
  31. rd+dewfKoPnWw0WyGFEWCg==
  32. -----END PRIVATE KEY-----

PEM key as a resource location

  1. jasypt:
  2. encryptor:
  3. privateKeyFormat: PEM
  4. privateKeyLocation: classpath:private_key.pem

Encrypting properties

There is no program/command to encrypt properties using asymmetric keys but you can use the following code snippet to encrypt your properties:

DER Format

  1. import com.ulisesbocchio.jasyptspringboot.encryptor.SimpleAsymmetricConfig;
  2. import com.ulisesbocchio.jasyptspringboot.encryptor.SimpleAsymmetricStringEncryptor;
  3. import org.jasypt.encryption.StringEncryptor;
  4.  
  5. public class PropertyEncryptor {
  6. public static void main(String[] args) {
  7. SimpleAsymmetricConfig config = new SimpleAsymmetricConfig();
  8. config.setPublicKey("MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArQfyGCvBOdgmDGU6ciGPVNB6jHsMip0b0qOrPvVTSJ/x0offjKARogA2tjGjyr3rUtwg9woMBqv/iyENR0GBnIUa0jkYsznCKeygcflnNa4mrVf7XKXLhSwtY+kCe3diPk+0QPfEsfF9/aK6pWBUFcrE8P2k2sF/8mo8dFJU1t6zQGPspHkNAgR6MLU8SjPZxnMS6EG722MdYhvSYAKsnu02Hozqb4jh/gaQ/E6NkvM3DkqIyIYsRH2smstIFEb9CCiTdiz/OsJKQLgGy/pqIVKtai3lnUxAayEV45Z61rNTOusNJf+icGhZxjqhAeoWjMxOCVmVC2GKa9sisqBgkQIDAQAB");
  9. StringEncryptor encryptor = new SimpleAsymmetricStringEncryptor(config);
  10. String message = "chupacabras";
  11. String encrypted = encryptor.encrypt(message);
  12. System.out.printf("Encrypted message %s\n", encrypted);
  13. }
  14. }

PEM Format

  1. import com.ulisesbocchio.jasyptspringboot.encryptor.SimpleAsymmetricConfig;
  2. import com.ulisesbocchio.jasyptspringboot.encryptor.SimpleAsymmetricStringEncryptor;
  3. import org.jasypt.encryption.StringEncryptor;
  4. import static com.ulisesbocchio.jasyptspringboot.util.AsymmetricCryptography.KeyFormat.PEM;
  5.  
  6. public class PropertyEncryptor {
  7. public static void main(String[] args) {
  8. SimpleAsymmetricConfig config = new SimpleAsymmetricConfig();
  9. config.setKeyFormat(PEM);
  10. config.setPublicKey("-----BEGIN PUBLIC KEY-----\n" +
  11. "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArQfyGCvBOdgmDGU6ciGP\n" +
  12. "VNB6jHsMip0b0qOrPvVTSJ/x0offjKARogA2tjGjyr3rUtwg9woMBqv/iyENR0GB\n" +
  13. "nIUa0jkYsznCKeygcflnNa4mrVf7XKXLhSwtY+kCe3diPk+0QPfEsfF9/aK6pWBU\n" +
  14. "FcrE8P2k2sF/8mo8dFJU1t6zQGPspHkNAgR6MLU8SjPZxnMS6EG722MdYhvSYAKs\n" +
  15. "nu02Hozqb4jh/gaQ/E6NkvM3DkqIyIYsRH2smstIFEb9CCiTdiz/OsJKQLgGy/pq\n" +
  16. "IVKtai3lnUxAayEV45Z61rNTOusNJf+icGhZxjqhAeoWjMxOCVmVC2GKa9sisqBg\n" +
  17. "kQIDAQAB\n" +
  18. "-----END PUBLIC KEY-----\n");
  19. StringEncryptor encryptor = new SimpleAsymmetricStringEncryptor(config);
  20. String message = "chupacabras";
  21. String encrypted = encryptor.encrypt(message);
  22. System.out.printf("Encrypted message %s\n", encrypted);
  23. }
  24. }

Demo App

The jasypt-spring-boot-demo-samples repo contains working Spring Boot app examples. The main jasypt-spring-boot-demoDemo app explicitly sets a System property with the encryption password before the app runs. To have a little more realistic scenario try removing the line where the system property is set, build the app with maven, and the run:

  1. java -jar target/jasypt-spring-boot-demo-0.0.1-SNAPSHOT.jar --jasypt.encryptor.password=password

And you'll be passing the encryption password as a command line argument. Run it like this:

  1. java -Djasypt.encryptor.password=password -jar target/jasypt-spring-boot-demo-0.0.1-SNAPSHOT.jar

And you'll be passing the encryption password as a System property.

If you need to pass this property as an Environment Variable you can accomplish this by creating application.properties or application.yml and adding:

  1. jasypt.encryptor.password=${JASYPT_ENCRYPTOR_PASSWORD:}

or in YAML

  1. jasypt:
  2. encryptor:
  3. password: ${JASYPT_ENCRYPTOR_PASSWORD:}

basically what this does is to define the jasypt.encryptor.password property pointing to a different property JASYPT_ENCRYPTOR_PASSWORD that you can set with an Environment Variable, and you can also override via System Properties. This technique can also be used to translate property name/values for any other library you need. This is also available in the Demo app. So you can run the Demo app like this:

  1. JASYPT_ENCRYPTOR_PASSWORD=password java -jar target/jasypt-spring-boot-demo-1.5-SNAPSHOT.jar

Note: When using Gradle as build tool, processResources task fails because of '$' character, to solve this you just need to scape this variable like this '$'.

Other Demo Apps

While jasypt-spring-boot-demo is a comprehensive Demo that showcases all possible ways to encrypt/decrypt properties, there are other multiple Demos that demo isolated scenarios.

jasypt-spring-boot的更多相关文章

  1. Spring Boot集成Jasypt安全框架

    Jasypt安全框架提供了Spring的集成,主要是实现 PlaceholderConfigurerSupport类或者其子类. 在Sring 3.1之后,则推荐使用PropertySourcesPl ...

  2. spring boot + mybatis + hikaricp + swagger2 + jasypt

    好久没写博客了记录下写过的东西,别到时候又忘了 文章前提:前面开发项目的时候数据池一直用的阿里的druid,这个数据池吧也不能说它不好,为什么现在想改成hikaricp数据池呢,完全是实用项目需要.d ...

  3. 在spring boot中使用jasypt对配置文件中的敏感字符串加密

    在spring boot的配置文件application.property(application.yml)文件中常常配置一些密码类的字符,如果用明文则很容易被盗用,可以使用jasypt在配置密码的地 ...

  4. Spring Boot demo系列(九):Jasypt

    2021.2.24 更新 1 概述 Jasypt是一个加密库,Github上有一个集成了Jasypt的Spring Boot库,叫jasypt-spring-boot,本文演示了如何使用该库对配置文件 ...

  5. 3行代码快速实现Spring Boot Oauth2服务

    这里的3行代码并不是指真的只需要写3行代码,而是基于我已经写好的一个Spring Boot Oauth2服务.仅仅需要修改3行数据库配置信息,即可得到一个Spring Boot Oauth2服务. 项 ...

  6. Spring Boot开发Web应用

    静态资源访问 在我们开发Web应用的时候,需要引用大量的js.css.图片等静态资源. 默认配置 Spring Boot默认提供静态资源目录位置需置于classpath下,目录名需符合如下规则: /s ...

  7. spring boot 教程(二)模板依赖

    在Spring boot中有一个很重要的概念,叫做约定优于配置--软件开发的简约原则.所以Spring boot会按照约定好的文件位置去找我们的包和类. 默认配置 Spring Boot默认提供静态资 ...

  8. Spring Boot☞ 使用Thymeleaf模板引擎渲染web视图

    静态资源访问 在我们开发Web应用的时候,需要引用大量的js.css.图片等静态资源. 默认配置 Spring Boot默认提供静态资源目录位置需置于classpath下,目录名需符合如下规则: /s ...

  9. Spring Boot - 配置信息后处理

    最近在做项目的过程中,PSS提出配置文件中类似数据库连接需要的用户名.密码等敏感信息需要加密处理(之前一直是明文的). 为了快速完成任务,网上搜刮到jasypt包,也有相应的starter,使用方法可 ...

  10. Spring Boot: 加密应用配置文件敏感信息

    Spring Boot: 加密应用配置文件敏感信息 背景 我们的应用之前使用的是Druid数据库连接池,由于需求我们迁移到HikariCP连接池,druid 数据源加密提供了多种方式: 可以在配置文件 ...

随机推荐

  1. Unsafe API介绍及其使用

      废话 个人理解:java 出现的原因之一,就是对内存的管理:在c/c++,内存可以随心使用,超高的性能也伴有极高的风险:java极大的规避了这种风险,却也降低了程序运行的性能:那么java是否提供 ...

  2. 啊哈!算法(第一章)C#实现

    第1节 最简单的排序--桶排序     期末考试完了老师要将同学们的分数按照从高到低排序. 小哼的班上只有 5 个同学,这 5 个同学分别考了 5 分.3 分.5 分.2 分和 8 分,考得真是惨不忍 ...

  3. ASP.NET Core中如何显示[PII is hidden]的隐藏信息

    有时候我们在ASP.NET Core项目运行时,发生在后台程序中的错误会将关键信息隐藏为[PII is hidden]这种占位符,如下所示: 而知道这些关键信息,有时候对我们调试程序是非常重要的.所以 ...

  4. vue 封装公用函数

    Vue 函数封装 格式化浏览器时间 /** * 格式化时间 * @param params * @param blo 默认为true * @returns {string} * @constructo ...

  5. 单词CAEMENT水泥CAEMENT英文

    caement Archaic spelling of cement. caement Alternative forms caement (archaic) c?ment (archaic) Hyp ...

  6. android ListView中含有按钮事件实时更新ListView数据案例

    1.布局文件Listview <?xml version="1.0" encoding="utf-8"?> <android.support. ...

  7. Jnetpcap简述

    Jnetpcap简述 最近需要做一个本地网络流量分析的项目,基于 Java 语言,上网查了很多资料,最后利用 Jnetpcap 实现了,这里做个记录. 这里先列一下我用到的工具以及版本: Eclips ...

  8. Python小练习:批量删除多个文件夹内的相同文件

    应用场景: 下载的多个文件夹是压缩包,解压后每个文件夹都有某个网站的推广链接,想要批量的删除该文件 使用环境:win7,python3.6 代码: 1.直接用for循环 由于os.walk()方法自带 ...

  9. 大数据:Hadoop(JDK安装、HDFS伪分布式环境搭建、HDFS 的shell操作)

    所有的内容都来源与 Hadoop 官方文档 一.Hadoop 伪分布式安装步骤 1)JDK安装 解压:tar -zxvf jdk-7u79-linux-x64.tar.gz -C ~/app 添加到系 ...

  10. Django 之 rest_framework 分页器使用

    Django rest_framework 之分页器使用以及其源码分析 三种分页方式: 常规分页 -->PageNumberPagination 偏移分页 -->LimitOffsetPa ...