前端开发入门到精通的在线学习网站

网站首页 > 资源文章 正文

如何给application.yml文件中的敏感配置信息进行加密

qiguaw 2024-10-01 14:52:52 资源文章 15 ℃ 0 评论

在Spring Boot中,可以使用Jasypt(Java Simplified Encryption)来对敏感的配置信息进行加密。Jasypt是一个简单的加密库,支持在配置文件中使用占位符来引用加密后的值。

下面是使用 Jasypt 加密敏感配置信息的步骤

添加Jasypt依赖

首先,在 Maven的配置文件中添加Jasypt的依赖。

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

在配置文件中加密敏感信息

application.ymlapplication.properties文件中,使用ENC()函数将敏感信息进行加密,并将加密后的值放置在占位符中。例如

db:
  username: ENC(encrypted_username)
  password: ENC(encrypted_password)

使用Jasypt工具加密配置信息

用Jasypt提供的命令行工具或Java API来加密敏感信息。命令行工具可以在命令行中执行,Java API则可以在代码中调用。

使用命令行工具

java -cp jasypt-3.0.3.jar org.jasypt.intf.cli.JasyptPBEStringEncryptionCLI input="your_sensitive_data" password="your_encryption_password" algorithm=PBEWithMD5AndDES

这将输出加密后的值,将其复制并替换application.yml中的encrypted_usernameencrypted_password

使用Java API

public class JasyptExample {

    public static void main(String[] args) {
        StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
        encryptor.setPassword("your_encryption_password");

        String encryptedUsername = encryptor.encrypt("your_sensitive_username");
        String encryptedPassword = encryptor.encrypt("your_sensitive_password");

        System.out.println("Encrypted Username: " + encryptedUsername);
        System.out.println("Encrypted Password: " + encryptedPassword);
    }
}

启动应用程序

在启动Spring Boot应用程序时,Jasypt将会自动解密配置文件中的敏感信息,并注入到对应的属性中。

这样,敏感的配置信息就会以加密的形式存储在配置文件中,只有知道加密密码的人才能解密并查看真实的敏感信息,提高了配置信息的安全性。

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表