生成machineKey密鑰


參考資料

http://support.microsoft.com/kb/312906?wa=wsignin1.0

ASP.NET 配置概述

 

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();
        }
    }
}

 

格式:
<machineKey validationKey="AutoGenerate|value[,IsolateApps]"
            decryptionKey="AutoGenerate|value[,IsolateApps]"
            validation="SHA1|MD5|3DES"/>
樣例:
<machineKey validationKey="77A439696CB986680CEE71CB179BBFFA75AA0FE3AB875B278EE8C54536F2B364E1BDAB809BA26D4263C33863D29B4040CD55D9665E8002D26F04A80C701A4067" decryptionKey="79378FA6BD4BE839D0B8C1E94367A820C77F38FA9CD8C7F0" validation="SHA1"/>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM