添加依赖
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>2.1.0</version>
</dependency>
配置
jasypt:
encryptor:
bootstrap: true
password: test
如何加解密
- 使用
org.jasypt.intf.cli.JasyptPBEStringEncryptionCLI
加密java -cp jasypt-1.9.2.jar org.jasypt.intf.cli.JasyptPBEStringEncryptionCLI input="contactspassword" password=supersecretz algorithm=PBEWithMD5AndDES
- 使用
org.jasypt.intf.cli.JasyptPBEStringDecryptionCLI
解密
-java -cp jasypt-1.9.2.jar org.jasypt.intf.cli.JasyptPBEStringDecryptionCLI input="i00VogiiZ1FpZR9McY7XNw==" password=supersecretz algorithm=PBEWithMD5AndD
加密后的属性
- 加密后配置类似
spring.datasource.password=ENC(BsSPrDRNeU/Nb1v/GsHvZA==)
如何隐藏关键的机密key
如果使用-D 或者–server.port 设置启动参数.在ps 时或者jps时都能看到.因此是不安全的.下面两种方法可以解决这个问题.
- 方案一
echo "jasypt.encryptor.password=xxx" | java -jar -Dspring.datasource.usename=ENC(BsSPrDRNeU/Nb1v/GsHvZA==) xxx.jar
java -jar -Dspring.datasource.usename=ENC(BsSPrDRNeU/Nb1v/GsHvZA==) xxx.jar <<< "jasypt.encryptor.password=xxx"
- 解析参数的工具类
/** * 从stdin 中读取配置参数 * example: * echo "--jasypt.encryptor.password=xxx --server.port=8081" | java -jar xxx.jar * or * java -jar xxx.jar <<< "--jasypt.encryptor.password=xxx --server.port=8081" * <p> * 多个参数以空格分割. * * @author xielongwang * @create 2018-07-16 下午5:34 * @description 从stdin 中读取配置参数,为了隐蔽ps or jps 能看到启动参数 */ @Slf4j public class StdInParam { /** * 从stdin 中读取配置参数 * * @param args 原来的启动参数 * @return 合并后的参数 */ public static String[] getParamFormStdinLine(String[] args) { StringBuilder paramBuild = new StringBuilder(); try (BufferedReader in = new BufferedReader(new InputStreamReader(new BufferedInputStream(System.in)))) { if (in.ready()) { String param; while ((param = in.readLine()) != null && param.length() != 0) { paramBuild.append(param); } } } catch (Exception e) { log.error("reade stdin param error ", e); } //如果stdin 为空默认返回args if (StringUtils.isEmpty(paramBuild.toString())) { log.warn("stdin param is null! "); return args; } //转换成启动参数 String[] stdinParam = paramBuild.toString().split("\\s+"); return ObjectArrays.concat(stdinParam, args, String.class); } }
- 使用
public static void main(String[] args) { String[] startParam = StdInParam.getParamFormStdinLine(args); SpringApplication.run(xxx.class, startParam); }
- 方案二
- 使用
spring.profiles.include
配置项,
spring boot 会默认扫描"classpath:/,classpath:/config/,file:./,file:./config/"
这些路径下的配置文件. - 配置方法
application.yml
加入
在启动jar的目录中增加一个spring: profiles: include: - security
application-security.yml
配置上
在发版前把这个加上,发完版后清除掉即可. 但是当refresh 配置的时候是否为空就要测试好jasypt: encryptor: password: xxx
- 踩过的坑,使用druid 配置用户名密码加密时不要配置druid下面.要用spring.datasource.password 不然刷新就会有问题.
- 使用