SpringBoot配置文件屬性加密

摘要

添加依賴

implementation 'com.github.ulisesbocchio:jasypt-spring-boot-starter:3.0.3'

配置文件

jasypt:
  encryptor:
    #默認(rèn)加密算法:PBEWITHHMACSHA512ANDAES_256,sha512+AES算法,安全性更高,但是需要 Java JDK 1.9+
    #本服務(wù)使用jdk1.8,所以使用 PBEWithMD5AndDES md5+des算法
    #默認(rèn)使用 com.ulisesbocchio.jasyptspringboot.encryptor.DefaultLazyEncryptor 進行加解密 ,PooledPBEStringEncryptor可以對其加密的內(nèi)容進行解密
    algorithm: PBEWithMD5AndDES
    # 加密密鑰,使用方式 spring.datasource.password=ENC(密文),不要設(shè)置在配置文件中,建議使用環(huán)境變量或者啟動參數(shù): --jasypt.encryptor.password=123456
    password: 123456
    #設(shè)置密文前綴和后綴
    property:
      prefix: ENC(
      suffix: )
    iv-generator-classname: org.jasypt.iv.RandomIvGenerator

可用屬性

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

生成密文

# jar下載地址:https://repo1.maven.org/maven2/org/jasypt/jasypt/1.9.3/jasypt-1.9.3.jar
# 實際上使用maven或者gradle配置jasypt-spring-boot-starter依賴后,這個jar就已經(jīng)下載到本地倉庫了,去本地倉庫找找吧
#加密
java -cp jasypt-1.9.3.jar org.jasypt.intf.cli.JasyptPBEStringEncryptionCLI password=123456 algorithm=PBEWithMD5AndDES ivGeneratorClassName=org.jasypt.iv.RandomIvGenerator input=newpwd

#解密
java -cp jasypt-1.9.3.jar org.jasypt.intf.cli.JasyptPBEStringDecryptionCLI password=123456 algorithm=PBEWithMD5AndDES ivGeneratorClassName=org.jasypt.iv.RandomIvGenerator input=BwNPdUi+syCTKFj/nlbI5fAtGUKuhN8r

屬性加密

spring:
#數(shù)據(jù)源配置
  datasource:
    url: jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=utf-8&useTimezone=true&serverTimezone=GMT%2B8
    username: root
    password: ENC(BwNPdUi+syCTKFj/nlbI5fAtGUKuhN8r)
    driver-class-name: com.mysql.cj.jdbc.Driver

  #配置redis連接
  redis:
    host: 127.0.0.1
    password: ENC(FE4cpSc+2u9NFEY+Q5n9kNSxW6BUiNXGNTUPuhoQbPA=)

說明

  • 配置文件將需要加密的屬性使用ENC(密文)的方式進行配置,密文前綴和后綴可以在配置文件中進行配置
  • jasypt-spring-boot-starter在服務(wù)運行時會自動對密文進行解密處理

密鑰傳遞方式

#1.啟動參數(shù)
java -jar jasypt-spring-boot-demo.jar --jasypt.encryptor.password=password

#2.系統(tǒng)屬性
java -Djasypt.encryptor.password=password -jar jasypt-spring-boot-demo.jar

#3.環(huán)境變量
jasypt:
    encryptor:
        password: ${JASYPT_ENCRYPTOR_PASSWORD:}

JASYPT_ENCRYPTOR_PASSWORD=password java -jar jasypt-spring-boot-demo.jar

#也可以先設(shè)置環(huán)境變量
export JASYPT_ENCRYPTOR_PASSWORD=password
java -jar jasypt-spring-boot-demo.jar

代碼中使用Jasypt

/**
* 引入jasypt-spring-boot-starter就會自動注入
*/
@Resource
private StringEncryptor stringEncryptor;

public void StringEncryptor() {
    String encrypt = stringEncryptor.encrypt("newpwd");
    System.out.println(encrypt);

    String decrypt = stringEncryptor.decrypt(encrypt);
    System.out.println(decrypt);
}

非springboot項目

依賴

implementation 'org.jasypt:jasypt:1.9.3'

工具類

package com.example.utils;

import org.jasypt.encryption.pbe.PooledPBEStringEncryptor;
import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
import org.jasypt.encryption.pbe.config.EnvironmentStringPBEConfig;
import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig;

/**
 * <h1>屬性加密工具類</h1>
 */
public class JasyptUtil {

    public static String encrypt(String secretKey, String message) {
        return stringEncryptor(secretKey, message, true);
    }

    public static String decrypt(String secretKey, String message) {
        return stringEncryptor(secretKey, message, false);
    }

    /**
     * {@link StringEncryptor} 加解密。
     * 同一個密鑰(secretKey)對同一個內(nèi)容執(zhí)行加密,生成的密文都是不一樣的,但是根據(jù)根據(jù)這些密文解密成明文都是可以.
     * 1、Jasypt 默認(rèn)使用 {@link StringEncryptor} 來解密全局配置文件中的屬性,所以提供密文時,也需要提供 {@link StringEncryptor} 加密的密文
     * 2、{@link StringEncryptor} 接口有很多的實現(xiàn)類,比如常用的 {@link PooledPBEStringEncryptor}
     * 3、setConfig(final PBEConfig config):為對象設(shè)置 {@link PBEConfig} 配置對象
     * 4、encrypt(final String message):加密內(nèi)容
     * 5、decrypt(final String encryptedMessage):解密內(nèi)容
     *
     * @param secretKey :密鑰。加/解密必須使用同一個密鑰
     * @param message   :加/解密的內(nèi)容
     * @param isEncrypt :true 表示加密、false 表示解密
     * @return
     */
    private static String stringEncryptor(String secretKey, String message, boolean isEncrypt) {
        PooledPBEStringEncryptor pooledPBEStringEncryptor = new PooledPBEStringEncryptor();
        pooledPBEStringEncryptor.setConfig(getSimpleStringPBEConfig(secretKey));
        String result = isEncrypt ? pooledPBEStringEncryptor.encrypt(message) : pooledPBEStringEncryptor.decrypt(message);
        return result;
    }

    /**
     * 設(shè)置 {@link PBEConfig} 配置對象,SimpleStringPBEConfig 是它的實現(xiàn)類
     * 1、所有的配置項建議與全局配置文件中的配置項保持一致,特別是 password、algorithm 等等選項,如果不一致,則應(yīng)用啟動時解密失敗而報錯.
     * 2、setPassword(final String password):設(shè)置加密密鑰,必須與全局配置文件中配置的保存一致,否則應(yīng)用啟動時會解密失敗而報錯.
     * 3、setPoolSize(final String poolSize):設(shè)置要創(chuàng)建的加密程序池的大小.
     * 4、setAlgorithm(final String algorithm): 設(shè)置加密算法的值, 此算法必須由 JCE 提供程序支持
     * 5、setKeyObtentionIterations: 設(shè)置應(yīng)用于獲取加密密鑰的哈希迭代次數(shù)。
     * 6、setProviderName(final String providerName):設(shè)置要請求加密算法的安全提供程序的名稱
     * 7、setSaltGeneratorClassName:設(shè)置 Sal 發(fā)生器
     * 8、setIvGeneratorClassName:設(shè)置 IV 發(fā)生器
     * 9、setStringOutputType:設(shè)置字符串輸出的編碼形式??捎玫木幋a類型有 base64、hexadecimal
     *
     * @param secretKey
     * @return
     */
    private static SimpleStringPBEConfig getSimpleStringPBEConfig(String secretKey) {
        SimpleStringPBEConfig config = new SimpleStringPBEConfig();
        config.setPassword(secretKey);
        config.setAlgorithm("PBEWithMD5AndDES");
        //以下都是默認(rèn)值
        config.setPoolSize("1");
        config.setKeyObtentionIterations("1000");
        config.setProviderName("SunJCE");
        config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator");
        //命令行執(zhí)行時要指定這個參數(shù)
        config.setIvGeneratorClassName("org.jasypt.iv.RandomIvGenerator");
        config.setStringOutputType("base64");
        return config;
    }

}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容