springboot 配置 jasypt加密,应用于配置文件数据库密码加密形式展现
1.pom.xml导入对应的包
<dependency> <groupId>com.github.ulisesbocchio</groupId> <artifactId>jasypt-spring-boot-starter</artifactId> <version>3.0.3</version> </dependency> <build> <plugins> <plugin> <groupId>com.github.ulisesbocchio</groupId> <artifactId>jasypt-maven-plugin</artifactId> <version>3.0.3</version> </plugin> </plugins> </build>
2.第二步:加盐(三种方式)
1..yml中 一般是本地开发的时候
jasypt:
  encryptor:
    password: xxxxx
在环境变量中配置 JASYPT_ENCRYPTOR_PASSWORD =xxx (xxx根据自己的密钥设置)
2.在Program arguments 中设置 --jasypt.encryptor.password=xxx 一般是在正式显示采用这种方式,谁也不知道你的密钥是多少
3.在vm arguments 中设置 -Djasypt.encryptor.password=xxx 一般是在正式显示采用这种方式,谁也不知道你的密钥是多少
第三步:编写测试
package com.org;
 
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.SpringJUnit4ClassRunner;
 
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class EncryptorTest {
    @Autowired
    private StringEncryptor encryptor;
 
    @Test
    public void encry() {
        String username = encryptor.encrypt("UserName");
        String password = encryptor.encrypt("Password");
        System.out.println(username);  
        //获取加密的name  7VNwO00NWlgoqduTFjh9+NQrFnw/92Uu 在DB配置中替换
        System.out.println(password);  
       //获取加密的password  3g8eMXCA6UwoB3bqtfY5cOjJQRymvc8b  在DB配置中替换
    }
}
第四步:替换DB配置信息
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://xx.x.x.xx:3306/zxxxx
    username: ENC(7VNwO00NWlgoqduTFjh9+NQrFnw/92Uu) 
    password: ENC(3g8eMXCA6UwoB3bqtfY5cOjJQRymvc8b)
到这一步就OK了,如果需要自定义密文的前后缀,可如下设置:
jasypt:
  encryptor:
    property:
      prefix: "ENC@["
      suffix: "]"
如果以上配置不能使用的时候可以在启动类加上注解
@EnableEncryptableProperties
datasource 代码获取如下
@Configuration
@Order(3)
public class DataSourceConfig {
    //@Primary
    @Bean("datasource")
    //@Qualifier("datasource")
    @ConfigurationProperties(prefix = "datasource.datasource")
    public DataSource defaultDataSource() {
        return DataSourceBuilder.create().build();
    }
}
测试环境或者线上环境启动命令如下 在你的明令上添加上这个
-Djasypt.encryptor.password='xxxx'
 
                    
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号