MachineKey獲取介紹
對MachineKey進行配置,以便將其用於對 Forms 身份驗證 Cookie 數據和視圖狀態數據進行加密和解密,並將其用於對進程外會話狀態標識進行驗證。本次講的是如何獲取IIS自動給應用唯一生成的MachineKey和手動生成的MachineKey,下面2種方式都適合,但是有一定區別可選擇使用。
一般情況下是不允許獲取MachineKey(手動生成的KEY不在此范疇,直接復制即可,本次獲取的是IIS自動生成的,並且是歷史項目【代碼生成】,一般有由 FormsAuthentication 或者 System.Web.Security.MachineKey 等等其他相關操作類來進行獲取來進行相關操作的加密,本身微軟封裝MachineKey時就是internal的 訪問級別,不建議獲取。
嘗試了很多方式,APPCMD命令獲取,WMI獲取,等等,最后不得不編碼實現,如有其他方式,請回復賜教,本次獲取只能使用反射進行操作。
獲取MachineKey 的2種方式
方式一:
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的字節數組
方式二:
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集成分布式開發,又不希望停止服務,可以直接獲取到值后進行配置修改。