首页 > 编程 > Java > 正文

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

2019-11-26 08:22:14
字体:
来源:转载
供稿:网友

这篇文章主要介绍了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.Driverspring.datasource.url=jdbc:postgresql:spring.datasource.username=pg_namespring.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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持武林网。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表