Wednesday, May 27, 2015

Spring Boot & Jasypt easy: Keep your sensitive properties encrypted


Goal


I want to store my database password encrypted in the application properties file and provide the property encryption password at runtime as java system property or environment variable.

Context:


Java 7, Spring Boot 1.2.3.RELEASE
Currently Spring Boot does not offer native property encryption support.

Solution


Use jasypt encryption library and integrate it into Spring Boot's configuration flow.

How?
Here is a quick and dirty example:

1. Download jasypt and unzip the contents in a folder;
2. Choose a password for encrypting your sensitive properties; for the purpose of this example we choose "my-encryption-password";
3. Choose the property you want encrypted; here we choose to encrypt the database password "my-database-password";
4. Encrypt the database password ("my-database-password") using jasypt and the encryption password ("my-encryption-password"); go into the jasypt bin folder and run:

$ encrypt.sh  input=my-database-password password=my-encryption-password

----ENVIRONMENT-----------------

Runtime: Oracle Corporation Java HotSpot(TM) 64-Bit Server VM 24.60-b09

----ARGUMENTS-------------------

input: my-database-password

password: my-encryption-password

----OUTPUT----------------------

TJ1vA+DLWFrwEmbZKmGmawEonbJw4DxhkFf53JzKfvY=

The output is the encrypted password.
To configure the database in the SpringBoot's application.properties we add:

#for this example we use H2 database
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.url=jdbc:h2:mem:my-schema
spring.datasource.username=test-user

#here we provide the database encrypted password by enclosing in ENC()
#so that jasypt can detect and decrypt it
spring.datasource.password=ENC(TJ1vA+DLWFrwEmbZKmGmawEonbJw4DxhkFf53JzKfvY=)


Integrating Spring Boot and Jasypt


In order to instruct Spring Boot to transparently interpret our property file and extract and decrypt the encrypted properties we need to:

1. Create a PropertySourceLoader implementation that knows how to parse property files, identify encrypted properties and decrypt them before making them available to other components. Also the class knows to get the encryption password from system properties (provided at command line by -Dproperty.encryption.password=my-encryption-password) or as an environment variable in the operating system (export PROPERTY_ENCRYPTION_PASSWORD="my-encryption-password"). Listing follows:
package com.myexample;

import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
import org.jasypt.spring31.properties.EncryptablePropertiesPropertySource;
import org.springframework.boot.env.PropertySourceLoader;
import org.springframework.core.PriorityOrdered;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;

import java.io.IOException;
import java.util.Properties;


/**
 * This class is a replacement for the default Spring PropertySourceLoader. It has the capability of detecting
 * and decrypting encrypted properties via Jasypt Encryption Library.
 * The decryption password must be provided via an environment variable or via a System property. The name of the property can be {@code PROPERTY_ENCRYPTION_PASSWORD} or {@code property.encryption.password}.
 * For more information see http://www.jasypt.org/ and http://www.jasypt.org/spring31.html
 * For Spring Boot integration the default {@link PropertySourceLoader} configuration was overriden by
 * META-INF/spring.factories file.
 *
 * @see org.springframework.boot.env.PropertySourceLoader
 */

public class EncryptedPropertySourceLoader implements PropertySourceLoader, PriorityOrdered {

    private static final String ENCRYPTION_PASSWORD_ENVIRONMENT_VAR_NAME_UNDERSCORE = "PROPERTY_ENCRYPTION_PASSWORD";
    private static final String ENCRYPTION_PASSWORD_ENVIRONMENT_VAR_NAME_DOT = "property.encryption.password";
    private static final String ENCRYPTION_PASSWORD_NOT_SET = "ENCRYPTION_PASSWORD_NOT_SET";

    private final StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();

    public EncryptedPropertySourceLoader() {
        this.encryptor.setPassword(getPasswordFromEnvAndSystemProperties());
    }

    private String getPasswordFromEnvAndSystemProperties() {
        String password = System.getenv(ENCRYPTION_PASSWORD_ENVIRONMENT_VAR_NAME_UNDERSCORE);
        if (password == null) {
            password = System.getenv(ENCRYPTION_PASSWORD_ENVIRONMENT_VAR_NAME_DOT);
            if (password == null) {
                password = System.getProperty(ENCRYPTION_PASSWORD_ENVIRONMENT_VAR_NAME_UNDERSCORE);
                if (password == null) {
                    password = System.getProperty(ENCRYPTION_PASSWORD_ENVIRONMENT_VAR_NAME_DOT);
                    if (password == null) {
                        password = ENCRYPTION_PASSWORD_NOT_SET;
                    }
                }
            }
        }
        return password;
    }

    @Override
    public String[] getFileExtensions() {
        return new String[]{"properties"};
    }

    @Override
    public PropertySource load(final String name, final Resource resource, final String profile) throws
            IOException {
        if (profile == null) {
            //load the properties
            final Properties props = PropertiesLoaderUtils.loadProperties(resource);

            if (!props.isEmpty()) {
                //create the encryptable properties property source
                return new EncryptablePropertiesPropertySource(name, props, this.encryptor);
            }
        }

        return null;
    }

    @Override
    public int getOrder() {
        return HIGHEST_PRECEDENCE;
    }
}

2. Create a com/myexample/META_INF/spring.factories file to override the default PropertyResurceLoader (org.springframework.boot.env.PropertiesPropertySourceLoader) which is provided with the Spring Boot distribution in META-INF/spring.factories. Our file should contain one line as follows:
org.springframework.boot.env.PropertySourceLoader=com.myexample.EncryptedPropertySourceLoader

That's it! Now your application should be able to use encrypted properties.

Thanks for reading!
Dikran

To give the right credits, info that helped me solving the problem and writing this post were gathered from this Stackoverflow post.