"Jasypt spring boot" a powerful tool for encryption and decryption of sensitive information

gh0stbadb0y 2021-04-16 17:47:32
jasypt spring boot powerful tool


[toc]

1. brief introduction

Springboot Integrate Jasypt, Realize the security of configuration information , Such as database connection . Account and password . Interface voucher information, etc .

Jasypt It can be for Springboot There's a lot of encrypted information , There are mainly :

  • System Property System variables
  • Envirnment Property environment variable
  • Command Line argument Command line arguments
  • Application.properties Application profile
  • Yaml properties Application profile
  • other custom property sources Other configuration files

2. How to integrate

following 3 Methods :

  1. If your Spring Boot Project use @SpringBootApplication or @EnableAutoConfiguration annotation , stay pom Add the following starter jar rely on .

    <dependency>
    <groupId>com.github.ulisesbocchio</groupId>
    <artifactId>jasypt-spring-boot-starter</artifactId>
    <version>3.0.3</version>
    </dependency>
    
  2. If you don't use @SpringBootApplication or @EnableAutoConfiguration Two auto configuration annotations , You can add the following dependencies :

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

    Then configure Java Class using annotations @EncryptablePropertySource. give an example :

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

    That is to say, for the whole Spring The configuration information of the environment is encrypted and decrypted ( Include :System Property System variables 、Envirnment Property environment variable 、Command Line argument Command line arguments 、Application.properties Application profile 、Yaml properties Application profile 、other custom property sources Other configuration files )

  3. If you don't use @SpringBootApplication or @EnableAutoConfiguration Two auto configuration annotations , I don't want to do anything to the whole spring The parameters of the environment are encrypted and decrypted , There's a second 3 Methods . First , Add the following dependencies to your project :

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

    then , stay Java Add... To the configuration class @EncryptablePropertySource annotation . It's like adding spring Of @PropertySource annotation . such as :

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

    It's very convenient , One Java You can add a @EncryptablePropertySources annotation , You can also add a set of @EncryptablePropertySources annotation , Just like this. :

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

​ in addition , It's important to note that from 1.8 Version start ,@EncryptablePropertySource Support YAML file .

3. Custom environment

From version 1.15 Start , Support the use of the second 4 There are two ways to enable encryption properties . Customize a ConfigurableEnvironment class , such as :EncryptableEnvironmentStandardEncryptableEnvironmentStandardEncryptableServletEnvironment, And SpringApplicationBuilder Class , Customize the usage environment in this way :

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

This method only needs to use jasypt-spring-boot Dependence . Unwanted starter jar Dependencies . This method is very useful for accessing encrypted properties during startup . Although not required in most scenarios , But in customization Spring Boot It can be useful to initialize the behavior of or integrate some of the capabilities of the initialization configuration ( Such as log configuration ). Take a specific example , stay logback-spring.xml In file , If we want to springProperty The properties of the tag enable encryption , It's the only way . for example :

<springProperty name="user" source="db.user"/>
<springProperty name="password" source="db.password"/>
<appender name="db" class="ch.qos.logback.classic.db.DBAppender">
<connectionSource
class="ch.qos.logback.core.db.DriverManagerConnectionSource">
<driverClass>org.postgresql.Driver</driverClass>
<url>jdbc:postgresql://localhost:5432/simple</url>
<user>${user}</user>
<password>${password}</password>
</connectionSource>
</appender>

This mechanism can be used to initialize the database log records that need to pass sensitive credentials Appender(Database Logging Appender). in addition , We need to provide a custom StringEncryptor, And a static builder method StandardEncryptableEnvironment#builder To operate :

StandardEncryptableEnvironment
.builder()
.encryptor(new MyEncryptor())
.build()

4. working principle

SpringBoot Enable jasypt Encryption and decryption configuration mechanism , I will do the following 2 thing :

  1. Sign up for a Spring post processor , The processor is decorated with Spring All that's contained in the environment PropertySource object , Make them have “ Encrypted ID ”, When the attribute follows jasypt When encrypting according to the contract of , Registered processors can detect .
  2. Defines a default StringEncryptor, You can use general properties 、 Configuration of system properties or command line parameters .

5. How to deal with encrypted properties

Using the integration approach mentioned above 1 And methods 2 when , Can be included in any spring The encrypted properties are defined in the configuration file of the environment . for example , Use @PropertySource notes :

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

then , The properties defined in the configuration file are defined with the following identity :

 secret.property=ENC(nrmZtkF7T0kjG/VodDvBw93Ct8EgjCA+)

Now? , When you use environment.getProperty("secret.property") Or use @Value("${secret.property}") when , What you get is secret.property Decrypted version of .

When using an integrated approach 3(@EncryptablePropertySource) when , The way to get encrypted properties is the same , The only difference is ,Java Configuration class to use @EncryptablePropertySource annotation .

6. Password based encryption configuration

Jasypt Use StringEncryptor Class to encrypt attribute resources . As mentioned above 3 Among the three integration methods , If Spring There is no custom... In the context StringEncryptor class , Will use Jasypt Default class , By configuring the attributes in the following table in the configuration file to play the role of encryption and decryption :

Configuration item Whether must The default value is
jasypt.encryptor.password True -
jasypt.encryptor.algorithm False PBEWITHHMACSHA512ANDAES_256
jasypt.encryptor.key-obtention-iterations False 1000
jasypt.encryptor.pool-size False 1
jasypt.encryptor.provider-name False SunJCE
jasypt.encryptor.provider-class-name False null
jasypt.encryptor.salt-generator-classname False org.jasypt.salt.RandomSaltGenerator
jasypt.encryptor.iv-generator-classname False org.jasypt.iv.RandomIvGenerator
jasypt.encryptor.string-output-type False base64
jasypt.encryptor.proxy-property-sources False false
jasypt.encryptor.skip-property-sources False empty list

The only required encryption property is the encryption password , The rest of the configuration items can use default values . Although all of these properties can be declared in the properties file , But the encryptor password should not be stored in the properties file , It should be a system property 、 Command line parameters or environment variables pass , As long as its name is ' jasypt.encryptor '.

The last attribute ,jasypt.encryptor.proxyPropertySources Used to identify jasypt -spring-boot How to intercept attribute values for decryption . The default value is false when , Use PropertySource EnumerablePropertySource and MapPropertySource Custom wrapper implementation . When you specify true when , The interception mechanism will be in every PropertySource Identification of the property class on the implementation of the use CGLib agent . The original must be preserved in the future “PropertySource” In some scenarios of this type , This may be useful .

7. Use a custom encryption program

When in spring Use custom... In context StringEncryptor Class time , The default encryptor will be ignored , We can customize the configuration , such as :

 @Bean("jasyptStringEncryptor")
public StringEncryptor stringEncryptor() {
PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();
SimpleStringPBEConfig config = new SimpleStringPBEConfig();
config.setPassword("password");
config.setAlgorithm("PBEWITHHMACSHA512ANDAES_256");
config.setKeyObtentionIterations("1000");
config.setPoolSize("1");
config.setProviderName("SunJCE");
config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator");
config.setIvGeneratorClassName("org.jasypt.iv.RandomIvGenerator");
config.setStringOutputType("base64");
encryptor.setConfig(config);
return encryptor;
}

Be careful , The class name of the encryptor is usually fixed , because jasypt-spring-boot from 1.5 Version start , It detects a custom string encryptor by name . The default class name is :

jasyptStringEncryptor

But it can be overridden by the following configuration items :

jasypt.encryptor.bean

for instance , If jasypt.encryptor.bean=encryptorBean , that , You can use encryptorBean This name defines the encryptor :

 @Bean("encryptorBean")
public StringEncryptor stringEncryptor() {
...
}

8. Customize Property Detector, Prefix, Suffix and Resolver

stay jasypt-spring-boot-1.10 There are new extensions in , Use EncryptablePropertyResolver To parse all the attributes :

public interface EncryptablePropertyResolver {
String resolvePropertyValue(String value);
}

8.1 Customize EncryptablePropertyDetector

Define a name as encryptablePropertyDetector Of Java class , Implement and rewrite EncryptablePropertyDetector Interface . You can also configure items through jasypt.encryptor.property.detector-bean Define your own Java The name of the class , And after that , The defined class is responsible for detecting the encryption properties , The following example :

private static class MyEncryptablePropertyDetector implements EncryptablePropertyDetector {
@Override
public boolean isEncrypted(String value) {
if (value != null) {
return value.startsWith("[email protected]");
}
return false;
}
@Override
public String unwrapEncryptedValue(String value) {
return value.substring("[email protected]".length());
}
}
@Bean(name = "encryptablePropertyDetector")
public EncryptablePropertyDetector encryptablePropertyDetector() {
return new MyEncryptablePropertyDetector();
}

8.2 Custom encryption attribute prefix and suffix

If you want to add different prefixes to encrypted attributes / suffix , All default implementations can continue to be used , It's just coverage application.properties ( or application.yml) The following properties in :

jasypt:
encryptor:
property:
prefix: "[email protected]["
suffix: "]"

8.3 Customize EncryptablePropertyResolver

Define a name as encryptablePropertyResolver Of Java class , Implement and rewrite EncryptablePropertyResolver Interface . You can also configure items through jasypt.encryptor.property.resolver-bean Define your own Java The name of the class , And after that , The defined class is responsible for detecting and decrypting the encrypted properties , The following example :

 class MyEncryptablePropertyResolver implements EncryptablePropertyResolver {
private final PooledPBEStringEncryptor encryptor;
public MyEncryptablePropertyResolver(char[] password) {
this.encryptor = new PooledPBEStringEncryptor();
SimpleStringPBEConfig config = new SimpleStringPBEConfig();
config.setPasswordCharArray(password);
config.setAlgorithm("PBEWITHHMACSHA512ANDAES_256");
config.setKeyObtentionIterations("1000");
config.setPoolSize(1);
config.setProviderName("SunJCE");
config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator");
config.setIvGeneratorClassName("org.jasypt.iv.RandomIvGenerator");
config.setStringOutputType("base64");
encryptor.setConfig(config);
}
@Override
public String resolvePropertyValue(String value) {
if (value != null && value.startsWith("{cipher}")) {
return encryptor.decrypt(value.substring("{cipher}".length()));
}
return value;
}
}
@Bean(name="encryptablePropertyResolver")
EncryptablePropertyResolver encryptablePropertyResolver(@Value("${jasypt.encryptor.password}") String password) {
return new MyEncryptablePropertyResolver(password.toCharArray());
}

Be careful , By covering EncryptablePropertyResolver, Modifying any other configuration may have a custom prefix , suffix , that EncryptablePropertyDetector and StringEncryptor Will stop parsing detection , Because they are used by the default parser . You need to assemble these configuration items yourself . Fortunately, , In most cases, you don't have to rewrite this bean, The default configuration options should be enough .

however , As you can see in this example , For the detection and decryption of encrypted attributes, the work is custom MyEncryptablePropertyResolver Class .

9. Use filters

jasypt-spring-boot:2.1.0 A new feature is introduced to specify attribute filters . This filter is EncryptablePropertyResolverAPI Part of , Allows you to specify which properties to decrypt . This work is done before checking the search or trying to decrypt the actual property value . for example , By default , All names with jasypt The properties of the beginning . Out of the scope of the inspection .

9.1 DefaultPropertyFilter Attributes of a class

By default ,DefaultPropertyResolver Use DefaultPropertyFilter, Allows you to specify string patterns in the following list :

  • jasypt.encryptor.property.filter.include-sources: Specifies the attribute source name pattern to include for decryption
  • jasypt.encryptor.property.filter.exclude-sources: Specifies the attribute source name pattern to exclude for decryption
  • jasypt.encryptor.property.filter.include-names: Specifies the property name pattern to include for decryption
  • jasypt.encryptor.property.filter.exclude-names: Specifies the attribute name pattern to exclude for decryption

9.2 Customize EncryptablePropertyFilter

By defining the name encryptablePropertyFilter , The type is EncryptablePropertyFilter Of Bean To override the default implementation , Or if you define your own Bean name , Then override the property jasypt.encryptor.property.filter-bean. Then designate bean The name of . In doing so , You will be responsible for detecting the properties used for decryption and / Or attribute source . Example :

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

Be careful , If custom EncryptablePropertyFilter, Then there should be no custom EncryptablePropertyResolver, Instead, use the default parser . If you provide a custom parser , You need to be responsible for the entire process of detecting and decrypting attributes .

10. Filtering doesn't require encryption / Decrypted property class

Define an attribute named jasypt.encryptor.skip-property-sources, Property values are a comma separated list of fully qualified class names , These classes will be skipped from the loading process . And will not be packaged by this plug-in / agent , So the properties contained in it will not be encrypted / Decrypt :

jasypt.encryptor.skip-property-sources=org.springframework.boot.env.RandomValuePropertySource,org.springframework.boot.ansi.AnsiPropertySource

11. Maven The plug-in USES

Maven Plug ins provide many useful utilities , To use this plug-in , Just add the following to your pom.xml in :

<build>
<plugins>
<plugin>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-maven-plugin</artifactId>
<version>3.0.3</version>
</plugin>
</plugins>
</build>

When using this plug-in , The simplest way is to provide your encrypted password through a system property , namely -Djasypt.encryptor.password=" Custom password ".

By default , The plug-in will be in ./src/main/resources Under the standard of Spring Detect encryption configuration in startup configuration file . You can also use system properties or environment variables to provide this configuration . Be careful , The rest of the application code and resources are not available for plug-ins , because Maven The plug-in does not share the classpath with the project . If the application passes StringEncryptor bean Provide encryption configuration , Then it won't work , Generally speaking , It is recommended to rely only on the default configuration .

11.1 Encryption

Encrypt a single value :

mvn jasypt:encrypt-value -Djasypt.encryptor.password="the password" -Djasypt.plugin.value="theValueYouWantToEncrypt"

stay src/main/resources/application.properties In profile , use DEC(...) Anything enclosed by the logo can be encrypted , Including Spaces . Example :

sensitive.password=DEC(secret value)
regular.property=example

And then run the command :

mvn jasypt:encrypt -Djasypt.encryptor.password="the password"

The file encryption results will be shown in the following form :

sensitive.password=ENC(encrypted)
regular.property=example

You can customize the profile name and location .

11.2 Decryption

Decrypt a single value , Run the following command :

mvn jasypt:decrypt-value -Djasypt.encryptor.password="the password" -Djasypt.plugin.value="DbG1GppXOsFa2G69PnmADvQFI3esceEhJYbaEIKCcEO5C85JEqGAhfcjFMGnoRFf"

stay src/main/resources/application.properties In profile , use ENC(...) Anything enclosed by the logo can be decrypted , Including Spaces . Example :

sensitive.password=ENC(encrypted)
regular.property=example

Decryption will be achieved by the following command :

mvn jasypt:decrypt -Djasypt.encryptor.password="the password"

The decrypted content will be output to the screen :

sensitive.password=DEC(decrypted)
regular.property=example

Be careful , Output data to the screen , Instead of re editing the file in the right place , To reduce the chance of accidentally submitting decrypted values to version control . When decrypting , You probably just want to check the encrypted values , Instead of permanently decrypting the value .

11.3 Re-encryption

Use encryption / It's a bit difficult for decryption target to change the configuration of existing encryption properties . The decryption target must be run with the old configuration , Then copy the decrypted output back to the original file , Finally, run the encryption target with the new configuration .

The goal of re encryption is achieved by re encrypting the file in place . But it has to provide 2 Set configuration , Provide new configuration methods and other configurations maven The goal is the same way . The old configuration was through the belt "jasypt.plugin " The system properties of the prefix provide .

for example , Before re encrypting the application , It should be encrypted first with the old password , And then encrypt it with a new password :

mvn jasypt:reencrypt -Djasypt.plugin.old.password=OLD -Djasypt.encryptor.password=NEW

Be careful : All old configurations must be passed as system properties . Environment variables and Spring Boot profile .

11.4 Upgrade

Sometimes , The default encryption configuration may be in jasypt-spring-boot Changes between different versions of . You can automatically upgrade the encrypted properties to the new default values according to the upgrade target . This will decrypt your application . The properties file uses the old default configuration , And re encrypt with the new default configuration .

mvn jasypt:upgrade -Djasypt.encryptor.password=EXAMPLE

11.5 Load

When you want to make encrypted properties available to other Maven When plug-ins are available , You can load all the properties in the properties file into memory , send Maven They can be accessed .

You can connect the target of other plug-ins directly to this plug-in . for example , Use flyway:

mvn jasypt:load flyway:migrate -Djasypt.encryptor.password="the password"

You can also use it -Djasypt.plugin.keyPrefix=example. Specify a prefix for each attribute . This helps to avoid conflicts with other Maven There is a potential conflict between attributes .

11.6 Encrypt and change the property file path

For all of the above , To encrypt / The path of the decrypted file is file:src/main/resources/application.properties,

Relatively speaking , We can use -Djasypt.plugin.path To specify the file path , And there are other features , as follows :

Can encrypt test resources Files in directory

mvn jasypt:encrypt -Djasypt.plugin.path="file:src/main/test/application.properties" -Djasypt.encryptor.password="the password"

You can also encrypt non application.properties Name of the configuration file :

mvn jasypt:encrypt -Djasypt.plugin.path="file:src/main/resources/flyway.properties" -Djasypt.encryptor.password="the password"

Also supports .yaml Format of the configuration file :

mvn jasypt:encrypt -Djasypt.plugin.path="file:src/main/resources/application.yaml" -Djasypt.encryptor.password="the password"

Be careful load The module only supports .property File format

11.7 encryption Spring Properties file

When you run this plug-in , You can override any... That you support in your application spring To configure , For example, choose a given spring The configuration file :

mvn jasypt:encrypt -Dspring.profiles.active=cloud -Djasypt.encryptor.password="the password"

12. Asymmetric encryption

jasypt-spring-boot:2.1.1 Introduced a new feature , Use a pair of DER or PEM Format of the private key / Public key asymmetric encryption encrypts attributes / Decrypt .

12.1 Configuration properties

Here are the configuration properties that can be used to configure asymmetric decryption of properties ;

Property name The default value is describe
jasypt.encryptor.privateKeyString null Private key in string format for decryption
jasypt.encryptor.privateKeyLocation null Used to spring The location of the private key decrypted by the resource format
jasypt.encryptor.privateKeyFormat DER Secret key encoding format DER perhaps PEM

You can use strings or secret key paths to define key, If you define the secret key directly in string format , First of all base64 code

Be careful With jasypt.encryptor.password Mode configuration encryption takes precedence over asymmetric encryption configuration

12.2 Configure the instance

12.2.1 Configure... In string format DER The secret key to coding

jasypt:
encryptor:
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==

12.2.2 Configuration item assignment DER Encoded secret key file path

jasypt:
encryptor:
privateKeyLocation: classpath:private_key.der

12.2.3 Configure... In string format PEM The secret key to coding

jasypt:
encryptor:
privateKeyFormat: PEM
privateKeyString: |-
-----BEGIN PRIVATE KEY-----
MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCtB/IYK8E52CYM
ZTpyIY9U0HqMewyKnRvSo6s+9VNIn/HSh9+MoBGiADa2MaPKvetS3CD3CgwGq/+L
IQ1HQYGchRrSORizOcIp7KBx+Wc1riatV/tcpcuFLC1j6QJ7d2I+T7RA98Sx8X39
orqlYFQVysTw/aTawX/yajx0UlTW3rNAY+ykeQ0CBHowtTxKM9nGcxLoQbvbYx1i
G9JgAqye7TYejOpviOH+BpD8To2S8zcOSojIhixEfayay0gURv0IKJN2LP86wkpA
uAbL+mohUq1qLeWdTEBrIRXjlnrWs1M66w0l/6JwaFnGOqEB6haMzE4JWZULYYpr
2yKyoGCRAgMBAAECggEAQxURhs1v3D0wgx27ywO3zeoFmPEbq6G9Z6yMd5wk7cMU
vcpvoNVuAKCUlY4pMjDvSvCM1znN78g/CnGF9FoxJb106Iu6R8HcxOQ4T/ehS+54
kDvL999PSBIYhuOPUs62B/Jer9FfMJ2veuXb9sGh19EFCWlMwILEV/dX+MDyo1qQ
aNzbzyyyaXP8XDBRDsvPL6fPxL4r6YHywfcPdBfTc71/cEPksG8ts6um8uAVYbLI
DYcsWopjVZY/nUwsz49xBCyRcyPnlEUJedyF8HANfVEO2zlSyRshn/F+rrjD6aKB
V/yVWfTEyTSxZrBPl4I4Tv89EG5CwuuGaSagxfQpAQKBgQDXEe7FqXSaGk9xzuPa
zXy8okCX5pT6545EmqTP7/JtkMSBHh/xw8GPp+JfrEJEAJJl/ISbdsOAbU+9KAXu
PmkicFKbodBtBa46wprGBQ8XkR4JQoBFj1SJf7Gj9ozmDycozO2Oy8a1QXKhHUPk
bPQ0+w3efwoYdfE67ZodpFNhswKBgQDN9eaYrEL7YyD7951WiK0joq0BVBLK3rwO
5+4g9IEEQjhP8jSo1DP+zS495t5ruuuuPsIeodA79jI8Ty+lpYqqCGJTE6muqLMJ
Diy7KlMpe0NZjXrdSh6edywSz3YMX1eAP5U31pLk0itMDTf2idGcZfrtxTLrpRff
umowdJ5qqwKBgF+XZ+JRHDN2aEM0atAQr1WEZGNfqG4Qx4o0lfaaNs1+H+knw5kI
ohrAyvwtK1LgUjGkWChlVCXb8CoqBODMupwFAqKL/IDImpUhc/t5uiiGZqxE85B3
UWK/7+vppNyIdaZL13a1mf9sNI/p2whHaQ+3WoW/P3R5z5uaifqM1EbDAoGAN584
JnUnJcLwrnuBx1PkBmKxfFFbPeSHPzNNsSK3ERJdKOINbKbaX+7DlT4bRVbWvVj/
jcw/c2Ia0QTFpmOdnivjefIuehffOgvU8rsMeIBsgOvfiZGx0TP3+CCFDfRVqjIB
t3HAfAFyZfiP64nuzOERslL2XINafjZW5T0pZz8CgYAJ3UbEMbKdvIuK+uTl54R1
Vt6FO9T5bgtHR4luPKoBv1ttvSC6BlalgxA0Ts/AQ9tCsUK2JxisUcVgMjxBVvG0
lfq/EHpL0Wmn59SHvNwtHU2qx3Ne6M0nQtneCCfR78OcnqQ7+L+3YCMqYGJHNFSa
rd+dewfKoPnWw0WyGFEWCg==
-----END PRIVATE KEY-----

12.2.4 Configuration item assignment PEM Encoded secret key file path

jasypt:
encryptor:
privateKeyFormat: PEM
privateKeyLocation: classpath:private_key.pem

12.3 Java Code encryption properties

12.3.1 DER Format

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

12.3.2 PEM Format

import com.ulisesbocchio.jasyptspringboot.encryptor.SimpleAsymmetricConfig;
import com.ulisesbocchio.jasyptspringboot.encryptor.SimpleAsymmetricStringEncryptor;
import org.jasypt.encryption.StringEncryptor;
import static com.ulisesbocchio.jasyptspringboot.util.AsymmetricCryptography.KeyFormat.PEM;
public class PropertyEncryptor {
public static void main(String[] args) {
SimpleAsymmetricConfig config = new SimpleAsymmetricConfig();
config.setKeyFormat(PEM);
config.setPublicKey("-----BEGIN PUBLIC KEY-----\n" +
"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArQfyGCvBOdgmDGU6ciGP\n" +
"VNB6jHsMip0b0qOrPvVTSJ/x0offjKARogA2tjGjyr3rUtwg9woMBqv/iyENR0GB\n" +
"nIUa0jkYsznCKeygcflnNa4mrVf7XKXLhSwtY+kCe3diPk+0QPfEsfF9/aK6pWBU\n" +
"FcrE8P2k2sF/8mo8dFJU1t6zQGPspHkNAgR6MLU8SjPZxnMS6EG722MdYhvSYAKs\n" +
"nu02Hozqb4jh/gaQ/E6NkvM3DkqIyIYsRH2smstIFEb9CCiTdiz/OsJKQLgGy/pq\n" +
"IVKtai3lnUxAayEV45Z61rNTOusNJf+icGhZxjqhAeoWjMxOCVmVC2GKa9sisqBg\n" +
"kQIDAQAB\n" +
"-----END PUBLIC KEY-----\n");
StringEncryptor encryptor = new SimpleAsymmetricStringEncryptor(config);
String message = "chupacabras";
String encrypted = encryptor.encrypt(message);
System.out.printf("Encrypted message %s\n", encrypted);
}
}

13.Demo App

jasypt-spring-boot-demo-samples The warehouse contains Spring Boot Examples of applications . The main jasypt-spring-boot-demo The application explicitly sets a system property with an encrypted password before it runs . In order to have a more realistic scene , Suggest trying to remove the settings system Property line , use maven Building the application , And then run :

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

Pass the encrypted password as a command line parameter :

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

You can also create application.properties perhaps application.yml file , And add the following configuration items :

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

Definition jasypt.encryptor.password Attributes are the basic approach , You can also point to another property JASYPT_ENCRYPTOR_PASSWORD, It can be set by environment variable , You can also override it through system properties . This approach can also be used to translate property names for any other library you need / value ,demo It's also involved in :

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

** Be careful :** When using Gradle As a build tool ,processResources The mission will be because $ Character and failed , To solve this problem , Need to replace $ Such a variable .

14. Other demo app

jasypt-spring-boot-demo It's a comprehensive demonstration demo, It shows encryption / All possible ways to decrypt properties , But there are many others demo Demonstrates the usage scenarios of independent features .

15. Reference resources

Translated from :jasypt-spring-boot.README.md

版权声明
本文为[gh0stbadb0y]所创,转载请带上原文链接,感谢
https://javamana.com/2021/04/20210416155610755L.html

  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云