如何在ASP.NET中获取随机生成的cookie加密与验证密钥
作者:互联网
2009-06-30
本文是从的补充,通过示例代码说明如何通过反射在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:
相关标签:
相关推荐
专题
+ 收藏
+ 收藏
+ 收藏
+ 收藏
+ 收藏
+ 收藏
最新数据
相关文章
详解.NET Core如何构建一个弹性的HTTP请求机制
.NET Core使用Redis实现创建分布式锁
.NET内存管理释放的两种方式
基于.NET8实现WinFrom应用窗口自动缩放功能
浅析如何在 ASP.NET Core中实现速率限制
.NET Core 委托原理解析(最新推荐)
.NET 9 new features-Microsoft.ML.Tokenizers 库(文本标记化功能)
如何在 .NET 中使用 Tesseract 识别图片文字
ASP.NET Core Web API之Token验证的实现
asp.net core web api项目添加自定义中间件的实现
AI精选
