本文是從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.VEVb.com
新聞熱點
疑難解答