jasypt-spring-boot

repository·master·Indexed 25 days ago

https://github.com/ulisesbocchio/jasypt-spring-boot

Provides encryption support for property sources in Spring Boot applications, allowing sensitive configuration values to be stored in an encrypted format using the ENC(...) wrapper. It includes a Maven plugin for encrypting, decrypting, re-encrypting, and upgrading properties, as well as support for automatic, manual, and granular configuration via starters or annotations like @EnableEncryptableProperties and @EncryptablePropertySource.

Tokens
10.1K
Snippets
24
Records
28
Agent score
35%

What's inside jasypt-spring-boot

  1. Advanced usage: Spring profiles, Multi-module, and Asymmetric Encryption

    master

    Using Spring Profiles

    You can specify an active Spring profile when running plugin goals:

    mvn jasypt:encrypt -Dspring.profiles.active=production -Djasypt.encryptor.password="mypassword"

    Multi-Module Projects

    In multi-module projects, use the -N flag to prevent the plugin from recursing into child modules. You must specify the full path to the configuration file:

    mvn jasypt:encrypt -Djasypt.plugin.path="file:module/src/main/resources/application.properties" -Djasypt.encryptor.password="mypassword" -N

    Asymmetric Encryption (PEM format)

    To encrypt a value using a public key in PEM format:

    mvn jasypt:encrypt-value \
      -Dspring.config.location="file:src/main/resources/application.yml" \
      -Djasypt.encryptor.public-key-format="PEM" \
      -Djasypt.encryptor.public-key-location="file:src/main/resources/publickey.pem" \
      -Djasypt.plugin.value="valueToEncrypt"
    mvn jasypt:encrypt -Dspring.profiles.active=production -Djasypt.encryptor.password="mypassword"
  2. Pass the encryption password via Environment Variable

    master

    To use an environment variable for the encryption password, map the jasypt.encryptor.password property to an environment variable name in your application.properties or application.yml file. This allows you to set the password via the OS environment.

    In application.properties:

    jasypt.encryptor.password=${JASYPT_ENCRYPTOR_PASSWORD:}

    In application.yml:

    jasypt:
        encryptor:
            password: ${JASYPT_ENCRYPTOR_PASSWORD:}

    Execution example:

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

    Note for Gradle users: If using Gradle, the processResources task may fail due to the $ character. Escape the variable using \$ (e.g., \$JASYPT_ENCRYPTOR_PASSWORD).

    jasypt:
        encryptor:
            password: ${JASYPT_ENCRYPTOR_PASSWORD:}
  3. Use Custom Environment for early access to encrypted properties

    master

    For special cases where you need encrypted properties available very early in the Spring lifecycle (e.g., for logback-spring.xml configuration using the springProperty tag), you can use a custom ConfigurableEnvironment via SpringApplicationBuilder. This requires the jasypt-spring-boot dependency but does not require the starter jar.

    Use StandardEncryptableEnvironment or StandardEncryptableServletEnvironment to define the custom environment. You can also use a static builder to provide a custom StringEncryptor.

    new SpringApplicationBuilder()
        .environment(new StandardEncryptableEnvironment())
        .sources(YourApplicationClass.class).run(args);
    
    // With a custom encryptor via builder
    StandardEncryptableEnvironment
        .builder()
        .encryptor(new MyEncryptor())
        .build();
  4. Install the Jasypt Maven Plugin

    master

    To use the Jasypt Maven Plugin in your Spring Boot project, add the following plugin configuration to your pom.xml:

    <build>
      <plugins>
        <plugin>
          <groupId>com.github.ulisesbocchio</groupId>
          <artifactId>jasypt-maven-plugin</artifactId>
          <version>4.0.0-SNAPSHOT</version>
        </plugin>
      </plugins>
    </build>
    <build>
      <plugins>
        <plugin>
          <groupId>com.github.ulisesbocchio</groupId>
          <artifactId>jasypt-maven-plugin</artifactId>
          <version>4.0.0-SNAPSHOT</version>
        </plugin>
      </plugins>
    </build>
  5. Use a Custom StringEncryptor Bean

    master

    You can provide your own StringEncryptor implementation by defining a Bean in your Spring Context. If you do this, the default encryptor will be ignored.

    By default, the library looks for a bean named jasyptStringEncryptor. If you want to use a different bean name, you must specify it using the jasypt.encryptor.bean property.

    @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;
    }
  6. Pass the encryption password via command line or system properties

    master

    You can provide the required jasypt.encryptor.password to your Spring Boot application using command line arguments or JVM system properties.

    To pass it as a command line argument:

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

    To pass it as a JVM system property:

    java -Djasypt.encryptor.password=password -jar target/jasypt-spring-boot-demo-0.0.1-SNAPSHOT.jar
    java -jar target/jasypt-spring-boot-demo-0.0.1-SNAPSHOT.jar --jasypt.encryptor.password=password
  7. Integrate jasypt-spring-boot into a Spring Boot application

    master

    You can integrate jasypt-spring-boot using one of three primary methods depending on your application structure:

    1. Automatic Configuration (Recommended for most): If your application uses @SpringBootApplication or @EnableAutoConfiguration, simply add the jasypt-spring-boot-starter dependency. This enables encrypted properties across the entire Spring Environment (system properties, environment variables, command line arguments, application.properties, YAML, etc.).

    2. Manual Configuration (For non-auto-configured apps): If you do not use auto-configuration annotations, add the jasypt-spring-boot dependency and annotate your main Configuration class with @EnableEncryptableProperties.

    3. Granular Configuration (Specific property sources): If you want to enable encryption only for specific property sources rather than the entire environment, add the jasypt-spring-boot dependency and use @EncryptablePropertySource or @EncryptablePropertySources on your Configuration classes. This supports YAML files as of version 1.8.

    <!-- Method 1: Starter dependency -->
    <dependency>
            <groupId>com.github.ulisesbocchio</groupId>
            <artifactId>jasypt-spring-boot-starter</artifactId>
            <version>4.0.4</version>
    </dependency>
    
    <!-- Method 2: Manual Configuration -->
    <dependency>
            <groupId>com.github.ulisesbocchio</groupId>
            <artifactId>jasypt-spring-boot</artifactId>
            <version>4.0.4</version>
    </dependency>
    
    @Configuration
    @EnableEncryptableProperties
    public class MyApplication {
        ...
    }
    
    <!-- Method 3: Granular Property Sources -->
    @Configuration
    @EncryptablePropertySource(name = "EncryptedProperties", value = "classpath:encrypted.properties")
    public class MyApplication {
        ...
    }
  8. Skip Specific PropertySource Classes

    master

    To prevent certain PropertySource classes from being introspected (wrapped/proxied) by the plugin, provide a comma-separated list of their fully-qualified class names using the jasypt.encryptor.skip-property-sources property. Properties contained in these classes will not be supported for encryption/decryption.

    jasypt.encryptor.skip-property-sources=org.springframework.boot.env.RandomValuePropertySource,org.springframework.boot.ansi.AnsiPropertySource
  9. Configure encrypted properties cache refresh events

    master

    By default, jasypt-spring-boot clears the encrypted properties cache when it detects specific Spring events (e.g., RefreshScopeRefreshedEvent, EnvironmentChangeEvent). If you use externalized configuration (like a Config Server) and need to trigger a cache invalidation using custom events, you can register them using the jasypt.encryptor.refreshed-event-classes property. Separate multiple event classes with a comma.

    jasypt.encryptor.refreshed-event-classes=org.springframework.boot.context.event.ApplicationStartedEvent
  10. Configure Custom Encrypted Property Prefix and Suffix

    master

    If you only need to change the prefix and suffix used to identify encrypted properties without implementing custom logic, you can override these settings directly in your application.properties or application.yml file.

    jasypt:
      encryptor:
        property:
          prefix: "ENC@["
          suffix: "]"
  11. Configure AES 256-GCM Encryption

    master

    As of version 3.0.5, AES 256-GCM encryption is supported using the AES/GCM/NoPadding algorithm. You can provide the secret key via a string, a file location, or a password.

    Using a Key:

    • Provide a Base64 encoded key via jasypt.encryptor.gcm-secret-key-string.
    • Or provide a location via jasypt.encryptor.gcm-secret-key-location (supports classpath:, file:, or relative paths).

    Using a Password:

    • Provide a password via jasypt.encryptor.gcm-secret-key-password.
    • Configure iterations via jasypt.encryptor.key-obtention-iterations (default: 1000).
    • Configure salt via jasypt.encryptor.gcm-secret-key-salt (Base64 format, default: none).
    • Configure algorithm via jasypt.encryptor.gcm-secret-key-algorithm (default: PBKDF2WithHmacSHA256).

    Customizing IV Generation:

    • Use jasypt.encryptor.iv-generator-classname to override the default RandomIvGenerator.
    ### Using a key
    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
    
    ### Using a password
    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"
  12. Configure Password-based Encryption

    master

    If no custom StringEncryptor bean is found in the Spring Context, jasypt-spring-boot automatically creates one. The only required configuration is the encryption password. For security, the password should be passed via system properties, command line arguments, or environment variables rather than being stored in a properties file.

    Use the key jasypt.encryptor.password to set the password. Other available configuration properties include algorithm, iterations, pool size, and more.