MachineKey 操作 之 获取 MachineKey

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集成分布式开发,又不希望停止服务,可以直接获取到值后进行配置修改。

posted @ 2015-05-21 17:05  JasNature  阅读(4041)  评论(1编辑  收藏  举报
我要赞个
我要评论
我要收藏