jasypt-spring-boot 配置文件加密样例

首先引入pom.xml

<!-- 低版本的jdk(如1.8.0_25-b18)中会出现Failed to bind properties under 'xxx' to java.lang.String,不会在高版本的jdk(如1.8.0_161)运行环境中出现;
原因:加密引发异常。原因是您正在使用强加密算法,并且您尚未在此 Java 虚拟机中安装 Java 加密扩展 (JCE) 无限强度管辖策略文件 -->
<dependency>
    <groupId>com.github.ulisesbocchio</groupId>
    <artifactId>jasypt-spring-boot</artifactId>
    <version>3.0.4</version>
</dependency>

加密配置 application.yml

## 配置文件加密
jasypt:
  encryptor:
    password: xxxxxxxxx
    iv-generator-classname: org.jasypt.iv.NoIvGenerator
    algorithm: PBEWithMD5AndTripleDES
    salt-generator-classname: org.jasypt.salt.RandomSaltGenerator
    string-output-type: base64

启动类启用加密@EnableEncryptableProperties


import com.ulisesbocchio.jasyptspringboot.annotation.EnableEncryptableProperties;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@EnableEncryptableProperties
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

加密测试


import org.jasypt.encryption.StringEncryptor;
import org.jasypt.encryption.pbe.PooledPBEStringEncryptor;
import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Bean;
import org.springframework.test.context.ActiveProfiles;

/**
 * Created by EalenXie on 2022/4/11 12:15
 */
@ActiveProfiles("dev")
@SpringBootTest
public class EncryptorTest {
    
    /**
     * 与appcation.yml的配置一致
     */
    @Bean(name = "encryptorBean")
    static public StringEncryptor stringEncryptor() {
        PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();
        SimpleStringPBEConfig config = new SimpleStringPBEConfig();
        config.setPassword("xxxx");
        config.setAlgorithm("PBEWithMD5AndTripleDES");
        config.setKeyObtentionIterations("1000");
        config.setPoolSize("1");
        config.setProviderName("SunJCE");
        config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator");
        config.setIvGeneratorClassName("org.jasypt.iv.NoIvGenerator");
        config.setStringOutputType("base64");
        encryptor.setConfig(config);
        return encryptor;
    }

    @Test
    void testPassEnc(@Autowired StringEncryptor stringEncryptor) {
        String s = stringEncryptor.encrypt("xxxxxxxxxx");
        System.out.println(s);
        Assertions.assertNotNull(s);
    }
}

使用ENC(xxx)为属性进行加密配置

ali:
  access-key-id: ENC(xxxxxxxxxxxxxxxxx==)
  access-key-secret: ENC(O/+xxxxxxxxx/xxxxxxxxx==)
posted @ 2024-01-10 13:51  EalenXie  阅读(212)  评论(0编辑  收藏  举报