欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

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

前言

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

正文

方案一、使用druid數(shù)據(jù)庫連接池對數(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: 生成的方式有兩種,一種利用命令行生成,一種直接寫個工具類生成。本文示例直接采用工具類生成

工具類代碼如下

/**
 * 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這個工具類生成的密碼

 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
            # 最小連接池數(shù)量
            minIdle: 10
            # 最大連接池數(shù)量
            maxActive: 20
            # 配置獲取連接等待超時的時間
            maxWait: 60000
            # 配置間隔多久才進行一次檢測,檢測需要關(guān)閉的空閑連接,單位是毫秒
            timeBetweenEvictionRunsMillis: 60000
            # 配置一個連接在池中最小生存的時間,單位是毫秒
            minEvictableIdleTimeMillis: 300000
            # 配置一個連接在池中最大生存的時間,單位是毫秒
            maxEvictableIdleTimeMillis: 900000
            # 配置檢測連接是否有效
            validationQuery: SELECT 1 FROM DUAL
            testWhileIdle: true
            testOnBorrow: false
            testOnReturn: false
            webStatFilter:
                enabled: true
            statViewServlet:
                enabled: true
                # 設(shè)置白名單,不填則允許所有訪問
                allow:
                url-pattern: /druid/*
                # 控制臺管理用戶名和密碼
                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對數(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提供的工具類對明文密碼進行加密

加密工具類如下

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

因為我工具類使用的是加解密的工具類是BasicTextEncryptor,其對應(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
            # 最小連接池數(shù)量
            minIdle: 10
            # 最大連接池數(shù)量
            maxActive: 20
            # 配置獲取連接等待超時的時間
            maxWait: 60000
            # 配置間隔多久才進行一次檢測,檢測需要關(guān)閉的空閑連接,單位是毫秒
            timeBetweenEvictionRunsMillis: 60000
            # 配置一個連接在池中最小生存的時間,單位是毫秒
            minEvictableIdleTimeMillis: 300000
            # 配置一個連接在池中最大生存的時間,單位是毫秒
            maxEvictableIdleTimeMillis: 900000
            # 配置檢測連接是否有效
            validationQuery: SELECT 1 FROM DUAL
            testWhileIdle: true
            testOnBorrow: false
            testOnReturn: false
            webStatFilter:
                enabled: true
            statViewServlet:
                enabled: true
                # 設(shè)置白名單,不填則允許所有訪問
                allow:
                url-pattern: /druid/*
                # 控制臺管理用戶名和密碼
                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

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

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

1、自定義加解密工具類

/**
 * 利用hutool封裝的加解密工具,以AES對稱加密算法為例
 */
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
            # 最小連接池數(shù)量
            minIdle: 10
            # 最大連接池數(shù)量
            maxActive: 20
            # 配置獲取連接等待超時的時間
            maxWait: 60000
            # 配置間隔多久才進行一次檢測,檢測需要關(guān)閉的空閑連接,單位是毫秒
            timeBetweenEvictionRunsMillis: 60000
            # 配置一個連接在池中最小生存的時間,單位是毫秒
            minEvictableIdleTimeMillis: 300000
            # 配置一個連接在池中最大生存的時間,單位是毫秒
            maxEvictableIdleTimeMillis: 900000
            # 配置檢測連接是否有效
            validationQuery: SELECT 1 FROM DUAL
            testWhileIdle: true
            testOnBorrow: false
            testOnReturn: false
            webStatFilter:
                enabled: true
            statViewServlet:
                enabled: true
                # 設(shè)置白名單,不填則允許所有訪問
                allow:
                url-pattern: /druid/*
                # 控制臺管理用戶名和密碼
                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é)

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

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

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

相關(guān)文章

  • 異常排查記錄amqp協(xié)議鏈接陷阱

    異常排查記錄amqp協(xié)議鏈接陷阱

    這篇文章主要介紹了一次關(guān)于amqp協(xié)議鏈接陷阱-An?unexpected?connection?driver?error?occured的異常排查記錄,有需要的朋友可以借鑒參考下,希望能夠有所幫助
    2022-02-02
  • Idea導(dǎo)入多個maven項目到同一目錄下的方法示例

    Idea導(dǎo)入多個maven項目到同一目錄下的方法示例

    這篇文章主要介紹了Idea導(dǎo)入多個maven項目到同一目錄下,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-07-07
  • Java注解使用及原理解析

    Java注解使用及原理解析

    這篇文章主要介紹了Java注解使用及原理解析,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-06-06
  • Java集合Stream流操作的基本使用教程分享

    Java集合Stream流操作的基本使用教程分享

    流操作并不會影響原來的集合,可以簡單認為,流操作是把集合中的一個元素逐個復(fù)制放到一個首尾相接的流動的水槽中。這篇文章整理了Stream流操作的基本使用,需要的可以參考一下
    2023-02-02
  • Java基于servlet監(jiān)聽器實現(xiàn)在線人數(shù)監(jiān)控功能的方法

    Java基于servlet監(jiān)聽器實現(xiàn)在線人數(shù)監(jiān)控功能的方法

    這篇文章主要介紹了Java基于servlet監(jiān)聽器實現(xiàn)在線人數(shù)監(jiān)控功能的方法,結(jié)合實例形式分析了ServletContextListener監(jiān)聽功能的相關(guān)使用步驟與操作技巧,需要的朋友可以參考下
    2018-01-01
  • Java設(shè)計模式之備忘錄模式

    Java設(shè)計模式之備忘錄模式

    這篇文章主要介紹了Java設(shè)計模式之備忘錄模式,備忘錄模式(Memento Pattern),屬于行為型設(shè)計模式,目的是用于保存一個對象在某一時刻的狀態(tài),以便于在將來某個時刻根據(jù)此狀態(tài)恢復(fù)該對象,需要的朋友可以參考下
    2023-12-12
  • SpringBoot項目使用mybatis-plus代碼生成的實例詳解

    SpringBoot項目使用mybatis-plus代碼生成的實例詳解

    mybatis-plus是mybatis的增強,不對mybatis做任何改變,涵蓋了代碼生成,自定義ID生成器,快速實現(xiàn)CRUD,自動分頁,邏輯刪除等功能。本文就來講講SpringBoot項目如何使用mybatis-plus實現(xiàn)代碼生成,需要的可以了解一下
    2022-10-10
  • SpringBoot 如何使用RestTemplate來調(diào)用接口

    SpringBoot 如何使用RestTemplate來調(diào)用接口

    這篇文章主要介紹了SpringBoot 如何使用RestTemplate來調(diào)用接口方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-10-10
  • Linux下JDK安裝教程

    Linux下JDK安裝教程

    這篇文章主要為大家詳細介紹了Linux下JDK安裝教程,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-06-06
  • Spring Security基于散列加密方案實現(xiàn)自動登錄功能

    Spring Security基于散列加密方案實現(xiàn)自動登錄功能

    為了提高項目的用戶體驗,我們可以在項目中添加自動登錄功能,當(dāng)然也要給用戶提供退出登錄的功能。接下來學(xué)習(xí)下Spring Security基于散列加密方案實現(xiàn)自動登錄功能,一起看看吧
    2021-09-09

最新評論