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

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

一、引入依賴

        <!-- jasypt方式一 -->
        <dependency>
            <groupId>com.github.ulisesbocchio</groupId>
            <artifactId>jasypt-spring-boot-starter</artifactId>
            <version>3.0.2</version>
        </dependency>


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

     

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章