最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

springboot項(xiàng)目數(shù)據(jù)庫密碼如何加密

 更新時(shí)間:2021年07月08日 11:22:23   作者:linyb極客之路  
在我們?nèi)粘i_發(fā)中,我們可能很隨意把數(shù)據(jù)庫密碼直接明文暴露在配置文件中,今天就來聊聊在springboot項(xiàng)目中如何對(duì)數(shù)據(jù)庫密碼進(jìn)行加密,感興趣的可以了解一下

前言

在我們?nèi)粘i_發(fā)中,我們可能很隨意把數(shù)據(jù)庫密碼直接明文暴露在配置文件中,在開發(fā)環(huán)境可以這么做,但是在生產(chǎn)環(huán)境,是相當(dāng)不建議這么做,畢竟安全無小事,誰也不知道哪天密碼就莫名其妙泄露了。今天就來聊聊在springboot項(xiàng)目中如何對(duì)數(shù)據(jù)庫密碼進(jìn)行加密

正文

方案一、使用druid數(shù)據(jù)庫連接池對(duì)數(shù)據(jù)庫密碼加密

1、pom.xml引入druid包

為了方便其他的操作,這邊直接引入druid的starter

<dependency>
   <groupId>com.alibaba</groupId>
   <artifactId>druid-spring-boot-starter</artifactId>
   <version>${druid.version}</version>
  </dependency>

2、利用com.alibaba.druid.filter.config.ConfigTools生成公私鑰

ps: 生成的方式有兩種,一種利用命令行生成,一種直接寫個(gè)工具類生成。本文示例直接采用工具類生成

工具類代碼如下

/**
 * alibaba druid加解密規(guī)則:
 * 明文密碼+私鑰(privateKey)加密=加密密碼
 * 加密密碼+公鑰(publicKey)解密=明文密碼
 */
public final class DruidEncryptorUtils {

    private static String privateKey;

    private static String publicKey;

    static {
        try {
            String[] keyPair = ConfigTools.genKeyPair(512);
            privateKey = keyPair[0];
            System.out.println(String.format("privateKey-->%s",privateKey));
            publicKey = keyPair[1];
            System.out.println(String.format("publicKey-->%s",publicKey));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        }
    }

    /**
     * 明文加密
     * @param plaintext
     * @return
     */
    @SneakyThrows
    public static String encode(String plaintext){
        System.out.println("明文字符串:" + plaintext);
        String ciphertext = ConfigTools.encrypt(privateKey,plaintext);
        System.out.println("加密后字符串:" + ciphertext);
        return ciphertext;
    }

    /**
     * 解密
     * @param ciphertext
     * @return
     */
    @SneakyThrows
    public static String decode(String ciphertext){
        System.out.println("加密字符串:" + ciphertext);
        String plaintext = ConfigTools.decrypt(publicKey,ciphertext);
        System.out.println("解密后的字符串:" + plaintext);

        return plaintext;
    }

3、修改數(shù)據(jù)庫的配置文件內(nèi)容信息

a 、 修改密碼
把密碼替換成用DruidEncryptorUtils這個(gè)工具類生成的密碼

 password: ${DATASOURCE_PWD:HB5FmUeAI1U81YJrT/T6awImFg1/Az5o8imy765WkVJouOubC2H80jqmZrr8L9zWKuzS/8aGzuQ4YySAkhywnA==}

b、 filter開啟config

 filter:
                config:
                    enabled: true

c、配置connectionProperties屬性

 connection-properties: config.decrypt=true;config.decrypt.key=${spring.datasource.publickey}

ps: spring.datasource.publickey為工具類生成的公鑰

附錄: 完整數(shù)據(jù)庫配置

spring:
    datasource:
        type: com.alibaba.druid.pool.DruidDataSource
        driverClassName: com.mysql.cj.jdbc.Driver
        url: ${DATASOURCE_URL:jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai}
        username: ${DATASOURCE_USERNAME:root}
        password: ${DATASOURCE_PWD:HB5FmUeAI1U81YJrT/T6awImFg1/Az5o8imy765WkVJouOubC2H80jqmZrr8L9zWKuzS/8aGzuQ4YySAkhywnA==}
        publickey: MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAIvP9xF4RCM4oFiu47NZY15iqNOAB9K2Ml9fiTLa05CWaXK7uFwBImR7xltZM1frl6ahWAXJB6a/FSjtJkTZUJECAwEAAQ==
        druid:
            # 初始連接數(shù)
            initialSize: 5
            # 最小連接池?cái)?shù)量
            minIdle: 10
            # 最大連接池?cái)?shù)量
            maxActive: 20
            # 配置獲取連接等待超時(shí)的時(shí)間
            maxWait: 60000
            # 配置間隔多久才進(jìn)行一次檢測,檢測需要關(guān)閉的空閑連接,單位是毫秒
            timeBetweenEvictionRunsMillis: 60000
            # 配置一個(gè)連接在池中最小生存的時(shí)間,單位是毫秒
            minEvictableIdleTimeMillis: 300000
            # 配置一個(gè)連接在池中最大生存的時(shí)間,單位是毫秒
            maxEvictableIdleTimeMillis: 900000
            # 配置檢測連接是否有效
            validationQuery: SELECT 1 FROM DUAL
            testWhileIdle: true
            testOnBorrow: false
            testOnReturn: false
            webStatFilter:
                enabled: true
            statViewServlet:
                enabled: true
                # 設(shè)置白名單,不填則允許所有訪問
                allow:
                url-pattern: /druid/*
                # 控制臺(tái)管理用戶名和密碼
                login-username:
                login-password:
            filter:
                stat:
                    enabled: true
                    # 慢SQL記錄
                    log-slow-sql: true
                    slow-sql-millis: 1000
                    merge-sql: true
                wall:
                    config:
                        multi-statement-allow: true
                config:
                    enabled: true
            connection-properties: config.decrypt=true;config.decrypt.key=${spring.datasource.publickey}

方案二:使用jasypt對(duì)數(shù)據(jù)庫密碼加密

1、pom.xml引入jasypt包

<dependency>
   <groupId>com.github.ulisesbocchio</groupId>
   <artifactId>jasypt-spring-boot-starter</artifactId>
   <version>${jasypt.verison}</version>
  </dependency>

2、利用jasypt提供的工具類對(duì)明文密碼進(jìn)行加密

加密工具類如下

public final class JasyptEncryptorUtils {


    private static final String salt = "lybgeek";

    private static BasicTextEncryptor basicTextEncryptor = new BasicTextEncryptor();

    static {
        basicTextEncryptor.setPassword(salt);
    }

    private JasyptEncryptorUtils(){}

    /**
     * 明文加密
     * @param plaintext
     * @return
     */
    public static String encode(String plaintext){
        System.out.println("明文字符串:" + plaintext);
        String ciphertext = basicTextEncryptor.encrypt(plaintext);
        System.out.println("加密后字符串:" + ciphertext);
        return ciphertext;
    }

    /**
     * 解密
     * @param ciphertext
     * @return
     */
    public static String decode(String ciphertext){
        System.out.println("加密字符串:" + ciphertext);
        ciphertext = "ENC(" + ciphertext + ")";
        if (PropertyValueEncryptionUtils.isEncryptedValue(ciphertext)){
            String plaintext = PropertyValueEncryptionUtils.decrypt(ciphertext,basicTextEncryptor);
            System.out.println("解密后的字符串:" + plaintext);
            return plaintext;
        }
        System.out.println("解密失敗");
        return "";
    }
}

3、修改數(shù)據(jù)庫的配置文件內(nèi)容信息

a、 用ENC包裹用JasyptEncryptorUtils 生成的加密串

password: ${DATASOURCE_PWD:ENC(P8m43qmzqN4c07DCTPey4Q==)}

b、 配置密鑰和指定加解密算法

jasypt:
    encryptor:
        password: lybgeek
        algorithm: PBEWithMD5AndDES
        iv-generator-classname: org.jasypt.iv.NoIvGenerator

因?yàn)槲夜ぞ哳愂褂玫氖羌咏饷艿墓ぞ哳愂荁asicTextEncryptor,其對(duì)應(yīng)配置加解密就是PBEWithMD5AndDES和org.jasypt.iv.NoIvGenerator

ps: 在生產(chǎn)環(huán)境中,建議使用如下方式配置密鑰,避免密鑰泄露

java -jar -Djasypt.encryptor.password=lybgeek

附錄: 完整數(shù)據(jù)庫配置

spring:
    datasource:
        type: com.alibaba.druid.pool.DruidDataSource
        driverClassName: com.mysql.cj.jdbc.Driver
        url: ${DATASOURCE_URL:ENC(kT/gwazwzaFNEp7OCbsgCQN7PHRohaTKJNdGVgLsW2cH67zqBVEq7mN0BTIXAeF4/Fvv4l7myLFx0y6ap4umod7C2VWgyRU5UQtKmdwzQN3hxVxktIkrFPn9DM6+YahM0xP+ppO9HaWqA2ral0ejBCvmor3WScJNHCAhI9kHjYc=)}
        username: ${DATASOURCE_USERNAME:ENC(rEQLlqM5nphqnsuPj3MlJw==)}
        password: ${DATASOURCE_PWD:ENC(P8m43qmzqN4c07DCTPey4Q==)}
        druid:
            # 初始連接數(shù)
            initialSize: 5
            # 最小連接池?cái)?shù)量
            minIdle: 10
            # 最大連接池?cái)?shù)量
            maxActive: 20
            # 配置獲取連接等待超時(shí)的時(shí)間
            maxWait: 60000
            # 配置間隔多久才進(jìn)行一次檢測,檢測需要關(guān)閉的空閑連接,單位是毫秒
            timeBetweenEvictionRunsMillis: 60000
            # 配置一個(gè)連接在池中最小生存的時(shí)間,單位是毫秒
            minEvictableIdleTimeMillis: 300000
            # 配置一個(gè)連接在池中最大生存的時(shí)間,單位是毫秒
            maxEvictableIdleTimeMillis: 900000
            # 配置檢測連接是否有效
            validationQuery: SELECT 1 FROM DUAL
            testWhileIdle: true
            testOnBorrow: false
            testOnReturn: false
            webStatFilter:
                enabled: true
            statViewServlet:
                enabled: true
                # 設(shè)置白名單,不填則允許所有訪問
                allow:
                url-pattern: /druid/*
                # 控制臺(tái)管理用戶名和密碼
                login-username:
                login-password:
            filter:
                stat:
                    enabled: true
                    # 慢SQL記錄
                    log-slow-sql: true
                    slow-sql-millis: 1000
                    merge-sql: true
                wall:
                    config:
                        multi-statement-allow: true
jasypt:
    encryptor:
        password: lybgeek
        algorithm: PBEWithMD5AndDES
        iv-generator-classname: org.jasypt.iv.NoIvGenerator

方案三:自定義實(shí)現(xiàn)

實(shí)現(xiàn)原理: 利用spring后置處理器修改DataSource

1、自定義加解密工具類

/**
 * 利用hutool封裝的加解密工具,以AES對(duì)稱加密算法為例
 */
public final class EncryptorUtils {

    private static String secretKey;



    static {
        secretKey = Hex.encodeHexString(SecureUtil.generateKey(SymmetricAlgorithm.AES.getValue()).getEncoded());
        System.out.println("secretKey-->" + secretKey);
        System.out.println("--------------------------------------------------------------------------------------");
    }

    /**
     * 明文加密
     * @param plaintext
     * @return
     */
    @SneakyThrows
    public static String encode(String plaintext){
        System.out.println("明文字符串:" + plaintext);
        byte[] key = Hex.decodeHex(secretKey.toCharArray());
        String ciphertext =  SecureUtil.aes(key).encryptHex(plaintext);
        System.out.println("加密后字符串:" + ciphertext);

        return ciphertext;
    }

    /**
     * 解密
     * @param ciphertext
     * @return
     */
    @SneakyThrows
    public static String decode(String ciphertext){
        System.out.println("加密字符串:" + ciphertext);
        byte[] key = Hex.decodeHex(secretKey.toCharArray());
        String plaintext = SecureUtil.aes(key).decryptStr(ciphertext);
        System.out.println("解密后的字符串:" + plaintext);

        return plaintext;
    }

    /**
     * 明文加密
     * @param plaintext
     * @return
     */
    @SneakyThrows
    public static String encode(String secretKey,String plaintext){
        System.out.println("明文字符串:" + plaintext);
        byte[] key = Hex.decodeHex(secretKey.toCharArray());
        String ciphertext =  SecureUtil.aes(key).encryptHex(plaintext);
        System.out.println("加密后字符串:" + ciphertext);

        return ciphertext;
    }

    /**
     * 解密
     * @param ciphertext
     * @return
     */
    @SneakyThrows
    public static String decode(String secretKey,String ciphertext){
        System.out.println("加密字符串:" + ciphertext);
        byte[] key = Hex.decodeHex(secretKey.toCharArray());
        String plaintext = SecureUtil.aes(key).decryptStr(ciphertext);
        System.out.println("解密后的字符串:" + plaintext);

        return plaintext;
    }
}

2、編寫后置處理器

public class DruidDataSourceEncyptBeanPostProcessor implements BeanPostProcessor {

    private CustomEncryptProperties customEncryptProperties;

    private DataSourceProperties dataSourceProperties;

    public DruidDataSourceEncyptBeanPostProcessor(CustomEncryptProperties customEncryptProperties, DataSourceProperties dataSourceProperties) {
        this.customEncryptProperties = customEncryptProperties;
        this.dataSourceProperties = dataSourceProperties;
    }



    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if(bean instanceof DruidDataSource){
            if(customEncryptProperties.isEnabled()){
                DruidDataSource druidDataSource = (DruidDataSource)bean;
                System.out.println("--------------------------------------------------------------------------------------");
                String username = dataSourceProperties.getUsername();
                druidDataSource.setUsername(EncryptorUtils.decode(customEncryptProperties.getSecretKey(),username));
                System.out.println("--------------------------------------------------------------------------------------");
                String password = dataSourceProperties.getPassword();
                druidDataSource.setPassword(EncryptorUtils.decode(customEncryptProperties.getSecretKey(),password));
                System.out.println("--------------------------------------------------------------------------------------");
                String url = dataSourceProperties.getUrl();
                druidDataSource.setUrl(EncryptorUtils.decode(customEncryptProperties.getSecretKey(),url));
                System.out.println("--------------------------------------------------------------------------------------");
            }

        }
        return bean;
    }
}

3、修改數(shù)據(jù)庫的配置文件內(nèi)容信息

a 、 修改密碼
把密碼替換成用自定義加密工具類生成的加密密碼

  password: ${DATASOURCE_PWD:fb31cdd78a5fa2c43f530b849f1135e7}

b 、 指定密鑰和開啟加密功能

custom:
    encrypt:
        enabled: true
        secret-key: 2f8ba810011e0973728afa3f28a0ecb6

ps: 同理secret-key最好也不要直接暴露在配置文件中,可以用-Dcustom.encrypt.secret-key指定
附錄: 完整數(shù)據(jù)庫配置

spring:
    datasource:
        type: com.alibaba.druid.pool.DruidDataSource
        driverClassName: com.mysql.cj.jdbc.Driver
        url: ${DATASOURCE_URL:dcb268cf3a2626381d2bc5c96f94fb3d7f99352e0e392362cb818a321b0ca61f3a8dad3aeb084242b745c61a1d3dc244ed1484bf745c858c44560dde10e60e90ac65f77ce2926676df7af6b35aefd2bb984ff9a868f1f9052ee9cae5572fa015b66a602f32df39fb1bbc36e04cc0f148e4d610a3e5d54f2eb7c57e4729c9d7b4}
        username: ${DATASOURCE_USERNAME:61db3bf3c6d3fe3ce87549c1af1e9061}
        password: ${DATASOURCE_PWD:fb31cdd78a5fa2c43f530b849f1135e7}
        druid:
            # 初始連接數(shù)
            initialSize: 5
            # 最小連接池?cái)?shù)量
            minIdle: 10
            # 最大連接池?cái)?shù)量
            maxActive: 20
            # 配置獲取連接等待超時(shí)的時(shí)間
            maxWait: 60000
            # 配置間隔多久才進(jìn)行一次檢測,檢測需要關(guān)閉的空閑連接,單位是毫秒
            timeBetweenEvictionRunsMillis: 60000
            # 配置一個(gè)連接在池中最小生存的時(shí)間,單位是毫秒
            minEvictableIdleTimeMillis: 300000
            # 配置一個(gè)連接在池中最大生存的時(shí)間,單位是毫秒
            maxEvictableIdleTimeMillis: 900000
            # 配置檢測連接是否有效
            validationQuery: SELECT 1 FROM DUAL
            testWhileIdle: true
            testOnBorrow: false
            testOnReturn: false
            webStatFilter:
                enabled: true
            statViewServlet:
                enabled: true
                # 設(shè)置白名單,不填則允許所有訪問
                allow:
                url-pattern: /druid/*
                # 控制臺(tái)管理用戶名和密碼
                login-username:
                login-password:
            filter:
                stat:
                    enabled: true
                    # 慢SQL記錄
                    log-slow-sql: true
                    slow-sql-millis: 1000
                    merge-sql: true
                wall:
                    config:
                        multi-statement-allow: true
custom:
    encrypt:
        enabled: true
        secret-key: 2f8ba810011e0973728afa3f28a0ecb6

總結(jié)

上面三種方案,個(gè)人比較推薦用jasypt這種方案,因?yàn)樗粌H可以對(duì)密碼加密,也可以對(duì)其他內(nèi)容加密。而druid只能對(duì)數(shù)據(jù)庫密碼加密。至于自定義的方案,屬于練手,畢竟開源已經(jīng)有的東西,就不要再自己造輪子了。
最后還有一個(gè)注意點(diǎn)就是jasypt如果是高于2版本,且以低于3.0.3,會(huì)導(dǎo)致配置中心,比如apollo或者nacos的動(dòng)態(tài)刷新配置失效(最新版的3.0.3官方說已經(jīng)修復(fù)了這個(gè)問題)。

如果有使用配置中心的話,jasypt推薦使用3版本以下,或者使用3.0.3版本
demo鏈接

到此這篇關(guān)于springboot項(xiàng)目數(shù)據(jù)庫密碼如何加密的文章就介紹到這了,更多相關(guān)springboot數(shù)據(jù)庫密碼加密內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • mybatisplus 的SQL攔截器實(shí)現(xiàn)關(guān)聯(lián)查詢功能

    mybatisplus 的SQL攔截器實(shí)現(xiàn)關(guān)聯(lián)查詢功能

    大家都知道m(xù)ybatisplus不支持關(guān)聯(lián)查詢,后來學(xué)習(xí)研究發(fā)現(xiàn)mybatisplus的SQL攔截器可以實(shí)現(xiàn)這一操作,下面小編給大家分享我的demo實(shí)現(xiàn)基本的關(guān)聯(lián)查詢功能沒有問題,對(duì)mybatisplus關(guān)聯(lián)查詢相關(guān)知識(shí)感興趣的朋友一起看看吧
    2021-06-06
  • Java深入數(shù)據(jù)結(jié)構(gòu)理解掌握抽象類與接口

    Java深入數(shù)據(jù)結(jié)構(gòu)理解掌握抽象類與接口

    在類中沒有包含足夠的信息來描繪一個(gè)具體的對(duì)象,這樣的類稱為抽象類,接口是Java中最重要的概念之一,它可以被理解為一種特殊的類,不同的是接口的成員沒有執(zhí)行體,是由全局常量和公共的抽象方法所組成,本文給大家介紹Java抽象類和接口,感興趣的朋友一起看看吧
    2022-05-05
  • 淺談Java中的克隆close()和賦值引用的區(qū)別

    淺談Java中的克隆close()和賦值引用的區(qū)別

    下面小編就為大家?guī)硪黄獪\談Java中的克隆close()和賦值引用的區(qū)別。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2016-09-09
  • Java使用PDFBox實(shí)現(xiàn)操作PDF文檔

    Java使用PDFBox實(shí)現(xiàn)操作PDF文檔

    這篇文章主要為大家詳細(xì)介紹了Java如何使用PDFBox實(shí)現(xiàn)操作PDF文檔,例如添加本地圖片、添加網(wǎng)絡(luò)圖片、圖片寬高自適應(yīng)、圖片水平垂直居中對(duì)齊等功能,需要的可以了解下
    2024-03-03
  • SpringQuartz集群支持JDBC存儲(chǔ)與分布式執(zhí)行的最佳實(shí)踐

    SpringQuartz集群支持JDBC存儲(chǔ)與分布式執(zhí)行的最佳實(shí)踐

    SpringQuartz集群通過JDBC存儲(chǔ)和分布式執(zhí)行機(jī)制,有效解決了單點(diǎn)故障和擴(kuò)展性問題,本文將詳細(xì)介紹SpringQuartz集群支持的實(shí)現(xiàn)原理、配置方法和最佳實(shí)踐,助力開發(fā)者構(gòu)建穩(wěn)定可靠的分布式調(diào)度系統(tǒng),感興趣的朋友一起看看吧
    2025-04-04
  • Websocket如何保證接收消息完整性

    Websocket如何保證接收消息完整性

    用springboot起了個(gè)websocket服務(wù)端,有時(shí)候客戶端發(fā)來的消息過長,無法接收完整,需要進(jìn)行額外的處理,這篇文章主要介紹了Websocket如何保證接收消息完整性,需要的朋友可以參考下
    2023-09-09
  • spring帶bean和config如何通過main啟動(dòng)測試

    spring帶bean和config如何通過main啟動(dòng)測試

    這篇文章主要介紹了spring帶bean和config,通過main啟動(dòng)測試,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2023-07-07
  • 教你怎么用java實(shí)現(xiàn)客戶端與服務(wù)器一問一答

    教你怎么用java實(shí)現(xiàn)客戶端與服務(wù)器一問一答

    這篇文章主要介紹了教你怎么用java實(shí)現(xiàn)客戶端與服務(wù)器一問一答,文中有非常詳細(xì)的代碼示例,對(duì)正在學(xué)習(xí)java的小伙伴們有非常好的幫助,需要的朋友可以參考下
    2021-04-04
  • elasticsearch集群查詢超10000的解決方案

    elasticsearch集群查詢超10000的解決方案

    ES為了避免用戶的過大分頁請(qǐng)求造成ES服務(wù)所在機(jī)器內(nèi)存溢出,默認(rèn)對(duì)深度分頁的條數(shù)進(jìn)行了限制,默認(rèn)的最大條數(shù)是10000條,這篇文章主要給大家介紹了關(guān)于elasticsearch集群查詢超10000的解決方案,需要的朋友可以參考下
    2024-08-08
  • 簡單講解java中throws與throw的區(qū)別

    簡單講解java中throws與throw的區(qū)別

    這篇文章主要介紹了簡單講解java中throws與throw的區(qū)別,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-07-07

最新評(píng)論

安龙县| 吴桥县| 朝阳县| 黔西| 丰县| 夹江县| 射阳县| 邵阳县| 方山县| 惠州市| 新绛县| 扎鲁特旗| 黎城县| 凌云县| 游戏| 滁州市| 闽侯县| 余干县| 平罗县| 泰州市| 庆元县| 萝北县| 正镶白旗| 虎林市| 虹口区| 岳西县| 偃师市| 内江市| 永修县| 北辰区| 华池县| 夹江县| 福建省| 河北区| 三亚市| 固原市| 玉林市| 卢氏县| 内乡县| 西城区| 宝丰县|