SpringBoot使用Jasypt加密
2021-03-23 本文已影响0人
Lyudmilalala
pom.xml
加入jasypt
依赖
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
建立一个Test class,编写加密方法
package cn.jasyptTest;
import org.jasypt.util.text.BasicTextEncryptor;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import lombok.extern.slf4j.Slf4j;
@SpringBootTest(classes = {JasyptTestApplication.class}, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@Slf4j
class EncryptionTest {
@Test
void databaseEncryptionTest() {
BasicTextEncryptor textEncryptor = new BasicTextEncryptor();
//加密所需的salt(盐)
textEncryptor.setPassword("myApplicationSalt");
//要加密的数据(数据库的用户名或密码)
String username = textEncryptor.encrypt("root");
String password = textEncryptor.encrypt("1AmP@ssw0rd");
log.info("db username:"+username);
log.info("db password:"+password);
}
}
运行加密,得到密文
[cn.jasyptTest 2021-03-23 11:17:06.848] INFO Method: databaseEncryptionTest(Line 21) - db username:eLQMldjd8M/7qCMZZ6z0vg==
[cn.jasyptTest 2021-03-23 11:17:06.848] INFO Method: databaseEncryptionTest(Line 22) - db password:Hvvbp6fdZWfOUjUMaJWPExdWrQLcm7Wv
将密文和加密盐值写入application-properties
,程序运行时即可自动解密使用
jasypt.encryptor.password= myApplicationSalt
spring.datasource.username = ENC(eLQMldjd8M/7qCMZZ6z0vg==)
spring.datasource.password = ENC(Hvvbp6fdZWfOUjUMaJWPExdWrQLcm7Wv)
生产环境直接将盐值写在配置文件会有安全风险,可以选择在启动程序时带入
java -jar -Djasypt.encryptor.password=myApplicationSalt HelloWorld/target/helloWorld-server-0.0.1-SNAPSHOT.jar