使用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

4 在k8s的deployment文件增加配置

containers:
        - name: asset-platform-backend
          image: 'harbor.dcos.ncmp.unicom.local/asset-platform-int/backend:12359'
          ports:
            - name: http
              containerPort: 8080
              protocol: TCP
          env:
            - name: SPRING_PROFILES_ACTIVE
              value: integration
            - name: JASYPT_ENCRYPTOR_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: jasypt-secret
                  key: jasypt-encryptor-password

 

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

导航