使用jasypt 和 k8s 避免项目中写数据库连接密码

0 引入jasypt

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

1 对原密码进行加密

public static String encrypt(String plaintext) {
        StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
        EnvironmentStringPBEConfig config = new EnvironmentStringPBEConfig();
        // 指定算法
        config.setAlgorithm("PBEWithMD5AndDES");
        // 指定秘钥,和yml配置文件中保持一致
        config.setPassword("LYgKTd24qx1y");
        encryptor.setConfig(config);
        // 生成加密数据
        return encryptor.encrypt(plaintext);
    }

2 改yaml文件中的数据库连接

使用ENC(...)包裹住上面的对原密码进行加密后的生成的字符串

spring:
  datasource:
    url: jdbc:mysql://a.b.c.d:3307/xxx?serverTimezone=Asia/Shanghai&characterEncoding=utf8&characterSetResults=utf8&autoReconnect=true&rewriteBatchedStatements=true
    username: uuuu
    password: ENC(XgPteMTzxA19SBE16zeqFgtXq2WuSB1LeEY4nr9wz2g=)

3 在k8中建secret

  对密钥进行base64加密

echo -n "LYgKTd24qx1y" | base64
TFlnS1RkMjRxeDF5

  

posted on 2024-06-07 18:18  MaXianZhe  阅读(1)  评论(0编辑  收藏  举报

导航