Giter Club home page Giter Club logo

jasypt-spring-boot's Introduction

jasypt-spring-boot

Jasypt integration for Spring boot 2.x and 3.0.0

Build Status Gitter Maven Central

Code Climate Codacy Badge GitHub release Github All Releases MIT License volkswagen status

Paypal

"Buy Me A Coffee"

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?

Go to Releases

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, application-*.properties, yaml properties, and any other property sources can contain encrypted properties):

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

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

    And then add @EnableEncryptableProperties to 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)

  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:

    <dependency>
            <groupId>com.github.ulisesbocchio</groupId>
            <artifactId>jasypt-spring-boot</artifactId>
            <version>3.0.5</version>
    </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:

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

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

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

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:

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

This method would only require using a dependency for jasypt-spring-boot. 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:

<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 custom StringEncryptor is needed to be provided, a static builder method is provided StandardEncryptableEnvironment#builder for customization (other customizations are possible):

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

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:

    @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 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 @EncryptablePropertySource annotation 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.):

KeyRequiredDefault Value
jasypt.encryptor.passwordTrue -
jasypt.encryptor.algorithmFalsePBEWITHHMACSHA512ANDAES_256
jasypt.encryptor.key-obtention-iterationsFalse1000
jasypt.encryptor.pool-sizeFalse1
jasypt.encryptor.provider-nameFalseSunJCE
jasypt.encryptor.provider-class-nameFalsenull
jasypt.encryptor.salt-generator-classnameFalseorg.jasypt.salt.RandomSaltGenerator
jasypt.encryptor.iv-generator-classnameFalseorg.jasypt.iv.RandomIvGenerator
jasypt.encryptor.string-output-typeFalsebase64
jasypt.encryptor.proxy-property-sourcesFalsefalse
jasypt.encryptor.skip-property-sourcesFalseempty list

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 PropertySource, EnumerablePropertySource, 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.

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("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;
    }

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:

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

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:

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

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:

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 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):

jasypt:
  encryptor:
    property:
      prefix: "ENC@["
      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:

    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());
    }

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:

    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 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.

Filter out PropertySource classes from being introspected

Define a comma-separated list of fully-qualified class names to be skipped from introspection. This classes will not be wrapped/proxied by this plugin and thereby properties contained in them won't supported encryption/decryption:

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

Encryptable Properties cache refresh

Encrypted properties are cached within your application and in certain scenarios, like when using externalized configuration from a config server the properties need to be refreshed when they changed. For this jasypt-spring-boot registers a RefreshScopeRefreshedEventListener that listens to the following events by default to clear the encrypted properties cache:

public static final List<String> EVENT_CLASS_NAMES = Arrays.asList(
            "org.springframework.cloud.context.scope.refresh.RefreshScopeRefreshedEvent",
            "org.springframework.cloud.context.environment.EnvironmentChangeEvent",
            "org.springframework.boot.web.servlet.context.ServletWebServerInitializedEvent"
    );

Should you need to register extra events that you would like to trigger an encrypted cache invalidation you can add them using the following property (separate by comma if more than one needed):

jasypt.encryptor.refreshed-event-classes=org.springframework.boot.context.event.ApplicationStartedEvent

Maven Plugin

A Maven plugin is provided with a number of helpful utilities.

To use the plugin, just add the following to your pom.xml:

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

When using this plugin, the easiest way to provide your encryption password is via a system property i.e. -Djasypt.encryptor.password="the password".

By default, the plugin will consider encryption configuration in standard Spring boot configuration files under ./src/main/resources. You can also use system properties or environment variables to supply this configuration.

Keep in mind that the rest of your application code and resources are not available to the plugin because Maven plugins do not share a classpath with projects. If your application provides encryption configuration via a StringEncryptor bean then this will not be picked up.

In general, it is recommended to just rely on the secure default configuration.

Encryption

To encrypt a single value run:

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

To encrypt placeholders in src/main/resources/application.properties, simply wrap any string with DEC(...). For example:

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

Then run:

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

Which would edit that file in place resulting in:

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

The file name and location can be customised.

Decryption

To decrypt a single value run:

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

To decrypt placeholders in src/main/resources/application.properties, simply wrap any string with ENC(...). For example:

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

This can be decrypted as follows:

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

Which would output the decrypted contents to the screen:

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

Note that outputting to the screen, rather than editing the file in place, is designed to reduce accidental committing of decrypted values to version control. When decrypting, you most likely just want to check what value has been encrypted, rather than wanting to permanently decrypt that value.

Re-encryption

Changing the configuration for existing encrypted properties is slightly awkward using the encrypt/decrypt goals. You must run the decrypt goal using the old configuration, then copy the decrypted output back into the original file, then run the encrypt goal with the new configuration.

The re-encrypt goal simplifies this by re-encrypting a file in place. 2 sets of configuration must be provided. The new configuration is supplied in the same way as you would configure the other maven goals. The old configuration is supplied via system properties prefixed with "jasypt.plugin.old" instead of "jasypt.encryptor".

For example, to re-encrypt application.properties that was previously encrypted with the password OLD and then encrypt with the new password NEW:

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

Note: All old configuration must be passed as system properties. Environment variables and Spring Boot configuration files are not supported.

Upgrade

Sometimes the default encryption configuration might change between versions of jasypt-spring-boot. You can automatically upgrade your encrypted properties to the new defaults with the upgrade goal. This will decrypt your application.properties file using the old default configuration and re-encrypt using the new default configuration.

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

You can also pass the system property -Djasypt.plugin.old.major-version to specify the version you are upgrading from. This will always default to the last major version where the configuration changed. Currently, the only major version where the defaults changed is version 2, so there is no need to set this property, but it is there for future use.

Load

You can also decrypt a properties file and load all of its properties into memory and make them accessible to Maven. This is useful when you want to make encrypted properties available to other Maven plugins.

You can chain the goals of the later plugins directly after this one. For example, with flyway:

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

You can also specify a prefix for each property with -Djasypt.plugin.keyPrefix=example.. This helps to avoid potential clashes with other Maven properties.

Changing the file path

For all the above utilities, the path of the file you are encrypting/decrypting defaults to file:src/main/resources/application.properties.

This can be changed using the -Djasypt.plugin.path system property.

You can encrypt a file in your test resources directory:

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

Or with a different name:

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

Or with a different file type (the plugin supports any plain text file format including YAML):

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

Note that the load goal only supports .property files

Spring profiles and other spring config

You can override any spring config you support in your application when running the plugin, for instance selecting a given spring profile:

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

Multi-module maven projects

To encrypt/decrypt properties in multi-module projects disable recursion with -N or --non-recursive on the maven command:

mvn jasypt:upgrade -Djasypt.plugin.path=file:server/src/test/resources/application-test.properties  -Djasypt.encryptor.password=supersecret -N

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;

KeyDefault ValueDescription
jasypt.encryptor.privateKeyStringnull private key for decryption in String format
jasypt.encryptor.privateKeyLocationnulllocation of the private key for decryption in spring resource format
jasypt.encryptor.privateKeyFormatDERKey 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

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\n", 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-----\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);
    }
}

AES 256-GCM Encryption

As of version 3.0.5, AES 256-GCM Encryption is supported. To use this type of encryption, set the property jasypt.encryptor.gcm-secret-key-string, jasypt.encryptor.gcm-secret-key-location or jasypt.encryptor.gcm-secret-key-password.
The underlying algorithm used is AES/GCM/NoPadding so make sure that's installed in your JDK.
The SimpleGCMByteEncryptor uses a IVGenerator to encrypt properties. You can configure that with property jasypt.encryptor.iv-generator-classname if you don't want to use the default implementation RandomIvGenerator

Using a key

When using a key via jasypt.encryptor.gcm-secret-key-string or jasypt.encryptor.gcm-secret-key-location, make sure you encode your key in base64. The base64 string value could set to jasypt.encryptor.gcm-secret-key-string, or just can save it in a file and use a spring resource locator to that file in property jasypt.encryptor.gcm-secret-key-location. For instance:

jasypt.encryptor.gcm-secret-key-string="PNG5egJcwiBrd+E8go1tb9PdPvuRSmLSV3jjXBmWlIU="
#OR
jasypt.encryptor.gcm-secret-key-location=classpath:secret_key.b64
#OR
jasypt.encryptor.gcm-secret-key-location=file:/full/path/secret_key.b64
#OR
jasypt.encryptor.gcm-secret-key-location=file:relative/path/secret_key.b64

Optionally, you can create your own StringEncryptor bean:

@Bean("encryptorBean")
public StringEncryptor stringEncryptor() {
    SimpleGCMConfig config = new SimpleGCMConfig();
	config.setSecretKey("PNG5egJcwiBrd+E8go1tb9PdPvuRSmLSV3jjXBmWlIU=");
	return new SimpleGCMStringEncryptor(config);
}

Using a password

Alternatively, you can use a password to encrypt/decrypt properties using AES 256-GCM. The password is used to generate a key on startup, so there is a few properties you need to/can set, these are:

jasypt.encryptor.gcm-secret-key-password="chupacabras"
#Optional, defaults to "1000"
jasypt.encryptor.key-obtention-iterations="1000"
#Optional, defaults to 0, no salt. If provided, specify the salt string in ba64 format
jasypt.encryptor.gcm-secret-key-salt="HrqoFr44GtkAhhYN+jP8Ag=="
#Optional, defaults to PBKDF2WithHmacSHA256
jasypt.encryptor.gcm-secret-key-algorithm="PBKDF2WithHmacSHA256"

Make sure this parameters are the same if you're encrypting your secrets with external tools. Optionally, you can create your own StringEncryptor bean:

@Bean("encryptorBean")
public StringEncryptor stringEncryptor() {
    SimpleGCMConfig config = new SimpleGCMConfig();
	config.setSecretKeyPassword("chupacabras");
	config.setSecretKeyIterations(1000);
	config.setSecretKeySalt("HrqoFr44GtkAhhYN+jP8Ag==");
	config.setSecretKeyAlgorithm("PBKDF2WithHmacSHA256");
	return new SimpleGCMStringEncryptor(config);
}

Encrypting properties with AES GCM-256

You can use the Maven Plugin or follow a similar strategy as explained in Asymmetric Encryption's Encrypting Properties

Demo App

The jasypt-spring-boot-demo-samples repo contains working Spring Boot app examples. The main jasypt-spring-boot-demo Demo 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 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:

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's People

Contributors

alastair-watts-avrios avatar carldea avatar chiyutianyi avatar fahimfarookme avatar falcondamian avatar fenixcitizen avatar ggrebert avatar gologo13 avatar jerchende avatar jonas-haeusler avatar melloware avatar misselvexu avatar newnewcoder avatar nihaf avatar paul-kraftlauget avatar pierreprimot avatar qxo avatar rupert-madden-abbott avatar tavenyin avatar thorntonrp avatar trytocatch avatar ttulka avatar ulibocchio avatar ulisesbocchio avatar yassineimounachen avatar zeldan avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jasypt-spring-boot's Issues

Decrypted value ends with "="

I'm experiencing a very strange issue. When using encrypted password with an Oracle datasource

spring.datasource.url=jdbc:oracle:thin:@PCSRPWDSVIL:1521:dbrecpwd
spring.datasource.userId=otpuser
spring.datasource.password=ENC(0FiLiCHZdFUOnb938Gtfj9q3s23nmRyP)
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver

I always get an Invalid username/password error:

2016-01-27 17:49:09.686 ERROR 6411 --- [           main] o.a.tomcat.jdbc.pool.ConnectionPool      : Unable to create initial connections of pool.

java.sql.SQLException: ORA-01017: invalid username/password; logon denied

    at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:447) ~[ojdbc6-11.2.0.4.jar!/:11.2.0.4.0]
...

It works in plaintext. So I've wrote a very simple controller just for testing purposes, this is the controller code

@Controller
@RequestMapping("/encrypt")
public class JasyptController {

    private Logger logger = Logger.getLogger(JasyptController.class);

    @Autowired
    private StringEncryptor stringEncryptor;

    @RequestMapping(method = RequestMethod.POST)
    public
    @ResponseBody
    String encrypt(
            @RequestBody String text) {
        String encrypted = stringEncryptor.encrypt(text.trim());
        logger.info("ENCRYPTED: " + encrypted);
        logger.info("DECRYPTED: " + stringEncryptor.decrypt(encrypted));
        return String.format("ENC(%s)", encrypted);
    }
}

while this is the custom configuration made in Application class (1to1 copy from the project readme)

    @Bean
    static public StringEncryptor stringEncryptor() {
        PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();
        SimpleStringPBEConfig config = new SimpleStringPBEConfig();
        //TODO: replace with real secret... Read somewhere, e.g. a system property
        String secret = "password";
        config.setPassword(secret);
        config.setAlgorithm("PBEWithMD5AndDES");
        config.setKeyObtentionIterations("1000");
        config.setPoolSize("1");
        config.setProviderName("SunJCE");
        config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator");
        config.setStringOutputType("base64");
        encryptor.setConfig(config);
        return encryptor;
    }

This is how I invoke it

$ curl localhost:8080/encrypt --data mytext
ENC(kdOzCGcWc1ypiGmr2MIG8A==)

And this is the log:

2016-01-27 17:39:20.663  INFO 6368 --- [nio-8080-exec-1] c.n.m.controllers.JasyptController       : ENCRYPTED: kdOzCGcWc1ypiGmr2MIG8A==
2016-01-27 17:39:20.665  INFO 6368 --- [nio-8080-exec-1] c.n.m.controllers.JasyptController       : DECRYPTED: mytext=

So I think the problem resides in an additional base64 padding performed somewhere on the decrypted value... Really strange. Any advice? Or maybe am I missing something?

Thanks in advance, and best regards,
Fabio

XML Config file schemas are not available at time of load.

Some projects, including ones based on Spring Integration Framework and Spring Batch require XML Files for configuration. Custom encryption beans are sometimes also required which may need to be defined in XML. While various XSD Namespaces can be used during loading, the jasypt encryption xsds can not be used by Spring Boot with the Starter plugin. A Demo project illustrating this has been setup at https://github.com/gorky/jasyptDemo.
This can be run either from command line using ./gradlew run, or in an IDE.

Cannot enhance @Configuration bean definition 'beanNamePlaceholderRegistryPostProcessor'

Hi,

I've just been debugging why I get this warning in the logs. It happens as soon as I add Jasypt to my POM file in a SpringBoot 1.5.2 app. I tried changing to Spring Boot 1.5.1 too as I noticed it was mentioned as fixed in another ticket (#16), but it still appears. Actually that was slightly different but could ignore the warning in a similar fashion.

WARN [main] ConfigurationClassPostProcessor: Cannot enhance @Configuration bean definition 'beanNamePlaceholderRegistryPostProcessor' since its singleton instance has been created too early. The typical cause is a non-static @Bean method with a BeanDefinitionRegistryPostProcessor return type: Consider declaring such methods as 'static'.

I can get logback to ignore it, as is also mentioned in the other ticket, but as it was marked as fixed I thought I would raise it again.

How to use jasypt.encryptor.password in Hibernate @TypeDef ?

I am using jasypt-spring-boot and it works great for encypting properties in property files by passing --jasypt.encryptor.password=mysecretpassword.

Is it also possible to use that property in the Hibernate annotation?

I currently have this:

@TypeDef(
        name = "encryptedInteger",
        typeClass = EncryptedIntegerAsStringType.class,
        parameters= {
                @Parameter(name="password", value="mysecretpassword")
        }
)

But that is obviously not very convenient as it hardcodes the password in the code.

Configuration metadata

It would be awesome if jasypt-spring-boot supported configuration metadata http://docs.spring.io/spring-boot/docs/current/reference/html/configuration-metadata.html so documentation and IDE assistance are available for the various properties (jasypt.encryptor.password, jasypt.encryptor.algorithm, etc) which this project supports.

I can imagine this improvement being implemented in 1 of 2 ways:

  • Change to use @ConfigurationProperties which, combined with spring-boot-configuration-processor, will generate META-INF/spring-configuration-metadata.json
  • Add a manually written META-INF/spring-configuration-metadata.json

jasypt-spring-boot-starter not working with open-jdk 1.8

Below is the error I get:
Caused by: java.lang.UnsupportedClassVersionError: com/ulisesbocchio/jasyptspringboot/EnableEncryptablePropertySourcesPostProcessor : Unsupported major.minor version 52.0 (unable to load class com.ulisesbocchio.jasyptspringboot.EnableEncryptablePropertySourcesPostProcessor)
at org.apache.catalina.loader.WebappClassLoaderBase.findClassInternal(WebappClassLoaderBase.java:2499)
at org.apache.catalina.loader.WebappClassLoaderBase.findClass(WebappClassLoaderBase.java:859)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1301)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1166)
at org.springframework.util.ClassUtils.forName(ClassUtils.java:250)
at org.springframework.boot.SpringApplication.createSpringFactoriesInstances(SpringApplication.java:407)

Execution environment:
openjdk version "1.8.0_91"
OpenJDK Runtime Environment (build 1.8.0_91-8u91-b14-0ubuntu4~15.10.1-b14)
OpenJDK 64-Bit Server VM (build 25.91-b14, mixed mode)

pom.xml contains:

com.github.ulisesbocchio
jasypt-spring-boot-starter
1.7

no release available

Your solution looks promising and I would like to use it (oasp/oasp4j#279)

Will there be a release available in maven central?
There are not even tags in your git where to build a reliable version from.
Your documentation states that maven will download from the specified dependency but there is no such release. Am I missing something?

String Encryptor custom Bean not found with name 'jasyptStringEncryptor' even when bean exists in the config

Hi,
I am using jasypt spring boot starter plug in and added custom String Encryptor bean defination to the AppConfig file but still I get the String Encryptor custom Bean not found with name 'jasyptStringEncryptor' error in the logs and always it picking up default jasypt encryption config values.

Please help me why spring not picking up my custom encryption config values.

Spring boot version is -1.5.4.RELEASE
Jayspt version is -com.github.ulisesbocchio:jasypt-spring-boot-starter:1.12

My Bean definition looks like below.

@Bean(name="jasyptStringEncryptor")
	static public PooledPBEStringEncryptor 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.setStringOutputType("base64");
		encryptor.setConfig(config);
		return encryptor;
	}

log:
2017-06-20 21:53:29.921 INFO 16560 --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Overriding bean definition for bean 'jasyptStringEncryptor' with a different defin
ition: replacing [Root bean: class [com....AppConfig]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factor
yBeanName=null; factoryMethodName=stringEncryptor; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [com/
///AppConfig.class]] with [Root bean:
class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=com.ulisesbocchio.jasyptspringboot.con
figuration.EncryptablePropertyResolverConfiguration; factoryMethodName=stringEncryptor; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [com/ulisesbo
cchio/jasyptspringboot/configuration/EncryptablePropertyResolverConfiguration.class]]
2017-06-20 21:53:29.925 WARN 16560 --- [ main] o.s.c.a.ConfigurationClassPostProcessor : Cannot enhance @configuration bean definition 'beanNamePlaceholderRegistryPostProc
essor' since its singleton instance has been created too early. The typical cause is a non-static @bean method with a BeanDefinitionRegistryPostProcessor return type: Consider declari
ng such methods as 'static'.

2017-06-20 21:53:31.406 INFO 16560 --- [ main] EncryptablePropertyResolverConfiguration : String Encryptor custom Bean not found with name 'jasyptStringEncryptor'. Initiali
zing String Encryptor based on properties with name 'jasyptStringEncryptor'
2017-06-20 21:53:31.425 INFO 16560 --- [ main] c.u.j.encryptor.DefaultLazyEncryptor : Encryptor config not found for property jasypt.encryptor.algorithm, using default
value: PBEWithMD5AndDES

Spring Boot warning for com.ulisesbocchio.jasyptspringboot.configuration.EncryptablePropertyResolverConfiguration

Spring Boot version: 1.5.1.RELEASE
jasypt-spring-boot-starter version: 1.11

We see this warning every-time we run the application, although it does not affect the functionality. May be you can investigate the cause and fix it.

WARN o.s.c.a.ConfigurationClassPostProcessor - Cannot enhance @Configuration bean definition 'beanNamePlaceholderRegistryPostProcessor' since its singleton instance has been created too early. The typical cause is a non-static @Bean method with a BeanDefinitionRegistryPostProcessor return type: Consider declaring such methods as 'static'.

Unable to decrypt property when PropertySourcesPlaceholderConfigurer is used

My application is using netflix.archaius component to listen to dynamic changes to properties file. The properties file contains few jasypt encrypted properties. The application uses @EnableEncryptableProperties and required dependencies.

But encrypted properties are not being decrypted when below class i.e. PropertyResourceConfig is present in the application. Decryption works fine if I remove this class from the application. I am not sure how to make jasypt decryption working properly along with this class. I think the bean PropertySourcesPlaceholderConfigurer is causing the problem.
Please help me to resolve this issue.

package com.company.control.config;

import java.io.File;
import java.io.IOException;

import org.apache.commons.configuration.Configuration;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Profile;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MutablePropertySources;

import com.company.control.dynamicproperties.ApacheCommonsConfigPropertySource;
import com.company.control.dynamicproperties.ConfigurationWatcher;
import com.netflix.config.ConfigurationManager;
import com.netflix.config.DynamicConfiguration;
import com.netflix.config.DynamicURLConfiguration;

@org.springframework.context.annotation.Configuration
@Profile("common")
public class PropertyResourceConfig {
@bean
public ConfigurationWatcher configurationWatcher() {
return new ConfigurationWatcher();
}

@Bean
public DynamicConfiguration configuration(ConfigurationWatcher configurationWatcher) throws IOException {
    int pollInterval = NumberUtils.toInt(System.getProperty("config.pollInterval"), 15000);
    String basePath = StringUtils.defaultIfBlank(System.getProperty("config.directory"), "config");
    String appConfigPath = basePath + File.separatorChar + "authorization-control";
    String globalConfig = getFileUrl(appConfigPath, "global.properties");
    String instanceConfig = getFileUrl(appConfigPath, "instance.properties");

    DynamicConfiguration config = new DynamicURLConfiguration( //
            pollInterval, pollInterval, false, //
            globalConfig, instanceConfig);
    config.addConfigurationListener(configurationWatcher);
    ConfigurationManager.install(config);

    return config;
}

@Bean
public PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer(ConfigurableEnvironment env,
        Configuration configuration) {
    PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();

    MutablePropertySources sources = new MutablePropertySources();
    sources.addLast(new ApacheCommonsConfigPropertySource("archaius", configuration));
    configurer.setPropertySources(sources);
    configurer.setEnvironment(env);

    return configurer;
}

private static String getFileUrl(String basePath, String filename) {
    String filePath = basePath + File.separatorChar + filename;
    File file = new File(filePath);
    return file.toURI().toString();
}

}

Multiple parameters

Hi,

I have encrypted user id and password both with different keys, How can I pass the both keys while running the jar.
Ex :
java -Djasypt.encryptor.password=pass1 -Djasypt.encryptor.password=pass2 -jar xxx.jar

I have tried with above command but it is not working.
Please help me to achieve this.

Hi, is it possible to remove "encrypted.property" config, and auto detect "ENC " statement?

if i want to encrypt the datasource password, now the two configuration below is needed:

spring.datasource.password=ENC(+Nrx10OneKdA9VvXGXkyaxWzNHt+sQ46)
spring.datasource.password.property=

Stand on the common user side, i just feel a little strange, it is possible to use the format
spring.datasource.password.property=+Nrx10OneKdA9VvXGXkyaxWzNHt+sQ46

or
spring.datasource.password=ENC(+Nrx10OneKdA9VvXGXkyaxWzNHt+sQ46)

if they could be work, it's awesome :)

Performance waste due to decrypting each secret 34 times instead of once

I set a breakpoint into EncryptablePropertySource and figured out that it is called many times for the same property. So I added this line inside the inner if block (Line 17):

System.out.println("Decrypting value of property " + name);

When I startup my simple spring boot application with only a single datasource I get this output:

Decrypting value of property spring.datasource.password
Decrypting value of property spring.datasource.password
Decrypting value of property spring.datasource.password
Decrypting value of property spring.datasource.password
Decrypting value of property spring.datasource.password
Decrypting value of property spring.datasource.password
Decrypting value of property spring.datasource.password
Decrypting value of property spring.datasource.password
Decrypting value of property spring.datasource.password
Decrypting value of property spring.datasource.password
Decrypting value of property spring.datasource.password
Decrypting value of property spring.datasource.password
Decrypting value of property spring.datasource.password
Decrypting value of property spring.datasource.password
Decrypting value of property spring.datasource.password
Decrypting value of property spring.datasource.password
Decrypting value of property spring.datasource.password
Decrypting value of property spring.datasource.password
Decrypting value of property spring.datasource.password
Decrypting value of property spring.datasource.password
Decrypting value of property spring.datasource.password
Decrypting value of property spring.datasource.password
Decrypting value of property spring.datasource.password
Decrypting value of property spring.datasource.password
Decrypting value of property spring.datasource.password
Decrypting value of property spring.datasource.password
Decrypting value of property spring.datasource.password
Decrypting value of property spring.datasource.password
Decrypting value of property spring.datasource.password
Decrypting value of property spring.datasource.password
Decrypting value of property spring.datasource.password
Decrypting value of property spring.datasource.password
Decrypting value of property spring.datasource.password
Decrypting value of property spring.datasource.password

This means the same (and single) encrypted secret is decrypted 34 times.

IMHO this is rather a design flaw of spring that your code but I want to point this out and will also connect with the spring boot team on github.

Error creating bean with name 'springSecurityFilterChain'

I'm trying to implement a custom EncryptablePropertyResolver, but I'm receiving this error on start:

I have @EnableWebSecurity and @configuration in my WebSecurityConfig.

2017-06-26 15:54:24.882  INFO 13408 --- [  restartedMain] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2017-06-26 15:54:25.410  INFO 13408 --- [  restartedMain] o.apache.catalina.core.StandardService   : Stopping service Tomcat
2017-06-26 15:54:25.437  INFO 13408 --- [  restartedMain] utoConfigurationReportLoggingInitializer : 

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2017-06-26 15:54:25.448 ERROR 13408 --- [  restartedMain] o.s.boot.SpringApplication               : Application startup failed

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'springSecurityFilterChain' defined in class path resource [org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is java.lang.IllegalStateException: org.springframework.security.config.annotation.ObjectPostProcessor is a required bean. Ensure you have used @EnableWebSecurity and @Configuration
	at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1128) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1022) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:512) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
	at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
	at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:296) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:754) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
	at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866) ~[spring-context-4.3.4.RELEASE.jar:4.3.4.RELEASE]
	at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542) ~[spring-context-4.3.4.RELEASE.jar:4.3.4.RELEASE]
	at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.4.2.RELEASE.jar:1.4.2.RELEASE]
	at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:761) [spring-boot-1.4.2.RELEASE.jar:1.4.2.RELEASE]
	at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:371) [spring-boot-1.4.2.RELEASE.jar:1.4.2.RELEASE]
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) [spring-boot-1.4.2.RELEASE.jar:1.4.2.RELEASE]
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:1186) [spring-boot-1.4.2.RELEASE.jar:1.4.2.RELEASE]
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:1175) [spring-boot-1.4.2.RELEASE.jar:1.4.2.RELEASE]
	at com.dtec.cop.Application.main(Application.java:17) [bin/:na]
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_131]
	at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_131]
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_131]
	at java.lang.reflect.Method.invoke(Unknown Source) ~[na:1.8.0_131]
	at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) [spring-boot-devtools-1.4.2.RELEASE.jar:1.4.2.RELEASE]
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is java.lang.IllegalStateException: org.springframework.security.config.annotation.ObjectPostProcessor is a required bean. Ensure you have used @EnableWebSecurity and @Configuration
	at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
	at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
	... 25 common frames omitted
Caused by: java.lang.IllegalStateException: org.springframework.security.config.annotation.ObjectPostProcessor is a required bean. Ensure you have used @EnableWebSecurity and @Configuration
	at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter$1.postProcess(WebSecurityConfigurerAdapter.java:81) ~[spring-security-config-4.1.3.RELEASE.jar:4.1.3.RELEASE]
	at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.getHttp(WebSecurityConfigurerAdapter.java:174) ~[spring-security-config-4.1.3.RELEASE.jar:4.1.3.RELEASE]
	at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.init(WebSecurityConfigurerAdapter.java:290) ~[spring-security-config-4.1.3.RELEASE.jar:4.1.3.RELEASE]
	at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.init(WebSecurityConfigurerAdapter.java:69) ~[spring-security-config-4.1.3.RELEASE.jar:4.1.3.RELEASE]
	at com.dtec.cop.config.WebSecurityConfig$$EnhancerBySpringCGLIB$$fca24708.init(<generated>) ~[bin/:na]
	at org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder.init(AbstractConfiguredSecurityBuilder.java:371) ~[spring-security-config-4.1.3.RELEASE.jar:4.1.3.RELEASE]
	at org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder.doBuild(AbstractConfiguredSecurityBuilder.java:325) ~[spring-security-config-4.1.3.RELEASE.jar:4.1.3.RELEASE]
	at org.springframework.security.config.annotation.AbstractSecurityBuilder.build(AbstractSecurityBuilder.java:41) ~[spring-security-config-4.1.3.RELEASE.jar:4.1.3.RELEASE]
	at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration.springSecurityFilterChain(WebSecurityConfiguration.java:104) ~[spring-security-config-4.1.3.RELEASE.jar:4.1.3.RELEASE]
	at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration$$EnhancerBySpringCGLIB$$44e8aaaf.CGLIB$springSecurityFilterChain$6(<generated>) ~[spring-security-config-4.1.3.RELEASE.jar:4.1.3.RELEASE]
	at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration$$EnhancerBySpringCGLIB$$44e8aaaf$$FastClassBySpringCGLIB$$56c519e3.invoke(<generated>) ~[spring-security-config-4.1.3.RELEASE.jar:4.1.3.RELEASE]
	at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228) ~[spring-core-4.3.4.RELEASE.jar:4.3.4.RELEASE]
	at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:356) ~[spring-context-4.3.4.RELEASE.jar:4.3.4.RELEASE]
	at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration$$EnhancerBySpringCGLIB$$44e8aaaf.springSecurityFilterChain(<generated>) ~[spring-security-config-4.1.3.RELEASE.jar:4.1.3.RELEASE]
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_131]
	at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_131]
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_131]
	at java.lang.reflect.Method.invoke(Unknown Source) ~[na:1.8.0_131]
	at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162) ~[spring-beans-4.3.4.RELEASE.jar:4.3.4.RELEASE]
	... 26 common frames omitted```

integrating jasypt with ibmjcefips provider

I havent been successful at integrating jasypt with ibmjcefips provider. I can use the provider directly in my code so yes it is successfully set up in the jdk (e.g. strong encryption enabled, provider registered). But attempt to encrypt with it using jasypt I get a FipsRuntimeException. I have googled this exception repeatedly without luck. Is there a way to get more debug from jasypt? Has anyone successfully integrated jasypt with a truly FIPS compliant provider (Bouncy Castle is not certified compliant). Thanks.

How to protect jasypt.encryptor.password in AWS?

  • I am using jasypt-spring-boot to protect the secrets that are stored in application-*properties file in my spring boot app
  • Our spring boot app running from AWS and we supply the jasypt.encryptor.password via --jasypt.encryptor.password =value
    -This password can be visible to anyone who can see the history command on that host
  • Is there a better way to protect jasypt.encryptor.password

stringEnryptor should not be created by a type in BeanFactoryPostProcessor.

Instantiating a bean by a type in a spring BeanFactoryPostProcessor is quite dangerous because of an instantiate order. This order could be difference for each spring configuration. So stringEncryptor in EnableEncryptablePropertySourcesPostProcessor should be create by a name to avoid bean creation dependency.

`
private PropertySource makeEncryptable(PropertySource propertySource, ConfigurableListableBeanFactory registry) {
** String beanName = environment.getProperty("jasypt.encryptor.beanName", "stringEncryptor");
StringEncryptor encryptor = registry.getBean(beanName, StringEncryptor.class);
**
PropertySource encryptablePropertySource = interceptionMode == InterceptionMode.PROXY
? proxyPropertySource(propertySource, encryptor) : instantiatePropertySource(propertySource, encryptor);
LOG.info("Converting PropertySource {}[{}] to {}", propertySource.getName(), propertySource.getClass().getName(),
encryptablePropertySource.getClass().getSimpleName());
return encryptablePropertySource;
}

`

Cannot enhance @Configuration bean definition 'beanNamePlaceholderRegistryPostProcessor'

I have tried to apply the similar setup for the other app, but I have encountered this issue.

Jun 27, 2016 12:33:50 PM org.apache.catalina.startup.VersionLoggerListener log WARNING: Cannot enhance @Configuration bean definition 'beanNamePlaceholderRegistryPostProcessor' since its singleton instance has been created too early. The typical cause is a non-static @Bean method with a BeanDefinitionRegistryPostProcessor return type: Consider declaring such methods as 'static'.
Jun 27, 2016 12:34:25 PM org.apache.catalina.startup.TldConfig execute SEVERE: Context [] startup failed due to previous errors
Jun 27, 2016 12:34:32 PM org.springframework.web.context.support.XmlWebApplicationContext doClose

Can anyone takes a look at this?

Cannot decrypt from env variable

Hello,

Can I use it to decrpyt value from Environment Variable?

I tried something like this:
spring.datasource.password=ENC(${DB_PASSWORD})

and I got an error : org.jasypt.exceptions.EncryptionOperationNotPossibleException: null

Thank you.

passwordEnvName?

application.yml:

jasypt:
encryptor:
passwordEnvName: ${passwordEnvName}

or

jasypt:
encryptor:
password: systemEnvironment[${passwordEnvName}]

I Hope support system Environment password to jasypt-spring-boot.

Beans with @EnableConfigurationProperties are not properly instanciated.

Hi,

I found an issue when using jasypt-spring-boot with a Spring configuration bean mapped from an application.yml file (see §23.7 at http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html).

When @EnableEncryptableProperties is set, the configuration bean is not properly created. Properties of this bean that map a collection from the YAML file are not set. On the other side, it is correctly populated if @EnableEncryptableProperties is not set.

I pushed an example at carguel/jasypt-spring-boot-sample. If you run the Main class, a NPE is raised when accessing the items collection from the ItemConfig class. This collection should be populated from the items nested node of the application.yml file.

I guess some initializations steps are missing in EnableEncryptablePropertySourcesPostProcessor.java.
But I could not find how to fix this.

Updating jasypt-spring-boot to use Spring Boot 1.5.1.RELEASE

Hi

I am looking to update jasypt-spring-boot to use Spring Boot 1.5.1.RELEASE but I am hitting an issue as per below

Error creating bean with name 'beanNamePlaceholderRegistryPostProcessor' defined in class path resource [com/ulisesbocchio/jasyptspringboot/configuration/EncryptablePropertyResolverConfiguration.class]: Unsatisfied dependency expressed through method 'beanNamePlaceholderRegistryPostProcessor' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionRepository': Could not resolve matching constructor (hint: specify index/type/name arguments for simple parameters to avoid type ambiguities)

Warn Message from Spring Boot after upgrading to 1.2.6.RELEASE

After upgrading to Spring Boot 1.2.6.RELEASE, i have the following warn message in the logs :

@Bean method EnableEncryptablePropertySourcesConfiguration.enableEncryptablePropertySourcesPostProcessor is non-static and returns an object assignable to Spring's BeanFactoryPostProcessor interface. This will result in a failure to process annotations such as @Autowired, @Resource and @PostConstruct within the method's declaring @Configuration class. Add the 'static' modifier to this method to avoid these container lifecycle issues; see @Bean javadoc for complete details.

I'm using the 1.2 version of jasypt-spring-boot-starter.

Thanks in advance

jasypt password visible when passed as argument or System property

When an application is started in a way that is demonstrated below

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

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

a linux user can see it by listing currently running processes. I belive that it could be solved with command:
export MY_PASSW=password

however currently required variable is 'jasypt.encryptor.password' that is not valid name for environment settings. Could that be replace with name like:
jasypt_encryptor_password

I use spring but not use spring boot

Hi,

I want to custom spring @propertysource annotation for jasypt.

but it's hard for me, and I find this project.

The project so cool, but I use spring 4, not use spring boot,

can this project use for spring?

if can, give me a point or some hint, I want use this.

jasypt-spring-boot overrides custom jasyptStringEncryptor bean

Hi,
I am using the approach No. 2 stated by you in your documentation. The issue I am facing is that I see this in the logs:
Overriding bean definition for bean 'customBean': replacing [Root bean: class [com.test.Config]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=stringEncryptor; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [com/test/Config.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=com.ulisesbocchio.jasyptspringboot.configuration.StringEncryptorConfiguration; factoryMethodName=stringEncryptor; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [com/ulisesbocchio/jasyptspringboot/configuration/StringEncryptorConfiguration.class]]

and then I see this,

String Encryptor custom Bean not found with name 'customBean'. Initializing String Encryptor based on properties with name 'customBean'

Why does it override the bean with a null class bean and then say that the customBean was not found?

encrypted spring properties inside logback-spring.xml file

Hi,
I'm using spring properties (from application.yml file) inside my logback-spring.xml (see logback extensions inside the spring-boot doco)
That works fine but not for encrypted properties (I would like to make use of a DBAppender with an encrypted password coming from the spring config file).
Would you have any suggestion on how to make it work ?
Regards
kbjp

overriding jasypt properties (e.g. jasypt.encryptor.password) not possible

The whole story about spring-boot application properties is its flexibility. See here:
http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html

Now, when I add your jasypt-spring-boot-starter as a dependency I can not start the application without having jasypt.encryptor.password set even if I have no encrypted password configured anywhere. This makes my unit tests fail, etc. So what I did is adding

jasypt.encryptor.password=dummy

To my application.properties that I deliver within the WAR file (in default package).
Now I have an external application.properties in tomcat/lib/config/application.properties that defines encrypted passwords for DB, etc.
Of course I want to provide the master password somewhere different as having it in the same file would be quite pointless (my plan is that I have a secret master password per environment that is available in one place on the involved machines while I then can have the configs with encrypted passwords stored in VCS but regular developers can not decrypt them without knowing the master password but they can build release packages including the correct configs).

Now, I set the master password on the commandline as a system property. I verified that the system property is actually set and available in tomcat. However, it is not honored and jasypt will use the dummy password instead.

This is totally unexpected as it works for any other spring boot property like this. There might be a technical reason as you need early on bootstrapping and interception.
However, a solution is required to externalize the master password from the actual properties file.
Any solution or workaround is welcome.
Thanks for your great work!

Post processor @Bean should be marked static

Thanks for creating this project. Quick observation.

Starting an application gives me this warning:

WARN org.springframework.context.annotation.ConfigurationClassEnhancer - 
  @Bean method EnableEncryptablePropertySourcesConfiguration
    .enableEncryptablePropertySourcesPostProcessor is non-static and returns
    an object assignable to Spring's BeanFactoryPostProcessor interface. This
    will result in a failure to process annotations such as @Autowired,
    @Resource and @PostConstruct within the method's declaring
    @Configuration class. Add the 'static' modifier to this method to avoid these
    container lifecycle issues; see @Bean javadoc for complete details

See @Bean Javadoc, section titled BeanFactoryPostProcessor-returning @Bean methods

Suggestion: Merge with Jasypt Project

Hello!

I reached out to Chus Picos from the Jasypt project to ask if they had plans to officially support Spring Boot integration. Has anyone from that project reached out to you in the past or recently?

Jan Choike

Problem integrating with an ssl application

Hi!
I used your library to encrypt some properties and it works and the application runs fine. But when I enable SSL in the application it won't work, the application start and all request works, but if i add the HTTPS doesn't return anything. If I remove the @EnableEncryptableProperties from the Application class the SSL works as expected, do you have any clue about whats could be happening? I really appreciate any help.

Greetings!

Default Security provider if no specified

Hi,

at first thanks very much for your project. It helps us very good. I have one improvement. In Jasypt specification there is possibility to use default security provider if config property provider and providerName is not specified. I think it is good feature because for most cases is that what is required. StandardPBEStringEncryptor during initialize phase creates SecretKeyFactory based upon algorithm with first supported registered security provider, see documentation.

Is it possible to change it? I can contribute it if you want. I think required change must be done in StringEncryptorConfiguration, where jasypt.encryptor.providerName will be resolved and applied only and only if is filled.

We need it for Java 1.7 stack.

Thanks,
Tomas

spring boot jasypt not decrypting property in a config file other than application.yml

Hi Ulises, I created a very simple spring boot REST service (https://github.com/donstrong/spring-boot-jasypt) in attempts to decrypt an encrypted property in a different configuration file (one other than application.yml) and was able to get the value, but it's still encrypted. When the same encrypted property was added to application.yml, the decrypted value is returned and displayed on the browser. The config file, application.yml, remains solely within the service's resource folder, but a config. file (under a different name, of course) with encrypted values is stored remotely and accessed by a Spring Cloud Config server.

Decryption was working fine when @configuration and @value annotations were used in the config classes, but when source was changed to use Spring's @EnableConfigurationProperties and @ConfigurationProperties(prefix=... , locations=...), where getters and setters are used in lieu of @value, the problem arose. Including @propertysource and/or @EncryptablePropertySource (with reference to the config file in the classpath) didn't seem to resolve the problem. At this point, I can revert back to using @configuration for the class and @value for each property but thought maybe there was a simple solution when using Spring's @EnableConfigurationProperties and @ConfigurationProperties. The readme file provides other details.

Hi, When running the demo, I got a 'WARN' message, it can be solved?

2015-07-01 17:09:53.382 WARN 82640 --- [ main] o.s.c.a.ConfigurationClassEnhancer : @bean method EnableEncryptablePropertySourcesConfiguration.enableEncryptablePropertySourcesPostProcessor is non-static and returns an object assignable to Spring's BeanFactoryPostProcessor interface. This will result in a failure to process annotations such as @Autowired, @resource and @PostConstruct within the method's declaring @configuration class. Add the 'static' modifier to this method to avoid these container lifecycle issues; see @bean javadoc for complete details.

@ConditionalOnProperty fails with @EncryptablePropertySource

It looks like there is an issue with using @ConditionalOnProperty in conjunction with @EncryptablePropertySource. I have a bean which is annotated with
@ConditionalOnProperty(name = "bean.enabled", matchIfMissing = false)
and I am importing the properties with
@EncryptablePropertySource(value = { "classpath:beans.properties" })
and beans.properties contains the property "bean.enabled=true"
The bean is not instantiated. Commenting out the @ConditionalOnProperty annotation allows the bean to be created, and all other properties are loaded correctly.

Does it work with vanilla Spring 4/5

I did not see Jasypt have official support for Spring 4/5, but when I tried to include @EnableEncryptableProperties and @EncryptablePropertySource, it does not work as expected.

spring boot /env fails if overriding with an external encrypted property file

If we provide an encrypted property and password within the war (for db password) and then override this in the deployment environment with another encrypted property and jasypt password then the /env endpoint will throw an exception as it's unable to decrypt the original property from the embedded property.

I understand why this is happening, but it would be nice if it just skipped the undecryptable property.

Cheers,
Daniel.

loading encrypted password from database

Hi,
In my spring boot application, I am loading some passwords(password of remote machines for doing scp) from database on startup. So in database if I store ENC(encryptedpassword), this is not getting decrypted when it is loaded. But if I store the same thing in my properties file and load it, it is properly decrypted.
Is it possible to store in database encrypted password like ENC(encryptedpassword) and get the encrypted password decrypted automatically when I load my application.

As an alternative now I am doing this
I store the encryptedpassword in DB(without ENC()) And in my application, before I use this password I do

 BasicTextEncryptor textDecryptor = new BasicTextEncryptor();
 textDecryptor.setPassword(encryptDecryptKey);
 textDecryptor.decrypt(encryptedpasswordfromDb)

Thanks
Panikiran

Doesn't work with Java 1.6

Can you please make it compatible with Java 1.6

ERROR:

com.ulisesbocchio.jasyptspringboot.annotation.EnableEncryptableProperties
[ERROR] bad class file: com/ulisesbocchio/jasyptspringboot/annotation/EnableEncryptableProperties.class(com/ulisesbocchio/jasyptspringboot/annotation:EnableEncryptableProperties.class)
[ERROR] class file has wrong version 52.0, should be 50.0

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.