Secure Passwords In a Spring Boot Project Using Jasypt

Jasypt is a Java library which provides us to add basic encryption capabilities to projects with minimum effort and without writing any code !! 😀

let's see how we can do that…

Steps To Add Encryption Using Jasypt :

  1. Add Dependency in your pom.xml
  2. Add annotation in the Spring Boot Application main Configuration class
  3. Select a secret key to be used for encryption and decryption
  4. Generate Encrypted Key
  5. Add the encrypted key in the config file (application.properties)

1. Add Dependency in your pom.xml

In your pom.xml file add maven dependency which is easily available at maven repository. Here I am using 2.1.0 version of it.

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

2. Add annotation in the Spring Boot Application main Configuration class

@EnableEncryptableProperties annotation needs to add your main configuration class. So spring boot can enable encryptable properties in the whole application.

@Configuration
@EnableEncryptableProperties
public class MyProject {

}

3. Select a secret key to be used for encryption and decryption

The secret key is used to encrypt and descript the password, so can you use any parameter. Mentioned that secret key in application.properties.

jasypt.encryptor.password=myprojectsecretKey

4. Generate Encrypted Key

By using jasypt jar you can do encryption here so download the jar from maven repository(https://github.com/jasypt/jasypt). Go to location of jar file in the command line and run below command.
Please make sure your jar path is the correct one and use same secret key that you have entered in applciation.properties.

java -cp jasypt-1.9.2.jar org.jasypt.intf.cli.JasyptPBEStringEncryptionCLI input=”your_password” password=myprojectsecretKey algorithm=PBEWithMD5AndDES
Generated encrypted key

Here is the meaning of used parameter

input: It the password which you want to encrypt or hide. (your_password)
password: It is the secret key which is mentioned in application.properties and chosen by us.(myprojectsecretKey)
algorithm: It is the encryption algorithm used( PBEWithMD5AndDES).

5. Add the encrypted key in the config file (application.properties)

The simplest and most convenient way is to add the above generated encrypted key in application.properties as below.
Placed encrypted key inside ENC brackets as ENC(<encrypted key>)

spring.datasource.mydatabase.password=ENC(vhnKrz7YdptHHbGB9HDMLZdwHiXZ66xa)

Spring boot will automatically decrypt it when you start the application.
You can use same secret key decrypt the password!

Run the application as usual …

🙌 Thanks for reading, hope it helps you 🙌

Love Programming and Writing, Software Engineer, Pune