本文是从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进制表示的字符串
新闻热点
疑难解答
图片精选