博客详情

springboot中使用jasypt对配置文件进行加密 (原创)

作者: 朝如青丝暮成雪
发布时间:2019-09-26 23:47:00  文章分类:java编程   阅读(1384)  评论(0)

1、springboot项目中,引入依赖

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

2、在application.yml中配置jasypt.encryptor.password=yoursalt ,例如

jasypt:
  encryptor:
    password: turing


如果不想将jasypt的加密盐值直接配置在配置文件中,则也可改为在启动jar命令行中指定程序参数或jvm参数
#启动springboot的jar包,指定程序参数
java -jar xxx.jar --jasypt.encryptor.password=turing

#启动springboot的jar包,指定JVM参数
java  -Djasypt.encryptor.password=turing -jar xxx.jar 

3、命令行加解密

#直接使用命令对明文进行加密
java -cp jasypt-1.9.2.jar org.jasypt.intf.cli.JasyptPBEStringEncryptionCLI input="123456" password=turing algorithm=PBEWithMD5AndDES
#直接使用命令对密文进行解密
java -cp jasypt-1.9.2.jar org.jasypt.intf.cli.JasyptPBEStringDecryptionCLI input="KCQCruXa2BN+StcKVPlkAg==" password=turing algorithm=PBEWithMD5AndDES


4、 在项目业务代码中使用jasypt


package com.tingcream.springmybatis2;

import org.jasypt.encryption.StringEncryptor;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;


@RunWith(SpringRunner.class)
@SpringBootTest
public class JasyptTest {

@Autowired
private StringEncryptor stringEncryptor;


@Test
public void encrypt() {
String text ="123456";
String s1= stringEncryptor.encrypt(text);
System.out.println("加密后得到密文为:"+s1);
String s2= stringEncryptor.decrypt(s1);
System.out.println("解密后得到原文为:"+s2);

/*
* 注意: 每次使用stringEncryptor加密同样的明文,所得到的密码都可能不一样
* 加密后得到密文为:LTsP+Ixe26vAZYnVd28Lag==
解密后得到原文为:123456

加密后得到密文为:EeTv7ggGS3SVEICVd1TVdA==
解密后得到原文为:123456

加密后得到密文为:L0gcXucNVewXZSsFNrmVhw==
解密后得到原文为:123456

* */

}  
}



5、application.yml中配置敏感信息


spring: 

  datasource: 
    druid:
      driver-class-name: com.mysql.cj.jdbc.Driver
      username: root
      password: ENC(KCQCruXa2BN+StcKVPlkAg==)  #注意jasypt的密文需要使用ENC()括起来

      url: jdbc:mysql://localhost:3306/springmybatis?useUnicode=true&characterEncoding=utf-8&useSSL=false 





关键字:  jasypt  springboot  加密
评论信息
暂无评论
发表评论

亲,您还没有登陆,暂不能评论哦! 去 登陆 | 注册

博主信息
   
数据加载中,请稍候...
文章分类
   
数据加载中,请稍候...
阅读排行
 
数据加载中,请稍候...
评论排行
 
数据加载中,请稍候...

Copyright © 叮叮声的奶酪 版权所有
备案号:鄂ICP备17018671号-1

鄂公网安备 42011102000739号