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
相关推荐
YDS82914 小时前
DeepSeek RAG&MCP + Agent智能体项目 —— 集成ELK日志管理系统和Prometheus监控系统
java·elk·ai·springboot·agent·prometheus·deepseek
骄马之死21 小时前
SpringMVC + SpringBoot 核心知识点总结
java·spring boot·后端
GoGeekBaird1 天前
Anthropic技能"(Skills)的经验分享
后端
王码码20351 天前
多台服务器怎么统一看状态?Beszel 轻量监控,搭起来不费事
运维·服务器·后端·安全·阿里云·接口·web
郑洁文1 天前
基于Spring Boot的流浪动物救助网站
java·spring boot·后端·毕设·流浪动物救助
螺丝钉code1 天前
JAVA项目 Claude code CLAUDE.md 到底应该怎么写
java·人工智能·claude code
指令集梦境1 天前
Cursor + Spring Boot实战:从零写一个RESTful API
spring boot·后端·restful
摇滚侠1 天前
Maven 入门+高深 单一架构案例 54-59
java·架构·maven·intellij-idea
VidDown1 天前
Webhook 调试器:让第三方回调“原形毕露”
java·开发语言·javascript·编辑器·postman
码云之上1 天前
聊聊如何设计一个高效、稳定的 Node.js 接入层
前端·后端·node.js