SpringBoot集成ENC加密解密
描述:对配置文件的数据库密码明文进行加密解密
- jasypt 官网:https://github.com/ulisesbocchio/jasypt-spring-boot
- 坐标:
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>3.0.3</version>
<!--低版本使用-->
<!--<version>2.1.2</version>-->
</dependency>
<dependency>
<groupId>org.jasypt</groupId>
<artifactId>jasypt</artifactId>
<version>1.9.3</version>
</dependency>
- 配置文件
#写到配置文件也有风险,可以在程序启动中设置 -Djasypt.encryptor.password=123456
#ENC加密使用salt设置 #用来加密的salt值
#jasypt.encryptor.password=123456
jasypt.encryptor.algorithm=PBEWithMD5AndDES
jasypt.encryptor.iv-generator-classname=org.jasypt.iv.NoIvGenerator
说明:jasypt.encryptor.iv-generator-classname=org.jasypt.iv.NoIvGenerator,主要是3.x和2.x的区别。如果不使用则可以使用2.x低版本的,这里用到的是3.x版本。
spring.datasource.password=ENC(pF2Wn9bEZABAKSNqYUCtSsrO4jUXi0Z1)
- 启动类配置
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.ulisesbocchio.jasyptspringboot.annotation.EnableEncryptableProperties;
@SpringBootApplication
@EnableEncryptableProperties
- 测试类
//加密
public static void testEncryption(){
//加密工具
StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
//加密配置
EnvironmentStringPBEConfig config = new EnvironmentStringPBEConfig();
//加密算法,写死即可
config.setAlgorithm("PBEWithMD5AndDES");
//加密使用salt设置
config.setPassword("123456");
//应用配置
encryptor.setConfig(config);
//需要加密数据
String plaintext="123456";
//加密
String encrypttext=encryptor.encrypt(plaintext);
System.out.println(plaintext + " : " + encrypttext);
}
//解密
public static void testDecryption(){
//加密工具
StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
//加密配置
EnvironmentStringPBEConfig config = new EnvironmentStringPBEConfig();
//加密算法,写死即可
config.setAlgorithm("PBEWithMD5AndDES");
//加密使用salt设置
config.setPassword("123456");
//应用配置
encryptor.setConfig(config);
//需要加密数据
String encrypttext="pF2Wn9bEZABAKSNqYUCtSsrO4jUXi0Z1";
//加密
String plaintext=encryptor.decrypt(encrypttext);
System.out.println(encrypttext + " : " + plaintext);
}
- jar包运行
# linux启动
nohup java -Djasypt.encryptor.password=123 -Xms512m -Xmx1024m -jar xxx.jar &
# windows启动
java -Djasypt.encryptor.password=123 -Xms512m -Xmx1024m -jar xxx.jar
- idea配置
文章评论