【SpringBoot----配置文件加密解密】

jasypt代码地址:https://github.com/ulisesbocchio/jasypt-spring-boot

一、引入依赖

        
        
            com.github.ulisesbocchio
            jasypt-spring-boot-starter
            3.0.2
        


2种方式引入依赖包。

第一种是你的springboot应用使用了@SpringBootApplication or @EnableAutoConfiguration注解就可以这样引入。

如果没有使用上面的注解,就用第二种方式。并且还需要在你的启动类上加注解:

@Configuration
@EnableEncryptableProperties

package com.example.gate;
 
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
//import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
 
import com.ulisesbocchio.jasyptspringboot.annotation.EnableEncryptableProperties;
 
 
//使用jasypt的第二种方式.如果你没用到@SpringBootApplication 或  @EnableAutoConfiguration就必须用下面2个注解,才能正常使用jasypt
//@Configuration
//@EnableEncryptableProperties
 
//@EnableCircuitBreaker
@ComponentScan(basePackages = "com.example")
@EnableDiscoveryClient
@SpringBootApplication
public class GateApplication {
 
    public static void main(String[] args) {
        SpringApplication.run(GateApplication.class, args);
    }
}

二、配置文件中配置jasypt属性

#jasypt加密配置
jasypt:
  encryptor:
    password: Sunny
    algorithm: PBEWITHHMACSHA512ANDAES_256

其中秘钥password是必须自己定义的。其他都可以不配置,因为有默认的配置:

Key    Required    Default Value
jasypt.encryptor.password    True    -
jasypt.encryptor.algorithm    False    PBEWITHHMACSHA512ANDAES_256
jasypt.encryptor.key-obtention-iterations    False    1000
jasypt.encryptor.pool-size    False    1
jasypt.encryptor.provider-name    False    SunJCE
jasypt.encryptor.provider-class-name    False    null
jasypt.encryptor.salt-generator-classname    False    org.jasypt.salt.RandomSaltGenerator
jasypt.encryptor.iv-generator-classname    False    org.jasypt.iv.RandomIvGenerator
jasypt.encryptor.string-output-type    False    base64
jasypt.encryptor.proxy-property-sources    False    false
jasypt.encryptor.skip-property-sources    False    empty list

三、用jasypt加密,在yml填写加密后的密码

密码的格式:ENC(密码)

例如:

#jasypt加密后的密码
mypass:
  pass1: ENC(NfA+LtBfc26xLiHLb0EGXeNfU9TaE2tQIt7X94DrodPcUKV/tnTKQLz7bcLSM3i0)

工具类:

package com.sunber.common.util.jasypt;

import com.sunber.common.util.log.LogUtil;
import com.sunber.common.util.string.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.jasypt.encryption.StringEncryptor;
import org.jasypt.encryption.pbe.PooledPBEStringEncryptor;
import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig;

/**
 * @Title: 配置文件加密解密工具类
 * @Author: Sunny
 * @Date: 2020/6/19 18:16
 */
@Slf4j
public class JasyptUtil {
    private static StringEncryptor stringEncryptor = null;

    /**
     * @Title: Jasypt实例化
     * @Param: [secretKey]
     * @Return: org.jasypt.encryption.StringEncryptor
     * @Author: Sunny
     * @Date: 2020/6/19 18:30
     * @Throws:
     */
    public static StringEncryptor getInstance(String secretKey) throws Exception {
        if (StringUtil.isBlank(secretKey)) {
            log.error(LogUtil.log("jasypt", "错误", "secretKey不能为空!"));
            throw new Exception("org.jasypt.encryption.StringEncryptor秘钥不能为空!");
        }
        if (stringEncryptor == null) {
            PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();
            SimpleStringPBEConfig config = new SimpleStringPBEConfig();
            config.setPassword(secretKey);// 这个秘钥必须是我们自己定义
            config.setAlgorithm("PBEWITHHMACSHA512ANDAES_256");
            config.setKeyObtentionIterations("1000");
            config.setPoolSize("1");
            config.setProviderName("SunJCE");
            config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator");
            config.setIvGeneratorClassName("org.jasypt.iv.RandomIvGenerator");
            config.setStringOutputType("base64");
            encryptor.setConfig(config);
            stringEncryptor = encryptor;
        }
        return stringEncryptor;
    }
}

测试

package com.sunber.common.util.jasypt;

import com.sunber.common.util.Out;
import org.jasypt.encryption.StringEncryptor;
import org.junit.Test;

public class JasyptTest {
    // 秘钥字符串,Jasypt的password
    private String secretKey = "Sunny";

    @Test
    public void getPass() throws Exception {
        // 待加密字符串
        String pwd = "123456";

        StringEncryptor stringEncryptor = JasyptUtil.getInstance(secretKey);
        String encrypt = stringEncryptor.encrypt(pwd);
        Out.print("【" + pwd + "】被加密成【" + encrypt + "】");

        String decrypt = stringEncryptor.decrypt(encrypt);
        Out.print("【" + encrypt + "】被解密成【" + decrypt + "】");
    }
}


执行main方法打印:

==================================
【123456】被加密成【mKL+/Yz60nSoMLhCgisiRMoJMy88Xfijfv+ZbOM10evkWBanBqg1jmamJ4alYXav】
==================================


==================================
【mKL+/Yz60nSoMLhCgisiRMoJMy88Xfijfv+ZbOM10evkWBanBqg1jmamJ4alYXav】被解密成【123456】
==================================

注意,一个同样的密码和秘钥,每次执行加密,密文都是不一样的。但是解密是没问题的。

加密后的字符串配置到yml配置文件中中就可以了。

四、修改标识

ENC()这个标识是可以改的,比如我先改成ENC@[],只要按以下设置即可。其他的基本上就用默认的就行。

#jasypt加密配置
jasypt:
  encryptor:
    password: Sunny
    algorithm: PBEWITHHMACSHA512ANDAES_256
    property:
      prefix: "ENC@["
      suffix: "]"

五、密钥

存放位置

  1. 配置文件
  2. 代码常量
  3. 配置中心
  4. 环境变量
    java -Dfile.encoding=UTF8 -Djasypt.encryptor.password=${JASYPT_PASSWORD} -jar -Xmx512m settlement.jar

     

  5. 通过启动命令传递
    java -Dfile.encoding=UTF8 -Djasypt.encryptor.password=e9fbdb2d3b21 -jar -Xmx512m settlement.jar

     

你可能感兴趣的:(加密解密)