java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > SpringBoot jasypt配置文件加密

SpringBoot利用jasypt实现配置文件加密的完整指南

作者:HeyS1

在实际开发中,若出于安全考虑不想暴露一些敏感的配置,如数据库密码等,就需要对配置文件进行加密,下面我们来看看如何使用jasypt给配置文件加密吧

在实际开发中,若出于安全考虑不想暴露一些敏感的配置,如数据库密码等,就需要对配置文件进行加密,这个开源工具就很好帮我们实现这个需求

思路就是把配置文件中的值手动加密填上去,然后生产环境的秘钥通过运行参数传递,开发测试环境可以直接把秘钥写在配置文件

1.引入依赖

非Spring Boot的使用方式可查阅官方文档

github.com/ulisesbocchio/jasypt-spring-boot

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

2.yml 加入配置

# 配置秘钥
jasypt:
  encryptor:
    password: ${jasypt.encryptor.password:defaultPwd}

# 需要加密的字段(明文:123456),需要使用ENC() 包裹
db:
  password: ENC(bVv/e16L6qPO+1pqEPMUYT5uW1EjsERTCoIliqABM+YMr6WURdxPy26La8wHCxgF)

3.测试

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = OrderApplication.class)
public class DemoApplicationTest {

    @Autowired
    ConfigurableEnvironment environment;
    @Autowired
    StringEncryptor stringEncryptor;


    static {
        //指定运行环境密码
        System.setProperty("jasypt.encryptor.password", "password");
    }

    @Test
    public void testEnvironmentProperties() {
        //解密密文
        System.out.println(environment.getProperty("db.password"));
    }


    @Test
    public void encrypt() {
        //此处得到加密后的文本,放入yml
        System.out.println("密文: " + stringEncryptor.encrypt("123456"));
    }
}

方法补充

SpringBoot配置文件加密

依赖

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

设置秘钥

jasypt.encryptor.password=秘钥 开发环境可以直接在配置文件中指定,生产环境可以使用启动命理 --jasypt.encryptor.password=XXX 进行配置 ####加密解密

  package com.itdfq.springboot;

import org.jasypt.encryption.StringEncryptor;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

/**
 * @author duanfangqin 2022/7/11 10:56
 * @implNote
 */
@SpringBootTest
public class JasyptTest {
    @Autowired
    private StringEncryptor stringEncryptor;

    @Test
    public void encrypt(){

        System.out.println(stringEncryptor.encrypt("qweasd123"));
    }
    @Test
    public void decrypt(){
        System.out.println(stringEncryptor.decrypt("zI16ovOHuYiPIQaFx9cVlJF30bg5h3ql"));
    }
}

配置文件密码设置

#Redis服务器地址
spring.redis.host=119.3.234.108
#服务器密码
spring.redis.password=ENC(nwElWn8r6aqVHDdAStIRiEXPAiE57qUF)

ENC(加密之后的密码)

到此这篇关于SpringBoot利用jasypt实现配置文件加密的完整指南的文章就介绍到这了,更多相关SpringBoot jasypt配置文件加密内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文