Best practices of encrypting the password for Spring Boot database

By | June 9, 2021

In our daily development, we may casually expose the database password directly in plaintext in the configuration file, which can be done in the development environment, but it is not recommended to do so in the production environment. After all, security is not trivial. No one knows which day the password is somehow leaked. Today we will talk about how to encrypt the database password in the spring boot project.

Database password encryption using druid database connection pooling

  • Introduce druid package into pom.xml. In order to facilitate other operations, we should directly introduce the starter of druid.
  • Use druid.filter.config.ConfigTools to generate public and private keys

There are two ways to generate it, one is generated by the command line, and the other is generated directly by writing a tool class. The examples in this post are directly generated using tool classes. The tool code is as follows:

public final class DruidEncryptorUtils {

    private static String privateKey;

    private static String publicKey;

    static {
        try {
            String[] keyPair = ConfigTools.genKeyPair(512);
            privateKey = keyPair[0];
            publicKey = keyPair[1];
        } catch (NoSuchAlgorithmException e) {
        } catch (NoSuchProviderException e) {

     * @param plaintext
     * @return
    public static String encode(String plaintext){
        System.out.println("Your password:" + plaintext);
        String ciphertext = ConfigTools.encrypt(privateKey,plaintext);
        System.out.println("Encrypted Password:" + ciphertext);
        return ciphertext;

     * Decipher
     * @param ciphertext
     * @return
    public static String decode(String ciphertext){
        System.out.println("Encrypted text:" + ciphertext);
        String plaintext = ConfigTools.decrypt(publicKey,ciphertext);
        System.out.println("text:" + plaintext);

        return plaintext;
  • Modify the content information of the configuration file of the database
  • Change password
  • Replace the password with the password generated by the tool class DruidEncryptorUtils

password: ${DATASOURCE_PWD:HB5FmUeAI1U81YJrT/T6awImFg1/Az5o8imy765WkVJouOubC2H80jqmZrr8L9zWKuzS/8aGzuQ4YySAkhywnA==)
b, filter open config

enabled: true
c, configure connectionProperties properties

connection-properties: config.decrypt=true;config.decrypt.key=${spring.datasource.publickey}