It may happen, for whatever reason, that you must store credentials in your project. You could store the plain text credentials in your code repository, but this would allow everybody with access to the repository to use these credentials. Therefore, you should avoid this. Fortunately Spring has a solution for that and allows properties to be encrypted.
To show this by an example, I created a small application which returns the value of a decrypted property via a REST interface. The encryption of the properties is not part of the code, I will do this with Spring Boot CLI. As a start I created a new project at https://start.spring.io/ with the following dependencies:
Spring cannot decrypt the property, because the decryption key is still missing. You have to provide the key via the property
encrypt.key. As mentioned above, we still do not want to add a plain text password (the decryption key) to the file application.properties, because then it would be added to the code repository and this would finally lead the whole concept to absurdity. We need another way to provide the decryption key.: Spring can not only read property values from a properties file, you can also use environment variables. Therefore, I provide the key as an environment variable:
As a result, it is now possible to start the application and call the endpoint to receive the decrypted property:
As expected, this returns “mysecret” which is the decrypted value of the property.
In a real world example you wouldn’t start the application manually and provide the key as shown above. To automate this process, you can add the encryption key to your deployment infrastructure, and let it start the application with the key as an environment variable. In this way you can start the application, but you do not have to store the decryption key in the code repository.
A criticism of this approach could be that it is easier to provide the password directly as an environment variable instead of first encrypting it and then providing the decryption key. Since with both approaches you have to provide one environment variable. At least when there is more than one password, you will see the advantage of encrypted properties, because you have to set only one environment variable, independent of the number of passwords.
In this example I showed how to encrypt and decrypt properties with Spring without any additional infrastructure. With the help of encrypted property you can add credentials to property files without worrying that someone with access to your code repository is able to misuse them, because the decryption key is not stored in the code repository.
If you want to switch to Spring Cloud Config at any later date, it is also possible, because the encryption and decryption of properties in Spring Cloud Config Server work exactly the same.