jasypt-spring-boot-starter 对应 Spring Boot 版本

介绍

jasypt-spring-boot-starter 是一个用于 Spring Boot 的库,用于简化配置文件中的敏感数据加密。它基于 Jasypt 加密库,提供了 Spring Boot 的自动配置和集成。

在开发应用程序时,我们经常需要在配置文件中存储一些敏感数据,例如数据库密码、API 密钥等。为了保护这些敏感信息的安全性,我们通常会对其进行加密,并在应用程序启动时进行解密。jasypt-spring-boot-starter 就是为了解决这个问题而诞生的。

支持的 Spring Boot 版本

jasypt-spring-boot-starter 可以与不同版本的 Spring Boot 集成。下面是它对应的 Spring Boot 版本的列表:

  • 2.5.x 对应 jasypt-spring-boot-starter 3.0.x
  • 2.4.x 对应 jasypt-spring-boot-starter 2.1.x
  • 2.3.x 对应 jasypt-spring-boot-starter 2.0.x
  • 2.2.x 对应 jasypt-spring-boot-starter 1.18.x
  • 2.1.x 对应 jasypt-spring-boot-starter 1.17.x
  • 2.0.x 对应 jasypt-spring-boot-starter 1.16.x

以上列表中的版本是当前编写文章时的最新版本。请注意,随着时间的推移,可能会有新的版本发布。建议在使用之前查阅官方文档,以获取最新的版本信息。

安装 jasypt-spring-boot-starter

首先,需要在 Maven 或 Gradle 项目中添加 jasypt-spring-boot-starter 依赖。下面是 Maven 和 Gradle 的示例:

Maven

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

Gradle

dependencies {
    implementation 'com.github.ulisesbocchio:jasypt-spring-boot-starter:3.0.3'
}

配置 jasypt-spring-boot-starter

一旦添加了 jasypt-spring-boot-starter 依赖,就可以开始配置敏感数据的加密了。下面是一个示例配置文件:

# application.properties

# 配置加密算法和密钥
jasypt.encryptor.algorithm=PBEWithMD5AndDES
jasypt.encryptor.password=mySecretKey

# 加密敏感数据
myapp.db.username=ENC(pY8h8q17H/9g4zjzIGp8zg==)
myapp.db.password=ENC(w7bDNLi+Yvj2hLdGv2k7MA==)

在上面的示例中,我们配置了加密算法为 PBEWithMD5AndDES,密钥为 mySecretKey。然后,我们使用 ENC(encryptedValue) 的格式加密了两个敏感数据。加密后的值可以通过调用 jasypt.encryptor.encrypt(value) 方法来生成。

使用 jasypt-spring-boot-starter

一旦配置完成,jasypt-spring-boot-starter 将自动在应用程序启动时解密配置文件中的敏感数据,并将其注入到对应的 Bean 中。下面是一个示例:

@Service
public class MyService {

    @Value("${myapp.db.username}")
    private String username;

    @Value("${myapp.db.password}")
    private String password;

    public void doSomething() {
        System.out.println("Username: " + username);
        System.out.println("Password: " + password);
    }
}

在上面的示例中,我们使用 @Value 注解将加密后的敏感数据注入到 MyService 的成员变量中。在 doSomething 方法中,我们可以直接使用解密后的敏感数据。

总结

jasypt-spring-boot-starter 提供了一种方便的方式来加密和解密敏感数据。它与 Spring Boot 集成,可以轻松地对配置文件中的敏感信息进行加密和解密。本文介绍了 jasypt-spring-boot-starter 的用法,并给出了示例代码。希望通过本文