本文是從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進制表示的字符串
新聞熱點
疑難解答
圖片精選