美文网首页
SpringBoot使用Jasypt加密

SpringBoot使用Jasypt加密

作者: Lyudmilalala | 来源:发表于2021-03-23 11:22 被阅读0次

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

相关文章

网友评论

      本文标题:SpringBoot使用Jasypt加密

      本文链接:https://www.haomeiwen.com/subject/crtfhltx.html