Encrypting Spring Boot Configuration with Jasypt and a Custom EnvironmentPostProcessor
This guide demonstrates how to secure Spring Boot configuration values by using Jasypt encryption and a custom EnvironmentPostProcessor with RSA, covering Maven dependencies, property setup, encrypted YAML syntax, utility classes, processor implementation, and registration via spring.factories.
First Method – Jasypt Encryption
Add the appropriate Maven dependency for the Jasypt starter. The version differs between Spring Boot 1.x (2.0.0) and 2.x (3.0.3):
com.github.ulisesbocchio
jasypt-spring-boot-starter
2.0.0
com.github.ulisesbocchio
jasypt-spring-boot-starter
3.0.3Configure the encryption password in the configuration center (or pass it as a JVM argument):
jasypt.encryptor.password=henghe # encryption keyReplace sensitive values in application.yml with the ENC(...) format, for example:
password: ENC(tnJpIM6iACWO/wRI//7XsbBqy/Mpx6MG1hXe4S7U4cNWmGhajnUSeXmBmQiniKEU)Spring Boot will automatically detect and decrypt these values at startup. A test class JasyptUtils is provided to encrypt and decrypt strings:
import org.jasypt.encryption.pbe.PooledPBEStringEncryptor;
import org.jasypt.encryption.pbe.StandardPBEByteEncryptor;
import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig;
public class JasyptUtils {
public static String encryptPwd(String password, String value) {
PooledPBEStringEncryptor encryptOr = new PooledPBEStringEncryptor();
encryptOr.setConfig(cryptOr(password));
return encryptOr.encrypt(value);
}
public static String decyptPwd(String password, String value) {
PooledPBEStringEncryptor encryptOr = new PooledPBEStringEncryptor();
encryptOr.setConfig(cryptOr(password));
return encryptOr.decrypt(value);
}
public static SimpleStringPBEConfig cryptOr(String password) {
SimpleStringPBEConfig config = new SimpleStringPBEConfig();
config.setPassword(password);
config.setAlgorithm(StandardPBEByteEncryptor.DEFAULT_ALGORITHM);
config.setKeyObtentionIterations("1000");
config.setPoolSize("1");
config.setProviderName(null);
config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator");
config.setStringOutputType("base64");
return config;
}
public static void main(String[] args) {
System.out.println(encryptPwd("EbfYkitulv73I2p0mXI50JMXoaxZTKJ7", "root@1234"));
}
}Second Method – Custom EnvironmentPostProcessor
From Spring Boot 1.3 onward, EnvironmentPostProcessor can modify the environment before the application context is refreshed. Implement this interface to decrypt encrypted properties such as the datasource password.
Utility class RSAEncryptDecrypt provides RSA encryption/decryption using Base64‑encoded keys:
package com.yss.henghe.iris.configuration;
import java.util.Base64;
import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
public class RSAEncryptDecrypt {
private static String publicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqfkYJn8BHttyGrQYcoXTZK8Za" +
"MVUkqhEdFIyWZhnUQz6Jr299IkBCrbTnKcQTn3ekyQl5/F+j2p8YuNQDBJiq46T/srI+zh1XIaTIKJoOI8M4ploKOztJ8IP" +
"L9ucdnv/tEdGDD9kY5JILa5DQnem9HkaS55kGJX6Oet6CRiNekwiG4+K61SjyfqxuLcqm7v2gH2nvTnkci9FLwtErpdF4uT" +
"Mv6LB46Z9Hpg5iVsHDbwnwqOCfirgwdalJQTy+jcn9UqqNTsneREOxTtt9JQEnsDE/4UIPAYiU6cQDRJ5YrXR56LYC/0g55" +
"KpMVnMIJgS5Y/YVt66QHtUTCVmmSgxAQIDAQAB";
private static String privateKey = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCp+..."; // truncated for brevity
public static byte[] encrypt(byte[] str, String publicKey) throws Exception {
byte[] decoded = Base64.getDecoder().decode(publicKey);
RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
return cipher.doFinal(str);
}
public static byte[] decrypt(byte[] str) throws Exception {
byte[] decoded = Base64.getDecoder().decode(privateKey);
RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, priKey);
return cipher.doFinal(str);
}
public static void main(String[] args) throws Exception {
byte[] message = "1q2w3eROOT!".getBytes();
byte[] encrypted = encrypt(message, publicKey);
String base64 = new String(Base64.getEncoder().encode(encrypted));
System.out.println("Encrypted Base64: " + base64);
byte[] decoded = Base64.getDecoder().decode(base64);
byte[] decrypted = decrypt(decoded);
System.out.println("Decrypted: " + new String(decrypted));
}
}The processor SafetyEncryptProcessor reads the encrypted datasource password, decrypts it using the RSA utility, and injects the plain value back into the environment:
package com.yss.henghe.iris.configuration;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.env.*;
import java.util.*;
public class SafetyEncryptProcessor implements EnvironmentPostProcessor {
public static final String SPRING_DATASOURCE_PASSWORD = "spring.datasource.password";
public static final String PASSWORD_ENABLE_ENCRYPT = "password.enable.encrypt";
public static final String TRUE = "true";
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
String enableEncrypt = environment.getProperty(PASSWORD_ENABLE_ENCRYPT);
if (TRUE.equals(enableEncrypt)) {
String password = environment.getProperty(SPRING_DATASOURCE_PASSWORD);
Properties properties = new Properties();
byte[] decode = Base64.getDecoder().decode(password);
byte[] messageDe = new byte[0];
try {
messageDe = RSAEncryptDecrypt.decrypt(decode);
} catch (Exception e) { }
properties.setProperty(SPRING_DATASOURCE_PASSWORD, new String(messageDe));
PropertiesPropertySource pps = new PropertiesPropertySource(SPRING_DATASOURCE_PASSWORD, properties);
environment.getPropertySources().addFirst(pps);
}
}
}Register the processor in META-INF/spring.factories :
org.springframework.boot.env.EnvironmentPostProcessor=\
com.yss.henghe.iris.configuration.SafetyEncryptProcessorFinally, a Maven dependency for datax-core is shown to generate RSA key pairs, and a simple main method prints the generated public and private keys.
Source: blog.csdn.net/weixin_42728895/article/details/121731571
Selected Java Interview Questions
A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.