Skip to content

数据库密码加密

数据库密码加密的有两种方式

一、jasypt加密

1.1 引入pom包

        <!-- 数据库加密 -->
        <dependency>
            <groupId>com.github.ulisesbocchio</groupId>
            <artifactId>jasypt-spring-boot-starter</artifactId>
            <version>2.0.0</version>
        </dependency>

1.2 修改配置文件--盐值

jasypt:
  encryptor:
    #加盐--盐值
    password: salt_password

1.3 编写测试类

执行测试类,复制加密后的密码

@RunWith(SpringRunner.class)
@SpringBootTest
public class PasswordEncrypt {

    @Autowired
    StringEncryptor stringEncryptor;

    @Test
    public void encryptPwd(){
        System.out.println("-------------------jasypt加密-------------------");
        String result = stringEncryptor.encrypt("root");
        System.out.println("jasypt加密:" + result);
        System.out.println("-------------------jasypt加密-------------------");
    }
}

1.4 修改配置文件--密码

spring:
  datasource:
      password: ENC(AeX3+1M2Z1rTXEcs7eLGBg==)

二、druid加密

2.1 pom依赖

<!-- druid -->
<dependency>
  <groupId>com.alibaba</groupId>
  <artifactId>druid-spring-boot-starter</artifactId>
  <version>1.1.12</version>
</dependency>

2.2 编写测试类

执行一下方法,复制生成的公钥和密码

@Test
public void druidEncrypt() throws Exception{
    System.out.println("-------------------druid加密-------------------");
    //密码明文
    String password = "root";
    String[] keyPair = ConfigTools.genKeyPair(512);
    //私钥
    String privateKey = keyPair[0];
    //公钥
    String publicKey = keyPair[1];

    //用私钥加密后的密文
    password = ConfigTools.encrypt(privateKey,password);

    System.out.println("privateKey:" + privateKey);
    System.out.println("publicKey:" + publicKey);
    System.out.println("password:" + password);

    String decryptPassword = ConfigTools.decrypt(publicKey,password);
    System.out.println("解密后:" + decryptPassword);
    System.out.println("-------------------druid加密-------------------");
}

2.3 修改配置文件

增加或修改以下配置文件

public-key: MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAJf/4GX3DKon3Z52Px8j+hbgFTEFITVly7ZEoqiqoB1G6fwaAlsRfLRO4wZEQ8E7ObWhhNJbGkUzabxkjeDlbEkCAwEAAQ==
spring:
  datasource:
    druid:
      password: bnAcU9DVhnQKKpVPzf2MbJUoI213wGv/fTtkMDp46dp1An7hBWLMM80GUm3BZYIhsoBj7DmZEfdMF+zSxM6ZTQ==
      connection-properties: config.decrypt=true;config.decrypt.key=${public-key}
      filter:
        config:
          enabled: true