Springboot配置文件内容加密代码实例

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Springboot配置文件内容加密代码实例

  2021-04-02 我要评论

这篇文章主要介绍了Springboot配置文件内容加密代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

使用的是jasypt-spring-boot-starter,具体介绍可以参考  https://gitee.com/yangziyi2017/Jasypt-Spring-Boot

引入依赖

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

创建加密工具类

需要创建一个工具类,用于对明文进行加密,获取密文,然后把密文写入到application.yml这样的配置文件中

package com.hikvision.seclab.common.util.encrypt;
import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
/**
* 使用jasypt对配置文件进行加密的工具
* @author: 2019/11/7 16:47
* @since: 0.0.1-SNAPSHOT
* @modified By:
*/
public class JasyptTool {
  public static void main(String[] a){
    StandardPBEStringEncryptor se = new StandardPBEStringEncryptor();
    se.setPassword("xxx");
    String postgres = se.encrypt("abc123");
    System.out.println(postgres);
  }
}

其中有一个设定密码的动作,是设定加密使用的salt,时jasypt组件必选的配置,有些文章中在配置文件中使用jasypt.encryptor.password设置,这样不安全,别人拿到salt,使用jasypt可以直接解密配置文件中的密文。

修改配置文件

获取密文后,修改配置文件

spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql:
spring.datasource.username=pg_name
spring.datasource.password=ENC(t78dKQb1viAT2QKDxxeerdaNm6wyDCJ)
spring.datasource.initialization-mode=always

设置jasypt.encryptor.password

开发环境

可以通过配置jvm启动参数来指定jasypt.encryptor.password的值

生产环境

可以在启动时,设定在启动参数中
java -Dfile.encoding=UTF8 -Djasypt.encryptor.password=e9fbdb2d3b21 -jar -Xmx512m xxxDemo.jar

在docker容器中密文的密码可以设置成环境变量(如:JASYPT_PASSWORD ),上述命令可以修改为:
java -Dfile.encoding=UTF8 -Djasypt.encryptor.password=${JASYPT_PASSWORD} -jar -Xmx512m settlement.jar

您可能感兴趣的文章:

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们