本文是從ASP.NE T 1.1升級到ASP.NET 2.0需要考慮的Cookie問題的補充,通過範例程式碼說明如何通過反射在ASP.NET 1.1與ASP.NET 2.0中擷取隨機產生的cookie加密與驗證密鑰。
ASP.NET 1.1範例程式碼: object machineKeyConfig = HttpContext.Current.GetConfig("system.web/machineKey");
//得到System.Web.Configuration.MachineKey+MachineKeyConfig的執行個體,MachineKeyConfig是MachineKey的嵌套類
Type machineKeyType = machineKeyConfig.GetType().Assembly.GetType("System.Web.Configuration.MachineKey");
//得到System.Web.Configuration.MachineKey類型
BindingFlags bf = BindingFlags.NonPublic | BindingFlags.Static;
//設定綁定標誌
MethodInfo byteArrayToHexString = machineKeyType.GetMethod("ByteArrayToHexString", bf);
//通過反射擷取MachineKey中的ByteArrayToHexString方法,該方法用於將位元組數群組轉換為16進位表示的字串
Byte[] validationKey = (Byte[])machineKeyType.GetField("s_validationKey",bf).GetValue(machineKeyConfig);
//擷取驗證密鑰位元組數組
SymmetricAlgorithm algorithm = (SymmetricAlgorithm)machineKeyType.GetField("s_oDes",bf).GetValue(machineKeyConfig);
Byte[] decryptionKey = algorithm.Key;
//擷取加密金鑰位元組數組
string ValidationKey = (string)byteArrayToHexString.Invoke(null,new object[]{validationKey,validationKey.Length});
//將驗證密鑰位元組數群組轉換為16進位表示的字串
string DecryptionKey = (string)byteArrayToHexString.Invoke(null,new object[]{decryptionKey,decryptionKey.Length});
//將加密金鑰位元組數群組轉換為16進位表示的字串
ASP.NET 2.0範例程式碼: System.Web.Configuration.MachineKeySection machineKeySection = new System.Web.Configuration.MachineKeySection();
//直接建立MachineKeySection的執行個體,ASP.NET 2.0中用machineKeySection取代ASP.NET 1.1中的MachineKey,並且可以直接存取,沒有被internal保護。
Type type = typeof(System.Web.Configuration.MachineKeySection);//或者machineKeySection.GetType();
PropertyInfo propertyInfo = type.GetProperty("ValidationKeyInternal", BindingFlags.NonPublic | BindingFlags.Instance);
Byte[] validationKeyArray = (Byte[])propertyInfo.GetValue(machineKeySection, null);
//擷取隨機產生的驗證密鑰位元組數組
propertyInfo = type.GetProperty("DecryptionKeyInternal", BindingFlags.NonPublic | BindingFlags.Instance);
Byte[] decryptionKeyArray = (Byte[])propertyInfo.GetValue(machineKeySection, null);
//擷取隨機產生的加密金鑰位元組數組
MethodInfo byteArrayToHexString = type.GetMethod("ByteArrayToHexString", BindingFlags.Static | BindingFlags.NonPublic);
//通過反射擷取MachineKeySection中的ByteArrayToHexString方法,該方法用於將位元組數群組轉換為16進位表示的字串
string validationKey = (string)byteArrayToHexString.Invoke(null, new object[] { validationKeyArray, validationKeyArray.Length });
//將驗證密鑰位元組數群組轉換為16進位表示的字串
string DecryptionKey = (string)byteArrayToHexString.Invoke(null, new object[] { decryptionKeyArray, decryptionKeyArray.Length });
//將加密金鑰位元組數群組轉換為16進位表示的字串
//作者Blog: http://dudu.cnblogs.com