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

场景

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

步骤

1、pom文件引入依赖。

xml 复制代码
<dependency>
    <groupId>com.github.ulisesbocchio</groupId>
    <artifactId>jasypt-spring-boot-starter</artifactId>
    <version>3.0.4</version>
</dependency>

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

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

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

yaml 复制代码
# 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

线上环境

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

powershell 复制代码
java -jar -Djasypt.encryptor.password=your-secret
相关推荐
贾斯汀玛尔斯7 小时前
每天学一个算法--LSM-Tree(Log-Structured Merge Tree)
java·算法·lsm-tree
bitt TRES7 小时前
springboot与springcloud对应版本
java·spring boot·spring cloud
Y001112367 小时前
JavaWeb-end
java·servlet·web
万少8 小时前
Vibe Coding不停歇,移动端 TRAE SOLO 让你用手机也能编程啦
前端·javascript·后端
bzmK1DTbd8 小时前
Git版本控制:Java项目中的分支管理与合并策略
java·开发语言·git
Rust研习社8 小时前
为什么 Rust 没有空指针?
开发语言·后端·rust
皮皮林5518 小时前
全网最全的 Jenkins + Maven + Git 自动化部署指南!
后端
舒一笑8 小时前
用几十行代码搞定 Chat 接口透明转发:跨环境轻量级网关实战
后端·程序员·架构
铁皮饭盒9 小时前
成为AI全栈 - 第3课:路由 RESTful Elysia 状态码 设计规范
前端·后端·全栈
我叫黑大帅10 小时前
如何通过 Python 实现招聘平台自动投递
后端·python·面试