jasypt-spring-boot
運行
運行時配置解密秘鑰
-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 inapplication.propertiesfile. Maybe you are connecting to a database and you have to write your database password inapplication.properties. In this tutorial, I am going to useJasyptlibrary 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 mypom.xml
<!-- https://mvnrepository.com/artifact/com.github.ulisesbocchio/jasypt-spring-boot-starter -->
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>2.0.0</version>
</dependency>
In theapplication.properties(or yaml), we will write our encrypted properties between parenthesis and putENCkeyword before it. Like;
MyProperty=ENC(23ClLWiedLx8v6XT6Wk+Bg==)
How to generate those encrpyted values? We will useJasyptfor that! Go tohttp://www.jasypt.org/and download the latest version. When you are done, go intojasyptinand use theencrypt.shorencrypt.batto 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@EnableConfigurationPropertiesannotation to our application andjasyptwill 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
publicclassJasyptExampleApplication{
publicstaticvoidmain(String[]args){
SpringApplication.run(JasyptExampleApplication.class, args);
}
@Component
publicclassMyRunnerimplementsCommandLineRunner{
@Value("${myProperty}")
privateStringmyProperty;
@Override
publicvoidrun(String...args)throwsException{
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 inapplication.propertiesbut 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-2514:03:26.413INFO10028---[main]c.u.j.EncryptablePropertySourceConverter:Converting PropertySource configurationProperties[org.springframework.boot.context.properties.source.ConfigurationPropertySourcesPropertySource]to AOPProxy
2018-04-2514:03:26.413INFO10028---[main]c.u.j.EncryptablePropertySourceConverter:Converting PropertySource commandLineArgs[org.springframework.core.env.SimpleCommandLinePropertySource]to EncryptableEnumerablePropertySourceWrapper
2018-04-2514:03:26.414INFO10028---[main]c.u.j.EncryptablePropertySourceConverter:Converting PropertySource systemProperties[org.springframework.core.env.MapPropertySource]to EncryptableMapPropertySourceWrapper
2018-04-2514:03:26.414INFO10028---[main]c.u.j.EncryptablePropertySourceConverter:Converting PropertySource systemEnvironment[org.springframework.boot.env.SystemEnvironmentPropertySourceEnvironmentPostProcessor$OriginAwareSystemEnvironmentPropertySource]to EncryptableMapPropertySourceWrapper
2018-04-2514:03:26.414INFO10028---[main]c.u.j.EncryptablePropertySourceConverter:Converting PropertySource random[org.springframework.boot.env.RandomValuePropertySource]to EncryptablePropertySourceWrapper
2018-04-2514:03:26.415INFO10028---[main]c.u.j.EncryptablePropertySourceConverter:Converting PropertySource applicationConfig:[classpath:/application.properties][org.springframework.boot.env.OriginTrackedMapPropertySource]to EncryptableMapPropertySourceWrapper
2018-04-2514:03:26.468INFO10028---[main]c.u.j.r.DefaultLazyPropertyResolver:PropertyResolvercustom Bean not found with name'encryptablePropertyResolver'.InitializingDefaultPropertyResolver
2018-04-2514:03:26.470INFO10028---[main]c.u.j.d.DefaultLazyPropertyDetector:Property Detector custom Bean not found with name'encryptablePropertyDetector'.InitializingDefaultProperty Detector
2018-04-2514:03:26.472INFO10028---[main]c.u.j.encryptor.DefaultLazyEncryptor:StringEncryptor custom Bean not found with name'jasyptStringEncryptor'.InitializingDefaultStringEncryptor
2018-04-2514:03:26.478INFO10028---[main]c.u.j.encryptor.DefaultLazyEncryptor:Encryptor config not foundforproperty jasypt.encryptor.algorithm, usingdefaultvalue:PBEWithMD5AndDES
2018-04-2514:03:26.479INFO10028---[main]c.u.j.encryptor.DefaultLazyEncryptor:Encryptor config not foundforproperty jasypt.encryptor.keyObtentionIterations, usingdefaultvalue:1000
2018-04-2514:03:26.479INFO10028---[main]c.u.j.encryptor.DefaultLazyEncryptor:Encryptor config not foundforproperty jasypt.encryptor.poolSize, usingdefaultvalue:1
2018-04-2514:03:26.479INFO10028---[main]c.u.j.encryptor.DefaultLazyEncryptor:Encryptor config not foundforproperty jasypt.encryptor.providerName, usingdefaultvalue:null
2018-04-2514:03:26.479INFO10028---[main]c.u.j.encryptor.DefaultLazyEncryptor:Encryptor config not foundforproperty jasypt.encryptor.providerClassName, usingdefaultvalue:null
2018-04-2514:03:26.479INFO10028---[main]c.u.j.encryptor.DefaultLazyEncryptor:Encryptor config not foundforproperty jasypt.encryptor.saltGeneratorClassname, usingdefaultvalue:org.jasypt.salt.RandomSaltGenerator
2018-04-2514:03:26.480INFO10028---[main]c.u.j.encryptor.DefaultLazyEncryptor:Encryptor config not foundforproperty jasypt.encryptor.stringOutputType, usingdefaultvalue:base64
2018-04-2514:03:26.934INFO10028---[main]o.s.j.e.a.AnnotationMBeanExporter:Registering beansforJMX exposure on startup
2018-04-2514:03:26.948INFO10028---[main]demo.JasyptExampleApplication:Started JasyptExampleApplication in1.264seconds(JVM runningfor2.06)
My property is MBcoder
As you can see it picked up thePBEWithMD5AndDESalgorithm 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
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>2.0.0</version>
</dependency>
生成要加密的字符串
將數據庫的用戶名和密碼進行加密
public static void main(String[] args) {
BasicTextEncryptor textEncryptor = new BasicTextEncryptor();
//加密所需的salt(鹽)
textEncryptor.setPassword("G0CvDz7oJn6");
//要加密的數據(數據庫的用戶名或密碼)
String username = textEncryptor.encrypt("root");
String password = textEncryptor.encrypt("root123");
System.out.println("username:"+username);
System.out.println("password:"+password);
}
輸出信息為:
username:i8QgEN4uOy2E1rHzrpSTYA==
password:6eaMh/RX5oXUVca9ignvtg==
或者使用Maven下載好的jar包加密Mavenorgjasyptjasypt1.9.2jasypt-1.9.2.jar
java -cp jasypt-1.9.2.jar org.jasypt.intf.cli.JasyptPBEStringEncryptionCLI password=G0CvDz7oJn6 algorithm=PBEWithMD5AndDES input=root
輸出信息為:
----ENVIRONMENT-----------------
Runtime: Oracle Corporation Java HotSpot(TM) 64-Bit Server VM 25.171-b11
----ARGUMENTS-------------------
input: root
algorithm: PBEWithMD5AndDES
password: G0CvDz7oJn6
----OUTPUT----------------------
Gvkoz+sbFWiRe3ECtizV1A==
拷貝-OUTPUT-下的結果即可
配置properties文件
將生成的加密串配置ENC(加密串)到application.properties中
# 加密所需的salt(鹽)
jasypt.encryptor.password=G0CvDz7oJn6
# 默認加密方式PBEWithMD5AndDES,可以更改為PBEWithMD5AndTripleDES
# jasypt.encryptor.algorithm=PBEWithMD5AndDES
spring.datasource.username=ENC(6eaMh/RX5oXUVca9ignvtg==)
spring.datasource.password=ENC(6eaMh/RX5oXUVca9ignvtg==)
加密方式對應的類為BasicTextEncryptor和StrongTextEncryptor
public BasicTextEncryptor() {
super();
this.encryptor = new StandardPBEStringEncryptor();
this.encryptor.setAlgorithm("PBEWithMD5AndDES");
}
public StrongTextEncryptor() {
super();
this.encryptor = new StandardPBEStringEncryptor();
this.encryptor.setAlgorithm("PBEWithMD5AndTripleDES");
}
類圖
部署時配置salt(鹽)值
為了防止salt(鹽)泄露,反解出密碼.可以在項目部署的時候使用命令傳入salt(鹽)值
java -jar -Djasypt.encryptor.password=G0CvDz7oJn6 xxx.jar
或者在服務器的環境變量里配置,進一步提高安全性
打開/etc/profile文件
vim /etc/profile
文件末尾插入
export JASYPT_PASSWORD = G0CvDz7oJn6
編譯
source /etc/profile
運行
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 integratejasypt-spring-bootin your project:
Simply adding the starter jarjasypt-spring-boot-starterto your classpath if using@SpringBootApplicationor@EnableAutoConfigurationwill enable encryptable properties across the entire Spring Environment
Addingjasypt-spring-bootto your classpath and adding@EnableEncryptablePropertiesto your main Configuration class to enable encryptable properties across the entire Spring Environment
Addingjasypt-spring-bootto your classpath and declaring individual encryptable property sources with@EncrytablePropertySource
What's new?
Update 1/8/2019: Version 2.1.1 Release IncludingAsymmetric Encryption
and support for JSB96 with IV Generators (Thanks@melloware!!)
Update 7/17/2018: Version 2.1.0 Release IncludingFilters
Update 3/17/2018: Version 2.0.0 has been released supporting Spring Boot 2.0.X.RELEASE.SemVeradopted.
Update 7/18/2015:jasypt-spring-bootis now in Maven Central!
What to do First?
Use one of the following 3 methods (briefly explained above):
Simply add the starter jar dependency to your project if your Spring Boot application uses@SpringBootApplicationor@EnableAutoConfigurationand 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):
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
IF you don't use@SpringBootApplicationor@EnableAutoConfigurationAuto Configuration annotations then add this dependency to your project:
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot</artifactId>
<version>2.1.1</version>
</dependency>
And then add@EnableEncryptablePropertiesto you Configuration class. For instance:
@Configuration
@EnableEncryptableProperties
public class MyApplication {
...
}
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)
IF you don't use@SpringBootApplicationor@EnableAutoConfigurationAuto 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:
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot</artifactId>
<version>2.0.0</version>
</dependency>
And then add as many@EncryptablePropertySourceannotations as you want in your Configuration files. Just like you do with Spring's@PropertySourceannotation. For instance:
@Configuration
@EncryptablePropertySource(name = "EncryptedProperties", value = "classpath:encrypted.properties")
public class MyApplication {
...
}
Conveniently, there's also a@EncryptablePropertySourcesannotation that one could use to group annotations of type@EncryptablePropertySourcelike this:
@Configuration
@EncryptablePropertySources({@EncryptablePropertySource("classpath:encrypted.properties"),
@EncryptablePropertySource("classpath:encrypted2.properties")})
public class MyApplication {
...
}
Also, note that as of version 1.8,@EncryptablePropertySourcesupports YAML files
Custom Environment
As of version1.71.15, a 4th method of enabling encryptable properties exists for some special cases. A customConfigurableEnvironmentclass is provided:EncryptableEnvironmentStandardEncryptableEnvironmentandStandardEncryptableServletEnvironmentthat can be used withSpringApplicationBuilderto define the custom environment this way:
new SpringApplicationBuilder()
.environment(new StandardEncryptableEnvironment())
.sources(YourApplicationClass.class).run(args);
This method would only require using a dependency forjasypt-spring-boot.Notice that. 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 inEncryptableEnvironmentis just a wrapper, so you have to provide the actual Environment implementation, in this caseStandardServletEnvironmentlogback-spring.xmlfiles, using thespringPropertytag. For instance:
<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 could be used for instance (as shown) to initialize Database Logging Appender that require sensitive credentials to be passed. Alternatively, if a customStringEncryptoris needed to be provided, a second constructorEncryptableEnvironment(ConfigurableEnvironment, StringEncryptor)is available for that purpose.
How everything Works?
This will trigger some configuration to be loaded that basically does 2 things:
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.
It defines a defaultStringEncryptorthat 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:
@SpringBootApplication
@EnableEncryptableProperties
@PropertySource(name="EncryptedProperties", value = "classpath:encrypted.properties")
public class MyApplication {
...
}
And your encrypted.properties file would look something like this:
secret.property=ENC(nrmZtkF7T0kjG/VodDvBw93Ct8EgjCA+)
Now when you doenvironment.getProperty("secret.property")or use@Value("${secret.property}")what you get is the decrypted version ofsecret.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 anStringEncryptorto decrypt properties. For all 3 methods, if no customStringEncryptor(see theCustom Encryptorsection 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 isjasypt.encryptor.passwordit'll work.
The last property,jasypt.encryptor.proxyPropertySourcesis used to indicatejasyp-spring-boothow property values are going to be intercepted for decryption. The default value,falseuses custom wrapper implementations ofPropertySource,EnumerablePropertySource, andMapPropertySource. Whentrueis specified for this property, the interception mechanism will use CGLib proxies on each specificPropertySourceimplementation. This may be useful on some scenarios where the type of the originalPropertySourcemust be preserved.
The propertyjasypt.encryptor.ivGeneratorClassnamedefaults 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 toorg.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:
@Bean("jasyptStringEncryptor")
public StringEncryptor stringEncryptor() {
PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();
SimpleStringPBEConfig config = new SimpleStringPBEConfig();
config.setPassword("password");
config.setAlgorithm("PBEWithMD5AndDES");
config.setKeyObtentionIterations("1000");
config.setPoolSize("1");
config.setProviderName("SunJCE");
config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator");
config.setIvGeneratorClassName("org.jasypt.salt.NoOpIVGenerator");
config.setStringOutputType("base64");
encryptor.setConfig(config);
return encryptor;
}
Notice that the bean name is required, asjasypt-spring-bootdetects custom String Encyptors by name as of version1.5. The default bean name is:
jasyptStringEncryptor
But one can also override this by defining property:
jasypt.encryptor.bean
So for instance, if you definejasypt.encryptor.bean=encryptorBeanthen you would define your custom encryptor with that name:
@Bean("encryptorBean")
public StringEncryptor stringEncryptor() {
...
}
Custom Property Detector, Prefix, Suffix and/or Resolver
As ofjasypt-spring-boot-1.10there are new extensions points.EncryptablePropertySourcenow usesEncryptablePropertyResolverto resolve all properties:
public interface EncryptablePropertyResolver {
String resolvePropertyValue(String value);
}
Implementations of this interface are responsible of bothdetectinganddecryptingproperties. The default implementation,DefaultPropertyResolveruses the before mentionedStringEncryptorand a newEncryptablePropertyDetector.
Provide a CustomEncryptablePropertyDetector
You can override the default implementation by providing a Bean of typeEncryptablePropertyDetectorwith nameencryptablePropertyDetectoror if you wanna provide your own bean name, override propertyjasypt.encryptor.property.detector-beanand specify the name you wanna give the bean. When providing this, you'll be responsible for detecting encrypted properties. Example:
private static class MyEncryptablePropertyDetector implements EncryptablePropertyDetector {
@Override
public boolean isEncrypted(String value) {
if (value != null) {
return value.startsWith("ENC@");
}
return false;
}
@Override
public String unwrapEncryptedValue(String value) {
return value.substring("ENC@".length());
}
}
@Bean(name = "encryptablePropertyDetector")
public EncryptablePropertyDetector encryptablePropertyDetector() {
return new MyEncryptablePropertyDetector();
}
Provide a Custom Encrypted Propertyprefixandsuffix
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 inapplication.properties(orapplication.yml):
jasypt:
encryptor:
property:
prefix: "ENC@["
suffix: "]"
Provide a CustomEncryptablePropertyResolver
You can override the default implementation by providing a Bean of typeEncryptablePropertyResolverwith nameencryptablePropertyResolveror if you wanna provide your own bean name, override propertyjasypt.encryptor.property.resolver-beanand specify the name you wanna give the bean. When providing this, you'll be responsible for detecting and decrypting encrypted properties. 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("PBEWithMD5AndDES");
config.setKeyObtentionIterations("1000");
config.setPoolSize(1);
config.setProviderName("SunJCE");
config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator");
config.setIvGeneratorClassName("org.jasypt.salt.NoOpIVGenerator");
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());
}
Notice that by overridingEncryptablePropertyResolver, any other configuration or overrides you may have for prefixes, suffixes,EncryptablePropertyDetectorandStringEncryptorwill 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 toMyEncryptablePropertyResolver
Using Filters
jasypt-spring-boot:2.1.0introduces a new feature to specify property filters. The filter is part of theEncryptablePropertyResolverAPI 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 withjasypt.encryptorare excluded from examination. This is to avoid circular dependencies at load time when the library beans are configured.
DefaultPropertyFilter properties
By default, theDefaultPropertyResolverusesDefaultPropertyFilter, 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 customEncryptablePropertyFilter
You can override the default implementation by providing a Bean of typeEncryptablePropertyFilterwith nameencryptablePropertyFilteror if you wanna provide your own bean name, override propertyjasypt.encryptor.property.filter-beanand 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:
class MyEncryptablePropertyFilter implements EncryptablePropertyFilter {
public boolean shouldInclude(PropertySource<?> source, String name) {
return name.startsWith('encrypted.');
}
}
@Bean(name="encryptablePropertyFilter")
EncryptablePropertyFilter encryptablePropertyFilter() {
return new MyEncryptablePropertyFilter();
}
Notice that for this mechanism to work, you should not provide a customEncryptablePropertyResolverand 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.1introduces 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 useprivateKeyStringorprivateKeyLocation, the String format takes precedence if set. To specify a private key in DER format withprivateKeyString, please encode the key bytes tobase64.
Notethatjasypt.encryptor.passwordstill takes precedences for PBE encryption over the asymmetric config.
Sample config
DER key as string
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==
DER key as a resource location
jasypt:
encryptor:
privateKeyLocation: classpath:private_key.der
PEM key as string
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-----
PEM key as a resource location
jasypt:
encryptor:
privateKeyFormat: PEM
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
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
", encrypted);
}
}
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-----
" +
"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArQfyGCvBOdgmDGU6ciGP
" +
"VNB6jHsMip0b0qOrPvVTSJ/x0offjKARogA2tjGjyr3rUtwg9woMBqv/iyENR0GB
" +
"nIUa0jkYsznCKeygcflnNa4mrVf7XKXLhSwtY+kCe3diPk+0QPfEsfF9/aK6pWBU
" +
"FcrE8P2k2sF/8mo8dFJU1t6zQGPspHkNAgR6MLU8SjPZxnMS6EG722MdYhvSYAKs
" +
"nu02Hozqb4jh/gaQ/E6NkvM3DkqIyIYsRH2smstIFEb9CCiTdiz/OsJKQLgGy/pq
" +
"IVKtai3lnUxAayEV45Z61rNTOusNJf+icGhZxjqhAeoWjMxOCVmVC2GKa9sisqBg
" +
"kQIDAQAB
" +
"-----END PUBLIC KEY-----
");
StringEncryptor encryptor = new SimpleAsymmetricStringEncryptor(config);
String message = "chupacabras";
String encrypted = encryptor.encrypt(message);
System.out.printf("Encrypted message %s
", encrypted);
}
}
Demo App
Thejasypt-spring-boot-demo-samplesrepo contains working Spring Boot app examples. The mainjasypt-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:
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:
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:
jasypt.encryptor.password=${JASYPT_ENCRYPTOR_PASSWORD:}
or in YAML
jasypt:
encryptor:
password: ${JASYPT_ENCRYPTOR_PASSWORD:}
basically what this does is to define thejasypt.encryptor.passwordproperty pointing to a different propertyJASYPT_ENCRYPTOR_PASSWORDthat 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:
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
Whilejasypt-spring-boot-demois a comprehensive Demo that showcases all possible ways to encrypt/decrypt properties, there are other multiple Demos that demo isolated scenarios.
總結
以上是生活随笔為你收集整理的jasypt-spring-boot的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: HDU6438 Buy and Rese
- 下一篇: 洛谷P3066 [USACO12DEC]