Saturday, 13 March 2021

How to encrypt passwords in a Spring Boot project using Jasypt

What is Jasypt?

Jasypt
 is a java library which allows the developer to add basic encryption capabilities to his/her projects with minimum effort, and without the need of having deep knowledge on how cryptography works. High-security, standards-based encryption techniques, both for unidirectional and bidirectional encryption.

Steps To Add Encryption Using Jasypt: 

1. 
Add maven dependency of jasypt: 
In the pom.xml file, add maven dependency which can be found easily at maven Repository.




2. Add annotation in the Spring Boot Application main Configuration class: 
@EnableEncryptableProperties annotation needs to be added to make the application understand the encryptable properties across the entire Spring Environment.





3. 
Decide a secret key to be used for encryption and decryption: 
The secret key is used to encrypt the password and later can be used to decrypt the encrypted value to get the actual password. You can choose any value as the secret key. Eg. abcdxyz

4. Generate Encrypted Key:
The encrypted key can be generated by using the Jasypt Online Tool.





5. Add the encrypted key in the config file (application.yml or application.properties): 
Now instead of adding the actual password ie. “123456” as per the above eg., you need to add the encrypted value generated by either of the above methods.
But how will the jasypt dependency understand that the particular property of the config file needs to be decrypted? Hence to make Jasypt aware of your encrypted values, it uses a convention which you need to add in the following format:

spring.datasource.password = ENC(1ZF5y+RzZc8m61cKHRt7vg==)

6. Secret key chosen needs to be passed to decrypt at runtime: 
Make the Jasypt aware of the secret key which you have used to form the encrypted value. 

Pass it as a property in the config file. Run the project as usual and the decryption would happen.


No comments:

Post a Comment