jasypt是java中流行的开源加解密工具包
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
@autowired 注入StringEncryptor bean
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括起来