.NetCore分散式部署中的DataProtection密鑰安全性

来源:https://www.cnblogs.com/nasha/archive/2019/01/12/10260158.html
-Advertisement-
Play Games

在.NetCore中預設使用DataProtection來保護數據,例如Cooike等。一般情況下DataProtection生成的密鑰會被加密後存儲,例如預設的文件存儲 可以看到使用了Windows DPAPI加密。 但是如果更改預設設置例如使用的外部存儲如redis則此時密鑰預設是不加密的 微軟 ...


在.NetCore中預設使用DataProtection來保護數據,例如Cooike等。一般情況下DataProtection生成的密鑰會被加密後存儲,例如預設的文件存儲

可以看到使用了Windows DPAPI加密。

但是如果更改預設設置例如使用的外部存儲如redis則此時密鑰預設是不加密的

微軟說明如下

警告密鑰未加密,這個時候如果redis被破解,系統的密鑰也就泄漏了。

微軟提供了2個介面IXmlEncryptor,IXmlDecryptor來實現密鑰的加密解密,下麵使用AES來簡單現實,也可以替換為任何加密方式

namespace Microsoft.AspNetCore.DataProtection
{
    /// <summary>
    /// Extensions for configuring data protection using an <see cref="IDataProtectionBuilder"/>.
    /// </summary>
    public static class DataProtectionBuilderExtensions
    {
        /// <summary>
        /// Configures keys to be encrypted with AES before being persisted to
        /// storage.
        /// </summary>
        /// <param name="builder">The <see cref="IDataProtectionBuilder"/>.</param>
        /// use on the local machine, 'false' if the key should only be decryptable by the current
        /// Windows user account.</param>
        /// <returns>A reference to the <see cref="IDataProtectionBuilder" /> after this operation has completed.</returns>
        public static IDataProtectionBuilder ProtectKeysWithAES(this IDataProtectionBuilder builder)
        {
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }

            builder.Services.AddSingleton<IConfigureOptions<KeyManagementOptions>>(services =>
            {
                //var loggerFactory = services.GetService<ILoggerFactory>() ?? NullLoggerFactory.Instance;
                return new ConfigureOptions<KeyManagementOptions>(options =>
                {
                    options.XmlEncryptor = new AesXmlEncryptor();
                });
            });

            return builder;
        }
    }
    /// <summary>
    /// An <see cref="IXmlEncryptor"/> that encrypts XML elements with a Aes encryptor.
    /// </summary>
    sealed class AesXmlEncryptor : IXmlEncryptor
    {
        /// <summary>
        /// Encrypts the specified <see cref="XElement"/> with a null encryptor, i.e.,
        /// by returning the original value of <paramref name="plaintextElement"/> unencrypted.
        /// </summary>
        /// <param name="plaintextElement">The plaintext to echo back.</param>
        /// <returns>
        /// An <see cref="EncryptedXmlInfo"/> that contains the null-encrypted value of
        /// <paramref name="plaintextElement"/> along with information about how to
        /// decrypt it.
        /// </returns>
        public EncryptedXmlInfo Encrypt(XElement plaintextElement)
        {
            if (plaintextElement == null)
            {
                throw new ArgumentNullException(nameof(plaintextElement));
            }
            // <encryptedKey>
            //   <!-- This key is encrypted with {provider}. -->
            //   <value>{base64}</value>
            // </encryptedKey>

            var Jsonxmlstr =JsonConvert.SerializeObject(plaintextElement);
            var EncryptedData = EncryptHelper.AESEncrypt(Jsonxmlstr, "b587be32-0420-4eb1-89c6-01bb999e18fe");
            var newElement = new XElement("encryptedKey",
                new XComment(" This key is encrypted with AES."),
                new XElement("value",EncryptedData));

            return new EncryptedXmlInfo(newElement, typeof(AesXmlDecryptor));
        }
    }
    /// <summary>
    /// An <see cref="IXmlDecryptor"/> that decrypts XML elements with a Aes decryptor.
    /// </summary>
    sealed class AesXmlDecryptor : IXmlDecryptor
    {
        /// <summary>
        /// Decrypts the specified XML element.
        /// </summary>
        /// <param name="encryptedElement">An encrypted XML element.</param>
        /// <returns>The decrypted form of <paramref name="encryptedElement"/>.</returns>
        public XElement Decrypt(XElement encryptedElement)
        {
            if (encryptedElement == null)
            {
                throw new ArgumentNullException(nameof(encryptedElement));
            }

            // <encryptedKey>
            //   <!-- This key is encrypted with {provider}. -->
            //   <value>{base64}</value>
            // </encryptedKey>
            var EncryptedData=(string)encryptedElement.Element("value");
            var Jsonxmlstr = EncryptHelper.AESDecrypt(EncryptedData, "b587be32-0420-4eb1-89c6-01bb999e18fe");

            // Return a clone of the single child node.
            return JsonConvert.DeserializeObject<XElement>(Jsonxmlstr);
        }
    }
    #region AES
    public class EncryptHelper
    {
        static readonly byte[] AES_IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF, 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
        /// <summary>
        /// AES加密演算法
        /// </summary>
        /// <param name="encryptString">加密前字元串</param>
        /// <param name="keytype">秘鑰</param>
        /// <returns></returns>
        public static string AESEncrypt(string encryptString, string encryptKey)
        {
            if (string.IsNullOrWhiteSpace(encryptString)) return null;
            if (string.IsNullOrWhiteSpace(encryptKey)) return null;
            encryptKey = encryptKey.PadRight(32, ' ');
            byte[] keyBytes = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 32));
            using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider())
            {
                aesAlg.Key = keyBytes;
                aesAlg.IV = AES_IV;
                ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
                using (MemoryStream msEncrypt = new MemoryStream())
                {
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                        {
                            swEncrypt.Write(encryptString);
                        }
                        byte[] bytes = msEncrypt.ToArray();
                        return Convert.ToBase64String(bytes).Replace('+', '-').Replace('/', '_');
                    }
                }
            }
        }
        /// <summary>
        /// AES解密演算法
        /// </summary>
        /// <param name="decryptString">解密前的字元串</param>
        /// <param name="keytype">秘鑰</param>
        /// <returns></returns>
        public static string AESDecrypt(string decryptString, string decryptKey)
        {
            if (string.IsNullOrWhiteSpace(decryptString)) return null;
            decryptString = decryptString.Replace('-', '+').Replace('_', '/');
            if (string.IsNullOrWhiteSpace(decryptKey)) return null;
            decryptKey = decryptKey.PadRight(32, ' ');
            byte[] keyBytes = Encoding.UTF8.GetBytes(decryptKey.Substring(0, 32));
            Byte[] inputBytes = Convert.FromBase64String(decryptString);
            using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider())
            {
                aesAlg.Key = keyBytes;
                aesAlg.IV = AES_IV;
                ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
                using (MemoryStream msEncrypt = new MemoryStream(inputBytes))
                {
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader srEncrypt = new StreamReader(csEncrypt))
                        {
                            return srEncrypt.ReadToEnd();
                        }
                    }
                }
            }
        }
    }
    #endregion
}
View Code

 

調用也很簡單.ProtectKeysWithAES()即可

  services.AddDataProtection().SetApplicationName("DataProtection").PersistKeysToStackExchangeRedis(ConnectionMultiplexer.Connect(RedisConnection), "DataProtection-Keys").ProtectKeysWithAES();

加密後的密鑰如下

註:在生成密鑰之前要刪除之前的密鑰,不然會使用舊密鑰而不生成新的密鑰直到密鑰過期。

 

對於AES所使用密鑰也要進行保護,可以使用第三方密鑰存儲庫如Azure 密鑰保管庫,或者也可以使用X509證書來來加密。

 github  https://github.com/saber-wang/DataProtection


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 在Python中支持兩種迴圈格式:while和for。這兩種迴圈的類型不同: while是通過條件判斷的真假來迴圈的 for是通過in的元素存在性測試來迴圈的 更通俗地說,while是普通的步進迴圈,for是迭代遍歷。 for的關鍵字在於"迭代"和"遍歷"。首先要有容器數據結構(如列表、字元串)存儲 ...
  • 前言 在多核時代,高併發時代,對系統並行處理能力有很高要求。多線程就是這個時代最好的產物。通過使用多線程可以增強系統並行處理能力,提高CPU資源的有效利用;從而提高系統的處理能力。常見應用場景如:多視窗售票、生產消費模式、非同步提交信息(如日誌、發送消息),只要系統需要並行任務處理的場景都可以考慮使用 ...
  • Object類是所有類的始祖,如果一個類沒有使用extends關鍵字明確地指出它的父類,那麼它就會繼承Object類。可以說,所有類都直接或間接地繼承了Object類。本文將對Object類中常用的方法進行介紹。 ...
  • Zip 方法允許把序列中的元素通過交織將 IEnumerable 序列連接在一起。Zip 是一種基於 IEnumerable 的擴展方法。例如,將具有年齡的名稱集合壓縮在一起: 將會生成包含三個元素的 IEnumerable <string>: image.png image.png 如果一個序列比 ...
  • 【譯】《C# 小技巧 -- 編寫更優雅的 C#》原書名《C# Tips -- Write Better C#》 目錄 介紹(Introduction) 第一部分:各種小技巧(Part 1: Assorted Tips) 使用 LINQ 合併 IEnumerable 序列(Merging IEnume ...
  • 使用WPF的裝飾器(Adorner)實現圖片拖拉變形,DrawingVisual高保真合成圖片。效果如下: 源碼:https://gitee.com/orchis/ImageFotoMix.git ...
  • 處理HTTP請求的11個階段如下圖:序號階段指令備註1POST_READrealip獲取客戶端真實IP2SERVER_REWRITErewrite3FIND_CONFIG4REWRITErewrite5POST_REWRITE6PRE_ACCESSlimit_conn, limit_req7ACCE... ...
  • 問題: 定義了預設TextBlock樣式後,再次自定義下拉框 or 其他控制項 ,當內部含有TextBlock時,設置控制項的字體相關樣式無效,系統始終使用TextBlock設置預設樣式 解決方案: 為相關控制項定義數據模板,為內部TextBlock添加樣式資源,指向預設資源。 具體為啥會有這種問題不清楚 ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...