0% found this document useful (0 votes)
5 views

SpringBoot_DB_Password_Encryption_using_CastleBouncy

This document outlines a Spring Boot project that demonstrates how to encrypt and decrypt a database password using the Bouncy Castle library. It details the project structure, including configuration files and utility classes, and provides steps to run the application along with security notes and enhancements for managing encryption keys. The AES algorithm is used for encryption, and it emphasizes the importance of keeping sensitive information secure.

Uploaded by

newsletter
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

SpringBoot_DB_Password_Encryption_using_CastleBouncy

This document outlines a Spring Boot project that demonstrates how to encrypt and decrypt a database password using the Bouncy Castle library. It details the project structure, including configuration files and utility classes, and provides steps to run the application along with security notes and enhancements for managing encryption keys. The AES algorithm is used for encryption, and it emphasizes the importance of keeping sensitive information secure.

Uploaded by

newsletter
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

Spring Boot with Bouncy Castle Encryption

Overview
This project demonstrates how to encrypt and decrypt a database password using the Bouncy Castle
library in a Spring Boot application. The encrypted password is stored in the application.properties file and
decrypted at runtime using a key provided in a separate file.

Project Structure

- `application.properties`: Contains the encrypted password and path to the encryption key.
spring.datasource.url=jdbc:mysql://localhost:3306/testdb
spring.datasource.username=root
spring.datasource.password=ENC(6Vuz3rMTnP8=)
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
encryption.key.path=classpath:key.txt

- `key.txt`: Holds the encryption key used for AES.


my-secret-key-1234

- `EncryptionUtil.java`: Utility class that handles encryption and decryption logic.


import org.bouncycastle.jce.provider.BouncyCastleProvider;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.Security;
import java.util.Base64;

public class EncryptionUtil {


static {
Security.addProvider(new BouncyCastleProvider());
}

private static final String ALGORITHM = "AES";

public static String encrypt(String plainText, String key) throws Exception {


SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM, "BC");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encrypted = cipher.doFinal(plainText.getBytes());
return Base64.getEncoder().encodeToString(encrypted);
}

public static String decrypt(String encryptedText, String key) throws Exception {


SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM, "BC");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decrypted = cipher.doFinal(Base64.getDecoder().decode(encryptedText));
return new String(decrypted);
}
}

- `PasswordDecryptionConfig.java`: Reads and decrypts the password during application startup.


import com.example.security.EncryptionUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct;
import java.nio.file.Files;
import java.nio.file.Paths;

@Configuration
public class PasswordDecryptionConfig {
@Value("${spring.datasource.password}")
private String encryptedPassword;
@Value("${encryption.key.path}")
private String keyPath;
private String decryptedPassword;

public String getDecryptedPassword() {


return decryptedPassword;
}
@PostConstruct
public void decryptPassword() {
try {
String key = new
String(Files.readAllBytes(Paths.get(getClass().getClassLoader().getResource("key.txt").toURI())));
String password = encryptedPassword.replace("ENC(", "").replace(")", "");
this.decryptedPassword = EncryptionUtil.decrypt(password, key);
} catch (Exception e) {
throw new RuntimeException("Failed to decrypt DB password", e);
}
}
}

- `DataSourceConfig.java`: Configures the datasource with the decrypted password.


import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;

@Configuration
public class DataSourceConfig {
@Autowired
private PasswordDecryptionConfig passwordDecryptionConfig;
@Value("${spring.datasource.url}")
private String dbUrl;
@Value("${spring.datasource.username}")
private String dbUsername;
@Value("${spring.datasource.driver-class-name}")
private String driverClassName;

@Bean
public DataSource dataSource() {
return DataSourceBuilder.create()
.driverClassName(driverClassName)
.url(dbUrl)
.username(dbUsername)
.password(passwordDecryptionConfig.getDecryptedPassword())
.build();
}
}

- `pom.xml`: Includes Bouncy Castle and MySQL dependencies.

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk18on</artifactId>
<version>1.80</version>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>

Encryption Algorithm
AES algorithm from Bouncy Castle is used. Encrypted passwords are Base64 encoded.

Steps to Run
1. Open the project in your IDE (like IntelliJ or Eclipse).

2. Set up a MySQL database named `testdb`.

3. Use the key from `key.txt` to encrypt your password and update `application.properties`.

4. Run the `DemoApplication` class.


Encryption Example
Use the `EncryptionUtil.encrypt()` method in a simple main method to generate encrypted passwords.

public class EncryptPasswordMain {


public static void main(String[] args) throws Exception {
String key = "my-secret-key-1234";
String plainPassword = "your-db-password";
String encrypted = EncryptionUtil.encrypt(plainPassword, key);
System.out.println("Encrypted: " + encrypted);
}
}

Security Note
Never commit `key.txt` or decrypted passwords to source control. Keep them secure.

Enhancement
We can even fetch the secret key from an environment variable instead of file.

1. Set the environment variable in your OS or run configuration:

set ENCRYPTION_SECRET_KEY=my-secret-key-1234

2. Update application.properties:

encryption.secret.key=${ENCRYPTION_SECRET_KEY}

3. Modify PasswordDecryptionConfig.java:
@Configuration
public class PasswordDecryptionConfig {

@Value("${spring.datasource.password}")
private String encryptedPassword;

@Value("${encryption.secret.key}")
private String secretKey;

private String decryptedPassword;

public String getDecryptedPassword() {


return decryptedPassword;
}

@PostConstruct
public void decryptPassword() {
try {
String password = encryptedPassword.replace("ENC(", "").replace(")", "");
this.decryptedPassword = EncryptionUtil.decrypt(password, secretKey);
} catch (Exception e) {
throw new RuntimeException("Failed to decrypt DB password", e);
}
}
}

If you want the secret key to persist and be accessible across sessions or reboots, you should set it
through System Environment Variables in Windows.

✅ How to Set ENCRYPTION_SECRET_KEY in Windows Environment Variables

For current user only:

1. Press Win + S and type "Environment Variables".


2. Click “Edit the system environment variables”.
3. In the System Properties dialog, click “Environment Variables…”.
4. Under User variables, click New.
5. Enter:
o Variable name: ENCRYPTION_SECRET_KEY
o Variable value: your-secret-key-here
6. Click OK on all dialogs.
For all users (System-wide):

Follow the same steps but add it under System variables instead.

🔁 After Setting:

 Restart your IDE or terminal to ensure the environment variable is picked up.
 Spring Boot will now resolve ${ENCRYPTION_SECRET_KEY} in application.properties.

🧪 To verify:

Run this in a terminal:

echo %ENCRYPTION_SECRET_KEY%

And in Java:

System.out.println(System.getenv("ENCRYPTION_SECRET_KEY"));
Modify PasswordDecryptionConfig.java:

package com.example.demo.config;

import com.example.demo.util.EncryptionUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

@Configuration
public class PasswordDecryptionConfig {

@Value("${spring.datasource.password}")
private String encryptedPassword;

private String decryptedPassword;

public String getDecryptedPassword() {


return decryptedPassword;
}

@PostConstruct
public void decryptPassword() {
try {
// Fetch the secret key from environment variables
String secretKey = System.getenv("ENCRYPTION_SECRET_KEY");

if (secretKey == null || secretKey.isEmpty()) {


throw new IllegalStateException("Environment variable ENCRYPTION_SECRET_KEY is not set.");
}

String password = encryptedPassword.replace("ENC(", "").replace(")", "");


this.decryptedPassword = EncryptionUtil.decrypt(password, secretKey);
} catch (Exception e) {
throw new RuntimeException("Failed to decrypt DB password", e);
}
}
}

You might also like