Jasypt 与 Spring Boot 集成文档

news/2025/3/5 7:40:12/

Jasypt 与 Spring Boot 集成文档

目录

  1. 简介
  2. 版本说明
  3. 快速开始
    • 添加依赖
    • 配置加密密钥
    • 加密配置文件
  4. 高级配置
    • 自定义加密算法
    • 多环境配置
  5. 最佳实践
  6. 常见问题
  7. 参考资料

简介

Jasypt 是一个简单易用的 Java 加密库,支持与 Spring Boot 无缝集成。通过 Jasypt,可以轻松加密和解密 Spring Boot 配置文件中的敏感信息(如数据库密码、API 密钥等),从而提高应用的安全性。


版本说明

支持版本

  • JDK 版本:JDK 1.8 及以上。
  • Spring Boot 版本:Spring Boot 2.x(推荐 2.5.6 及以上)。
  • Jasypt 版本jasypt-spring-boot-starter 3.x(推荐 3.0.5 及以上)。

版本区间建议

组件推荐版本备注
JDK1.8 或 11JDK 1.8 是主流选择,JDK 11 支持长期维护。
Spring Boot2.5.6 - 2.7.xSpring Boot 2.x 是稳定版本。
Jasypt3.0.5最新稳定版本,兼容 Spring Boot 2.x。

快速开始

添加依赖

在 Spring Boot 项目中,添加 jasypt-spring-boot-starter 依赖:

Maven

pom.xml 中添加以下依赖:

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

build.gradle 中添加以下依赖:

implementation 'com.github.ulisesbocchio:jasypt-spring-boot-starter:3.0.5'

配置加密密钥

Jasypt 需要一个加密密钥来加密和解密数据。密钥可以通过以下方式配置:

1. 在 application.yml 中配置(这个写在数据库配置的上面)
jasypt:encryptor:# 盐值password: vilasto# 指定加密方式algorithm: PBEWithSHA1AndRC2_40iv-generator-classname: org.jasypt.iv.NoIvGeneratorproperty:# 标识为加密属性的前缀prefix: ENC(# 标识为加密属性的后缀suffix: )

加密配置文件

1. 加密敏感数据

使用 Jasypt 提供的工具加密敏感数据。以下是一个示例:

java">import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
import org.jasypt.encryption.pbe.config.EnvironmentPBEConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;public class JasyptUtil {private static final Logger logger = LoggerFactory.getLogger(JasyptUtil.class);/*** PBE 算法*/public static final String PBE_ALGORITHMS_MD5_DES = "PBEWithMD5AndDES";public static final String PBE_ALGORITHMS_MD5_TRIPLEDES = "PBEWithMD5AndTripleDES";public static final String PBE_ALGORITHMS_SHA1_DE_SEDE = "PBEWithSHA1AndDESede";public static final String PBE_ALGORITHMS_SHA1_RC2_40 = "PBEWithSHA1AndRC2_40";/*** Jasypt 加密** @param encryptedStr 加密字符串* @param algorithm    加密算法* @param password     盐值* @return*/public static String encrypt(String encryptedStr, String algorithm, String password) {StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();EnvironmentPBEConfig config = new EnvironmentPBEConfig();// 指定加密算法config.setAlgorithm(algorithm);// 加密盐值config.setPassword(password);config.setIvGeneratorClassName("org.jasypt.iv.NoIvGenerator");encryptor.setConfig(config);// 加密return encryptor.encrypt(encryptedStr);}/*** Jasypt 解密** @param decryptStr 解密字符串* @param algorithm  指定解密算法:解密算法要与加密算法一一对应* @param password   盐值* @return*/public static String decrypt(String decryptStr, String algorithm, String password) {StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();EnvironmentPBEConfig config = new EnvironmentPBEConfig();// 指定解密算法:解密算法要与加密算法一一对应config.setAlgorithm(algorithm);// 加密秘钥config.setPassword(password);config.setIvGeneratorClassName("org.jasypt.iv.NoIvGenerator");encryptor.setConfig(config);// 解密return encryptor.decrypt(decryptStr);}public static void main(String[] args) {// 数据库明文密码String encryptedStr = "123456";// 加密算法-与application.yml配置一致String algorithm = PBE_ALGORITHMS_SHA1_RC2_40;//盐值-与application.yml配置一致String password = "vilasto"; String str = JasyptUtil.encrypt(encryptedStr, algorithm, password);//实际加密字符串中不包含ENC(),但是application.yml需要,打印添加了ENC()防止application.yml粘贴遗忘,logger.info("加密后的字符串: {}", "ENC(" + str + ")");logger.info("解密后的字符串: {}", JasyptUtil.decrypt(str, algorithm, password));}
}
2. 在配置文件中使用加密值

将加密后的值用 ENC() 包裹,放入 application.yml 中:

app:username: adminpassword: ENC(这里面写加密字符串,现在控制台打印带了ENC()可以直接复制粘贴)

高级配置

自定义加密算法

为了进一步防止密码泄露,我们可以自定义加密规则。

自定义加密规则非常简单,只需要提供自定义的加密器配置类,然后通过jasypt.encryptor.bean配置指定加密配置类即可。

java">/*** 自定义加密器*/
public class MyStringEncryptor implements StringEncryptor {/*** 加解密PBE 算法*/public static final String PBE_ALGORITHMS_MD5_DES = "PBEWithMD5AndDES";public static final String PBE_ALGORITHMS_MD5_TRIPLEDES = "PBEWithMD5AndTripleDES";public static final String PBE_ALGORITHMS_SHA1_DE_SEDE = "PBEWithSHA1AndDESede";public static final String PBE_ALGORITHMS_SHA1_RC2_40 = "PBEWithSHA1AndRC2_40";/*** 加解密盐值*/private String password;/*** 加解密算法*/private String algorithm = PBE_ALGORITHMS_MD5_DES;public MyStringEncryptor(String password) {this.password = password;}public MyStringEncryptor(String password, String algorithm) {this.password = password;this.algorithm = algorithm;}@Overridepublic String encrypt(String message) {PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();// 加解密盐值encryptor.setConfig(getConfig(this.password));return encryptor.encrypt(message);}@Overridepublic String decrypt(String encryptedMessage) {PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();encryptor.setConfig(getConfig(this.password));return encryptor.decrypt(encryptedMessage);}public SimpleStringPBEConfig getConfig(String password) {SimpleStringPBEConfig config = new SimpleStringPBEConfig();// 加密盐值config.setPassword(password);// 加解密算法config.setAlgorithm(PBE_ALGORITHMS_MD5_DES);// 设置密钥获取迭代次数config.setKeyObtentionIterations(1000);// 线程池大小:默认1config.setPoolSize(1);// 盐值生成器classNameconfig.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator");//  iv(initialization vector,初始化向量) 生成器classNameconfig.setIvGeneratorClassName("org.jasypt.iv.NoIvGenerator");// 设置字符串输出类型config.setStringOutputType("base64");return config;}
}

将自定义加密器添加到 Spring IoC 容器中

java">@Configuration
public class JasyptConfig {/*** 加解密盐值*/@Value("${jasypt.encryptor.password}")private String password;// @Bean("jasyptStringEncryptor")@Bean("myStringEncryptor")public StringEncryptor myStringEncryptor() {return new MyStringEncryptor(password);}
}
application.yml 中配置
jasypt:encryptor:# 指定加解密在spring ioc容器中bean的名称,默认 jasyptStringEncryptorbean: myStringEncryptor# 盐值password: vilasto

注意:Jasypt默认加解密器beanName为jasyptStringEncryptor,如果不想在配置文件中指定自定义加密器名称,需将自定义加密器beanName设置为jasyptStringEncryptor,否则将不生效。

加密盐值通过环境变量指定

  • 方式一:直接作为程序启动时的命令行参数
java -jar app.jar --jasypt.encryptor.password=vilasto
  • 方式二:直接作为程序启动时的应用环境变量
java -Djasypt.encryptor.password=vilasto -jar app.jar
  • 方式三:直接作为系统环境变量
# 1. 设置系统环境变量 JASYPT_ENCRYPTOR_PASSWORD = vilasto# 2. Spring Boot的项目配置文件指定系统环境变量:
jasypt.encryptor.password=${JASYPT_ENCRYPTOR_PASSWORD:}

多环境配

在不同的环境(如开发、测试、生产)中,可以使用不同的加密密钥和配置文件。

1. 创建环境配置文件
  • application-dev.yml(开发环境)
  • application-prod.yml(生产环境)
2. 配置环境变量

在启动应用时,指定激活的环境:

java -jar your-application.jar --spring.profiles.active=prod
3. 环境配置文件示例

application-prod.yml

jasypt:encryptor:password: prod-secret-keyapp:password: ENC(9Xy7C5z8eX0ZQzKz5o1o2w==)

最佳实践

  1. 密钥管理

    • 不要将密钥硬编码在代码中。
    • 使用环境变量或密钥管理服务(如 AWS KMS、HashiCorp Vault)传递密钥。
  2. 配置文件加密

    • 对敏感配置(如数据库密码、API 密钥)进行加密。
  3. 日志脱敏

    • 避免在日志中输出敏感信息的明文。
  4. 定期更换密钥

    • 定期更换加密密钥,并重新加密配置文件。

常见问题

1. 加密值无法解密

  • 检查加密密钥是否一致。
  • 检查加密算法是否一致。

2. 启动时抛出 EncryptionOperationNotPossibleException

  • 确保加密值正确包裹在 ENC() 中。
  • 确保加密密钥正确配置。

3. 多环境配置不生效

  • 检查 spring.profiles.active 是否正确设置。
  • 确保环境配置文件命名正确(如 application-prod.yml)。

参考资料

  • Jasypt 官网
  • Jasypt GitHub 仓库
  • Jasypt Spring Boot Starter GitHub 仓库

http://www.ppmy.cn/news/1576766.html

相关文章

【PyQt5项目实战分享】基于YOLOv5的交通道路目标检测和数据分析软件

这是我之前用PyQt5做的一个基于YOLOv5的交通目标检测软件&#xff0c;包括物体检测和相关数据的分析功能&#xff0c;最近将其完善了下并打包&#xff0c;希望对大家有所帮助~ Tips&#xff1a;文末有我放到 github 和 gitee 的项目开源地址哦 文章目录 ⭐项目功能交通物体检测…

利用Python爬取中国气象局天气预报数据

利用Python爬取中国气象局天气预报数据 在这篇博客中,我们将介绍一段使用Python编写的代码,它能够从中国气象局的网站上爬取天气预报数据,并将这些数据存储到数据库中。这段代码不仅展示了如何利用Python进行网页数据抓取,还涉及到数据处理和数据库操作等多方面的知识。 …

微信小程序中配置不同的环境变量,并依据环境变量编写API接口请求文件

在微信小程序中&#xff0c;为了在不同环境&#xff08;如开发、测试、生产&#xff09;下使用不同的 API 接口地址&#xff0c;我们可以通过配置环境变量来实现。以下是具体的实现步骤和示例代码&#xff1a; 1. 创建环境配置文件 在项目根目录下创建一个 env.js 文件&#…

Git强制覆盖分支:将任意分支完全恢复为main分支内容

Git强制覆盖分支&#xff1a;将任意分支完全恢复为main分支内容 场景背景完整操作步骤一、前置准备二、操作流程步骤 1&#xff1a;更新本地 main 分支步骤 2&#xff1a;强制重置目标分支步骤 3&#xff1a;强制推送至远程仓库 三、操作示意图 关键风险提示&#xff08;必读&a…

深入浅出C语言:第一步,理解 Hello World!

深入浅出C语言&#xff1a;第一步&#xff0c;理解 “Hello World!” 一、程序结构解析 “Hello World!” 程序虽然简短&#xff0c;但它包含了C语言程序的基本结构。 下面是这个程序的代码&#xff1a; #include <stdio.h>int main() { printf("Hello World…

comfyui使用ComfyUI-AnimateDiff-Evolved, ComfyUI-Advanced-ControlNet节点报错解决

comfyui使用animate-diff生成动画&#xff0c;各种报错解决 报错1&#xff1a; ‘cond_obj’ object has no attribute ‘hooks’ 报错2&#xff1a; AdvancedControlBase.get_control_inject() takes 5 positional arguments but 6 were given 报错3&#xff1a; ‘ControlN…

二叉树迭代遍历(三种写法)

写法一&#xff08;各个步骤分离&#xff09; 前序遍历 class Solution {public List<Integer> preorderTraversal(TreeNode root) {List<Integer> list new ArrayList<>();//迭代算法preorderStack(root, list);return list;} //通过栈的先进后出特性&am…

使用阿里云 API 进行声音身份识别的方案

使用阿里云 API 进行声音身份识别的方案 阿里云提供 智能语音交互&#xff08;智能语音识别 ASR&#xff09; 和 声纹识别&#xff08;说话人识别&#xff09; 服务&#xff0c;你可以利用 阿里云智能语音 API 进行 说话人识别&#xff0c;实现客户身份验证。 方案概述 准备工…