1. 程式人生 > >配置文件——節點<machineKey>的作用,強隨機生成

配置文件——節點<machineKey>的作用,強隨機生成

mac onf 特定 create per 數字 mar {0} pen

<machineKey>這個節允許你設置用於加密數據和創建數字簽名的服務器特定的密鑰。ASP.NET自動使用它來保護表單驗證Cookie,你也可以將它用於受保護的視圖狀態數據。同時,這個密鑰還用於驗證進程外的會話狀態提供程序。

如果你在使用Web集群並在多臺計算機上運行同一個應用程序,如果對頁面的請求由一臺計算機處理,而頁面回發又由另一臺計算機處理,第二個服務器就不能解 密來自第一臺服務器的視圖狀態和表單Cookie。這個問題之所以會發生,是因為兩臺服務器使用了不同的密鑰。

要解決這個問題,你必須顯式的在machine.config文件中定義這個密鑰:

<machineKey validationKey = "6efa......." decryptionKey = "ACE09876A7......." />

其中,validationKey 的值可以是48到128個字符長,強烈建議使用可用的最長密鑰。decryptionKey 的值可以是16到48字符長,建議使用48字符長。

自己去手動創建驗證密鑰和解密密鑰並沒有多大的意義。如果你這麽做的話,它們可能隨機性不足,這就可能允許某種類型的攻擊。更好的辦法是使用代碼 和.NET加密類(System.Security.Cryptography 命名空間)生成隨機密鑰,代碼如下:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 using System; using System.Text; using System.Security.Cryptography; namespace Crypto
{ public class KeyCreator { /// <summary> /// 生成machineKey密鑰 /// </summary> /// <param name="args"></param> /// <remarks> /// 參數: /// 第一個參數是用於創建 decryptionKey 屬性的字節數。 /// 第二個參數是用於創建 validationKey 屬性的字節數。 /// 註意:所創建的十六進制字符串的大小是從命令行傳入值的大小的兩倍。例如,如果您為密鑰指定 24 字節,則轉換後相應的字符串長度為 48 字節。 /// decryptionKey 的有效值為 8 或 24。此屬性將為數據加密標準 (DES) 創建一個 16 字節密鑰,或者為三重 DES 創建一個 48 字節密鑰。 /// validationKey 的有效值為 20 到 64。此屬性將創建長度從 40 到 128 字節的密鑰。 /// 代碼的輸出是一個完整的<machineKey>元素,您可以將其復制並粘貼到Machine.config文件中。 /// </remarks> public static void Main(String[] args) { String[] commandLineArgs = System.Environment.GetCommandLineArgs(); string decryptionKey = CreateKey(System.Convert.ToInt32(commandLineArgs[1])); string validationKey = CreateKey(System.Convert.ToInt32(commandLineArgs[2])); Console.WriteLine("<machineKey validationKey=\"{0}\" decryptionKey=\"{1}\" validation=\"SHA1\"/>", validationKey, decryptionKey); } static String CreateKey(int numBytes) { RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); byte[] buff = new byte[numBytes]; rng.GetBytes(buff); return BytesToHexString(buff); } static String BytesToHexString(byte[] bytes) { StringBuilder hexString = new StringBuilder(64); for (int counter = 0; counter < bytes.Length; counter++) { hexString.Append(String.Format("{0:X2}", bytes[counter])); } return hexString.ToString(); } } }

使用這個方法可以創建需要的密鑰,然後可以復制這些信息並粘貼配置文件文件中,這要比手工創建密鑰更安全,更便捷。

另外可以使用工具生成:http://www.aspnetresources.com/tools/keycreator.aspx

配置文件——節點<machineKey>的作用,強隨機生成