Jasypt整合springboot完成对配置文件中有关敏感数据的加密

场景

项目中有很多密码都是以明文的形式存储在配置文件中,这样很不安全。我们可以通过jasypt来完成敏感信息的加密。

步骤

1、pom文件引入依赖。

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

2、写个测试类获取密文。

        String secret = "haha";
        BasicTextEncryptor basicTextEncryptor = new BasicTextEncryptor();
        basicTextEncryptor.setPassword(secret); //设置密钥
        String s = basicTextEncryptor.encrypt("123456"); //加密
        System.out.println(s);

3、application.yml文件写死密文。

# Spring配置
spring:
  # 数据源配置
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/test?characterEncoding=utf-8&&serverTimezone=Asia/Shanghai&&useSSL=false
    username: root
    # 此处的密文要用ENC()进行包裹,不然是识别不了的,自然也就无法解密
    password: ENC(fUaD/g4L9TKx8AFhz8A5qQ==)

# 加密配置
jasypt:
  encryptor:
    # 指定密钥
    password: haha
    # 下面这两个参数必须得加,不加的话会报参数绑定异常
    # 指定解密算法,需要和加密时使用的算法一致
    algorithm: PBEWithMD5AndDES
    # 指定initialization vector类型
    iv-generator-classname: org.jasypt.iv.NoIvGenerator

线上环境

如果是线上环境,密钥需作为启动参数加进去,这样更安全。

java -jar -Djasypt.encryptor.password=your-secret
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在Spring Boot应用程序使用Jasypt进行配置文件加密和解密,可以按照以下步骤进行操作: 1. 添加Jasypt依赖项 在pom.xml文件添加以下依赖项: ```xml <dependency> <groupId>com.github.ulisesbocchio</groupId> <artifactId>jasypt-spring-boot-starter</artifactId> <version>{jasypt-version}</version> </dependency> ``` 其,{jasypt-version}是Jasypt版本号,可以根据需要进行修改。 2. 配置加密密码 在application.properties或者application.yml文件添加以下配置: ``` jasypt.encryptor.password=your_password ``` 其,your_password是你用来加密和解密配置文件的密码。 3. 加密配置文件 使用Jasypt提供的命令行工具,对需要加密配置文件进行加密。例如,对application.yml进行加密,可以使用以下命令: ``` java -cp jasypt-{jasypt-version}.jar org.jasypt.intf.cli.JasyptPBEStringEncryptionCLI input="your_plaintext_config" password="your_password" algorithm=PBEWithMD5AndDES ``` 其,your_plaintext_config是明文配置文件,your_password是加密密码,algorithm是加密算法。 加密后的配置文件应该包含ENC()前缀,例如: ``` spring: datasource: url: jdbc:mysql://localhost:3306/mydb?serverTimezone=UTC username: ENC(6kInJ6wB1JQqGz6Z7Qv+Q2z3Oc1k1f1+) password: ENC(Az7+0fJEWfDfPQXa/3GvZQ==) ``` 4. 解密配置文件 Spring Boot应用程序启动时,Jasypt会自动解密加密配置文件。因此,无需做任何额外的配置。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值