对MachineKey进行配置,以便将其用于对 Forms 身份验证 Cookie 数据和视图状态数据进行加密和解密,并将其用于对进程外会话状态标识进行验证。本次讲的是如何获取IIS自动给应用惟一辈子成的MachineKey和手动生成的MachineKey,下面2种方式都适合,可是有必定区别可选择使用。html
通常状况下是不容许获取MachineKey(手动生成的KEY不在此范畴,直接复制便可,本次获取的是IIS自动生成的,而且是历史项目【代码生成】,通常有由 FormsAuthentication 或者 System.Web.Security.MachineKey 等等其余相关操做类来进行获取来进行相关操做的加密,自己微软封装MachineKey时就是internal的 访问级别,不建议获取。web
尝试了不少方式,APPCMD命令获取,WMI获取,等等,最后不得不编码实现,若有其余方式,请回复赐教,本次获取只能使用反射进行操做。数组
方式一:分布式
private string ConvertToHex(byte[] binary) { return binary.Aggregate( new StringBuilder(), (acc, c) => acc.AppendFormat("{0:x2}", c), acc => acc.ToString()); } string key = "", iv = ""; public void GetMachineKey() { System.Web.Configuration.MachineKeySection section = (System.Web.Configuration.MachineKeySection) ConfigurationManager.GetSection("system.web/machineKey"); System.Reflection.BindingFlags flags = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.GetProperty; Func<string, byte[]> propertyReader = name => (byte[])section .GetType() .GetProperty(name, flags) .GetValue(section, null); key = ConvertToHex(propertyReader("DecryptionKeyInternal")); iv = ConvertToHex(propertyReader("ValidationKeyInternal"));}
这种方式的缺点是,只能在第一次初始化时获取,第二次进行获取的时候,所有是00000000000000000000000000的字节数组ui
方式二:编码
Configuration config = WebConfigurationManager.OpenWebConfiguration("/"); MachineKeySection machineKeySection = (MachineKeySection)config.GetSection("system.web/machineKey"); PropertyInfo validata = ty.GetProperty("ValidationKeyInternal", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetProperty); PropertyInfo desc = ty.GetProperty("DecryptionKeyInternal", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetProperty); byte[] valiValue = (byte[])validata.GetValue(machineKeySection); byte[] descValue = (byte[])desc.GetValue(machineKeySection); string valiStr = null; foreach (var item in valiValue) { valiStr += string.Format("{0:x2}", item); } string descStr = null; foreach (var item in descValue) { descStr += string.Format("{0:x2}", item); }
该方式惟一不一样的就是,把获取配置的方式修改为了【WebConfigurationManager】来进行操做,这样任何页面和调用均可以获取到。加密
这样,若是有旧项目须要SSO集成分布式开发,又不但愿中止服务,能够直接获取到值后进行配置修改。spa