数据库密码配置加密

本文介绍了如何在SpringBoot项目中使用Jasypt库对数据库密码进行加密,提供了三种不同的配置方法,包括直接配置、启动参数和脚本启动时输入密文,以增强密码安全性。

📌为避免配置文件直接密码明文配置,可能存在泄漏,引入密文来加密明文密码

项目文件引入依赖

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

找到对应加密jar对明文密码进行加密

例如密钥为test123

数据库密码为123456

进入jar包所在目录1,打开控制台,注意jar包版本号,这里使用的是1.9.2

加密密码使用java -cp jasypt-1.9.2.jar org.jasypt.intf.cli.JasyptPBEStringEncryptionCLI input="123456" password=test123 algorithm=PBEWithMD5AndDES

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

解密密码使用java -cp jasypt-1.9.2.jar org.jasypt.intf.cli.JasyptPBEStringDecryptionCLI input="KAxsns3B73FWeryPWVfpGg==" password=test123 algorithm=PBEWithMD5AndDES

在这里插入图片描述

项目配置文件修改

spring:
  datasource:
    driver-class-name: com.p6spy.engine.spy.P6SpyDriver
    url: jdbc:p6spy:postgresql://127.0.0.1:5432/postgres?currentSchema=public
    username: postgres
    password:  ENC(KAxsns3B73FWeryPWVfpGg==)

修改passwod处密码为上面输出的加密密码即可


密钥配置启动

方式一、直接在配置文件中配置

jasypt:
  encryptor:
    password: test123

这样配置密文简单粗暴,容易被暴露,原密码便可以被解密出来

方式二、启动参数配置

  • 本地项目增加如图配置项–jasypt.encryptor.password=test123
    在这里插入图片描述

  • 线上运行jar时,java -jar -Djasypt.encryptor.password=test123 project.jar

这样配置相比第一种不易暴露,但这些启动参数是可以通过查看进程信息,密文会明文显示出来,原密码便可以被解密出来

方式三、脚本启动时手动输入

思路:脚本启动服务时,手动输入密文,并保存到临时文件,springboot初始化时读取该密文到内存中,脚本再删除临时文件。

这种方式相对于前面两种,密文暴露的可能性就极低了,因为密文是直接保存在内存中的

脚本

#!/bin/bash

echo "please input jasypt.encryptor.password: "

read encryption

echo "${encryption}" > /tmp/encryption.tmp

nohup java -jar project.jar >/dev/null 2>&1 &

sleep 10

rm -rf /tmp/encryption.tmp

启动类

@SpringBootApplication
@EnableScheduling
public class MyDemoApplication {
    private static final String TMP_ENCRYPTION_PATH = "/tmp/encryption.tmp";
    private static final String JASYPT_ENCRYPTOR_PASSWORD = "jasypt.encryptor.password";

    public static void main(String[] args) throws Exception {
        SpringApplication app = new SpringApplication(MyDemoApplication.class);
        app.setDefaultProperties(
                MapUtil.of(
                        JASYPT_ENCRYPTOR_PASSWORD,
                        FileUtil.readLine(new RandomAccessFile(new File(TMP_ENCRYPTION_PATH), "r"), Charset.defaultCharset())
                )
        );
        app.run(args);
    }
}

  1. 全局搜索JasyptPBEStringEncryptionCLI类即可找到对应jar ↩︎

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值