导出 (0) 打印
全部展开

StrongNameIdentityPermission 类

更新:2007 年 11 月

为强名称定义标识权限。无法继承此类。

命名空间:  System.Security.Permissions
程序集:  mscorlib(在 mscorlib.dll 中)

[SerializableAttribute]
[ComVisibleAttribute(true)]
public sealed class StrongNameIdentityPermission : CodeAccessPermission
/** @attribute SerializableAttribute */ 
/** @attribute ComVisibleAttribute(true) */
public final class StrongNameIdentityPermission extends CodeAccessPermission
public final class StrongNameIdentityPermission extends CodeAccessPermission

如果确认调用代码位于特定的具有强名称的代码程序集中,则可以使用 StrongNameIdentityPermission 来实现对版本控制与命名的保护。

强名称标识基于一个名为 Blob 的加密公钥,它还可以与特定程序集的名称和版本结合。密钥定义唯一的命名空间,提供强验证核实该名称是真实的,原因在于该名称的定义必须位于由对应私钥签名的程序集内。

请注意:强名称密钥的有效性不依赖于必须为该密钥颁发的任何证书或信任关系。

说明:

仅当堆栈中的所有程序集都有正确的证据来满足请求时,对 StrongNameIdentityPermission 的完全请求才能成功。而只要直接调用方有正确的证据,使用 StrongNameIdentityPermissionAttribute 的链路请求就能成功。

重要说明:

在 .NET Framework 1.0 和 1.1 版中,标识权限不能具有 Unrestricted 权限状态值。在 .NET Framework 2.0 版中,标识权限可以具有任何权限状态值。 这意味着在 2.0 版中,标识权限与实现 IUnrestrictedPermission 接口的权限具有相同的行为。即,如果程序集被授予完全信任,则不论该程序集采用何种标识,对标识的请求始终都会成功。有关使用 1.1 版 CAS 策略执行 2.0 版应用程序的信息,请参见 <legacyV1CASPolicy> 元素

在 .NET Framework 1.0 和 1.1 版中,即使调用程序集受到完全信任,对标识权限的要求也仍然有效。即,即使调用程序集已获得完全信任,如果该程序集不满足要求的条件,对标识权限的请求也将失败。在 .NET Framework 2.0 版中,如果调用程序集已获得完全信任,则对标识权限的要求将无效。这样做可确保所有权限的一致性,避免了标识权限的处理特殊化现象。

有关强名称的完整说明,请参见 StrongName。有关具有强名称的程序集的更多信息,请参见具有强名称的程序集

StrongNameIdentityPermission 类用于定义访问类型的公共成员的强名称要求。StrongNameIdentityPermissionAttribute 属性可用于定义程序集级别的强名称要求。在 .NET Framework 2.0 版中,还可以使用 InternalsVisibleToAttribute 指定该程序集中的所有非公共类型对另一个程序集而言都是可见的。有关更多信息,请参见友元程序集(C# 编程指南)友元程序集 (Visual Basic)

下面的代码示例阐释了如何使用 StrongNameIdentityPermission 类。此示例为类库的形式,它同时应用 StrongNameIdentityPermissionAttribute 属性和 StrongNameIdentityPermission 以要求用特定的强名称对调用方进行签名。

//The following commented code should be compiled as an console application to execute the
// class library example.
//
//using System;
//using System.Reflection;
//using SignedLib;
//[assembly: AssemblyVersion("1.0.0.0")]
//[assembly: AssemblyKeyFile("snKey.snk")]
//public class StrongNameTest
//{
//  // Demonstrate the declarative and imperative forms of the StrongNameIdentityPermission.
//  public static void Main()
//  {
//      try
//      {
//            Signed signedLib = new Signed();
//            signedLib.GetWindirImperative();
//            signedLib.GetWindirDeclarative();
//            Console.WriteLine( "Called the signed library assembly methods successfully.");
//      }
//      catch (Exception e)
//      {
//            Console.WriteLine( "Exception thrown in called assembly: " + e.Message);
//      }
//   }
//}
//
// Class library example to demonstrate StrongNameIdentityPermission and 
// StrongNameIdentityPermissionAttribute.
using System;
using System.Security.Permissions;
using System.Reflection;
[assembly: AssemblyVersion("1.0.*")]
[assembly :AssemblyKeyFile("snKey.snk")]
namespace SignedLib
{

    public class Signed
    {
        // Read the windir environment variable.
        public void GetWindirImperative()
        {
            try
            {
                // Use Sn.exe to generate the byte array for the public key.
                byte[] b1 = { 0, 36, 0, 0, 4, 128, 0, 0, 148, 0, 0, 0, 6, 2, 0, 0, 0, 36, 
                    0, 0, 82, 83, 65, 49, 0, 4, 0, 0, 1, 0, 1, 0, 237, 146, 145, 51, 34, 
                    97, 123, 196, 90, 174, 41, 170, 173, 221, 41, 193, 175, 39, 7, 151, 
                    178, 0, 230, 152, 218, 8, 206, 206, 170, 84, 111, 145, 26, 208, 158, 
                    240, 246, 219, 228, 34, 31, 163, 11, 130, 16, 199, 111, 224, 4, 112, 
                    46, 84, 0, 104, 229, 38, 39, 63, 53, 189, 0, 157, 32, 38, 34, 109, 0, 
                    171, 114, 244, 34, 59, 9, 232, 150, 192, 247, 175, 104, 143, 171, 42, 
                    219, 66, 66, 194, 191, 218, 121, 59, 92, 42, 37, 158, 13, 108, 210, 
                    189, 9, 203, 204, 32, 48, 91, 212, 101, 193, 19, 227, 107, 25, 133, 
                    70, 2, 220, 83, 206, 71, 102, 245, 104, 252, 87, 109, 190, 56, 34, 180 };

                // Specify the version of the calling assembly.
                Version v1 = new Version("1.0.0.0");
                StrongNamePublicKeyBlob blob = new StrongNamePublicKeyBlob(b1);
                Console.WriteLine(ComparePublicKeys() ? "Calling assembly has same key as this assembly " : "Calling assembly has different key than this assembly");
                // Create different permissions to exercise the set operations.
                StrongNameIdentityPermission snPerm = new StrongNameIdentityPermission(blob, "StrongNamedExe", v1);
                snPerm.Demand();
                // Return the location of the Windows directory that is found in 
                // the windir environment variable.
                Console.WriteLine(Environment.GetEnvironmentVariable("windir"));
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception thrown in called assembly: " + e.Message);
            }
        }
    // Use an attribute to demand that the calling assembly has a specific strong name key.
    // Use Sn.exe to generate the public key string used for the demand.
    [StrongNameIdentityPermissionAttribute(SecurityAction.Demand, PublicKey = 
        "0024000004800000940000000602000000240000525341310004000001000100ed92913322617b" +
        "c45aae29aaaddd29c1af270797b200e698da08ceceaa546f911ad09ef0f6dbe4221fa30b8210c7" +
        "6fe004702e540068e526273f35bd009d2026226d00ab72f4223b09e896c0f7af688fab2adb4242" +
        "c2bfda793b5c2a259e0d6cd2bd09cbcc20305bd465c113e36b19854602dc53ce4766f568fc576d" +
        "be3822b4")]
        public void GetWindirDeclarative()
        {
            try
            {
                // Return the location of the Windows directory that is found in 
                // the windir environment variable.
                Console.WriteLine(Environment.GetEnvironmentVariable("windir"));
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception thrown in called assembly: " + e.Message);
            }
        }
        public static bool ComparePublicKeys()
        {
            try
            {
                Assembly callingAssembly;

                // Create a target object.
                Int32 integer1 = new Int32();
                Type type1;

                // Set the Type instance to the target class type.
                type1 = integer1.GetType();

                // Create an instance of the assembly class to house the Integer type.  
                callingAssembly = Assembly.GetAssembly(integer1.GetType());

                // Display the name of the calling assembly.
                Assembly entryAssembly = Assembly.GetEntryAssembly();
                string mainAssembly = entryAssembly.FullName;

                Console.WriteLine("Calling assembly = " + entryAssembly.FullName);

                // Get the name of the assembly being called (this assembly).
                string thisAssembly = Assembly.GetCallingAssembly().FullName;

                Console.WriteLine("Called assembly=" + thisAssembly);

                int tokenIndex1 = thisAssembly.LastIndexOf("PublicKeyToken");
                int tokenIndex2 = mainAssembly.LastIndexOf("PublicKeyToken");
                string testString1 = thisAssembly.Substring(tokenIndex1, 31);
                string testString2 = mainAssembly.Substring(tokenIndex2, 31);

                return testString1.Equals(testString2);
            }
            catch
            {
                Console.WriteLine("This is an unexpected exception");
                throw;
            }
        }
    }
}



package SignedLib ; 

//  The following commented code should be compiled as an console application 
//  to execute the class library example.

//    import System .* ;
//    import System.Reflection .* ;
//    import SignedLib .* ;
//    /** @assembly AssemblyVersion("1.0.0.0")
//     */
//    /** @assembly AssemblyKeyFile("snKey.snk")
//     */
//    public class StrongNameTest
//    {

//        //Demonstrate the declarative and imperative forms of the 
//        // StrongNameIdentityPermission.
//        public static void main(String[] args)
//        {
//            try {
//                Signed signedLib =  new Signed();
//                signedLib.GetWindirImperative();
//                signedLib.GetWindirDeclarative();
//                Console.WriteLine(("Called the signed library assembly " 
//                    + "methods successfully."));
//            }
//            catch(System.Exception e) {
//                Console.WriteLine(("Exception thrown in called assembly: " 
//                    + e.get_Message()));
//            }
//        } //main
//    } //StrongNameTest

// Class library example to demonstrate StrongNameIdentityPermission and 
// StrongNameIdentityPermissionAttribute.

import System.*;
import System.Security.Permissions.*;
import System.Reflection.*;

/** @assembly AssemblyVersion("1.0.*")
 */
/** @assembly AssemblyKeyFile("snKey.snk")
 */
public class Signed
{
    // Read the windir environment variable.
    public void GetWindirImperative()
    {
        try {
            // Use Sn.exe to generate the byte array for the public key.
            ubyte b1[] =  { 0, 36, 0, 0, 4, 128, 0, 0, 148, 0, 0, 0, 6, 2, 
                0, 0, 0, 36, 0, 0, 82, 83, 65, 49, 0, 4, 0, 0, 1, 0, 1, 0,
                237, 146, 145, 51, 34, 97, 123, 196, 90, 174, 41, 170, 173,
                221, 41, 193, 175, 39, 7, 151, 178, 0, 230, 152, 218, 8, 
                206, 206, 170, 84, 111, 145, 26, 208, 158, 240, 246, 219,
                228, 34, 31, 163, 11, 130, 16, 199, 111, 224, 4, 112, 46,
                84, 0, 104, 229, 38, 39, 63, 53, 189, 0, 157, 32, 38, 34,
                109, 0, 171, 114, 244, 34, 59, 9, 232, 150, 192, 247, 175,
                104, 143, 171, 42, 219, 66, 66, 194, 191, 218, 121, 59, 92,
                42, 37, 158, 13, 108, 210, 189, 9, 203, 204, 32, 48, 91, 
                212, 101, 193, 19, 227, 107, 25, 133, 70, 2, 220, 83, 206,
                71, 102, 245, 104, 252, 87, 109, 190, 56, 34, 180};

            // Specify the version of the calling assembly.
            Version v1 = new Version("1.0.0.0");
            StrongNamePublicKeyBlob blob = new StrongNamePublicKeyBlob(b1);

            Console.WriteLine((ComparePublicKeys()) ? "Calling assembly " 
                + "has same key as this assembly " : "Calling assembly has " 
                + "different key than this assembly");

            // Create different permissions to exercise the set operations.
            StrongNameIdentityPermission snPerm = 
                new StrongNameIdentityPermission(blob, "StrongNamedExe", v1);

            snPerm.Demand();

            // Return the location of the Windows directory that is found in 
            // the windir environment variable.
            Console.WriteLine(Environment.GetEnvironmentVariable("windir"));
        }
        catch (System.Exception e) {
            Console.WriteLine(("Exception thrown in called assembly: " 
                + e.get_Message()));
        }
    } //GetWindirImperative

    // Use an attribute to demand that the calling assembly has a 
    // specific strong name key.
    // Use Sn.exe to generate the public key string used for the demand.
    /** @attribute StrongNameIdentityPermissionAttribute(
        SecurityAction.Demand, PublicKey = 
        "0024000004800000940000000602000000240000525341310004000001000100ed" + 
        "92913322617b" + "c45aae29aaaddd29c1af270797b200e698da08ceceaa546f" + 
        "911ad09ef0f6dbe4221fa30b8210c7" + "6fe004702e540068e526273f35bd009d" + 
        "2026226d00ab72f4223b09e896c0f7af688fab2adb4242" + "c2bfda793b5c2a259" + 
        "e0d6cd2bd09cbcc20305bd465c113e36b19854602dc53ce4766f568fc576d" + 
        "be3822b4")
     */

    public void GetWindirDeclarative()
    {
        try {
            // Return the location of the Windows directory that is found in 
            // the windir environment variable.
            Console.WriteLine(Environment.GetEnvironmentVariable("windir"));
        }
        catch (System.Exception e) {
            Console.WriteLine(("Exception thrown in called assembly: " 
                + e.get_Message()));
        }
    } //GetWindirDeclarative

    public static boolean ComparePublicKeys() throws Exception
    {
        try {
            Assembly callingAssembly;

            // Create a target object.
            Int32 integer1 = new Int32();
            Type type1;

            // Set the Type instance to the target class type.
            type1 = integer1.GetType();

            // Create an instance of the assembly class to house the Integer 
            // type.  
            callingAssembly = Assembly.GetAssembly(integer1.GetType());

            // Display the name of the calling assembly.
            Assembly entryAssembly = Assembly.GetEntryAssembly();
            String mainAssembly = entryAssembly.get_FullName();

            Console.WriteLine(("Calling assembly = " 
                + entryAssembly.get_FullName()));

            // Get the name of the assembly being called (this assembly).
            String thisAssembly = Assembly.GetCallingAssembly().
                get_FullName();

            Console.WriteLine(("Called assembly=" + thisAssembly));

            int tokenIndex1 = thisAssembly.LastIndexOf("PublicKeyToken");
            int tokenIndex2 = mainAssembly.LastIndexOf("PublicKeyToken");
            String testString1 = thisAssembly.Substring(tokenIndex1, 31);
            String testString2 = mainAssembly.Substring(tokenIndex2, 31);

            return testString1.Equals(testString2);
        }
        catch (System.Exception exp) {
            Console.WriteLine("This is an unexpected exception");
            throw new Exception();
        }
    } //ComparePublicKeys
} //Signed


下面的代码示例演示 StrongNameIdentityPermission 方法的行为。

此示例旨在演示当您通过自己的代码执行这些方法时,它们将表现出怎样的行为。通常情况下,权限类的方法由安全性基础结构使用,而不在应用程序中使用。


using System;
using System.Security;
using System.Security.Permissions;


public class StrongNameIdentityDemo
{
    // Public key
    static byte[] b1 = { 0, 36, 0, 0, 4, 128, 0, 0, 148, 0, 0, 0, 6, 2, 0, 0, 0, 36, 0, 0,
82, 83, 65, 49, 0, 4, 0, 0, 1, 0, 1, 0, 237, 146, 145, 51, 34,
97, 123, 196, 90, 174, 41, 170, 173, 221, 41, 193, 175, 39, 7,
151, 178, 0, 230, 152, 218, 8, 206, 206, 170,84, 111, 145, 26,
208, 158, 240, 246, 219, 228, 34, 31, 163, 11, 130, 16, 199, 111,
224, 4, 112, 46, 84, 0, 104, 229, 38, 39, 63, 53, 189, 0, 157,
32, 38, 34, 109, 0, 171, 114, 244, 34, 59, 9, 232, 150, 192, 247,
175, 104, 143, 171, 42, 219, 66, 66, 194, 191, 218, 121, 59, 92,
42, 37, 158, 13, 108, 210, 189, 9, 203, 204, 32, 48, 91, 212, 101,
193, 19, 227, 107, 25, 133, 70, 2, 220, 83, 206, 71, 102, 245, 104,
252, 87, 109, 190, 56, 34, 180};

    StrongNamePublicKeyBlob blob = new StrongNamePublicKeyBlob(b1);
    // Use this version number.
    Version v1 = new Version("1.0.0.0");
    // IsSubsetOf determines whether the current permission is a subset of the specified permission.
    private bool IsSubsetOfDemo()
    {

        bool returnValue = true;

        StrongNameIdentityPermission snIdPerm1, snIdPerm2;

        snIdPerm1 = new StrongNameIdentityPermission(blob, "MyCompany.MyDepartment.*", new Version("1.0.0.0"));
        snIdPerm2 = new StrongNameIdentityPermission(blob, "MyCompany.MyDepartment.MyFile", new Version("1.0.0.0"));

        if (snIdPerm1.IsSubsetOf(snIdPerm2))
        {

            Console.WriteLine("MyCompany.MyDepartment.* is a subset " +
            "of MyCompany.MyDepartment.MyFile \n");
        }
        else
        {
            Console.WriteLine("MyCompany.MyDepartment.*" +
            " is not a subset of MyCompany.MyDepartment.MyFile \n");
        }

        return returnValue;
    }
    // Union creates a new permission that is the union of the current permission and the specified permission.
    private bool UnionDemo()
    {

        bool returnValue = true;

        StrongNameIdentityPermission snIdPerm1, snIdPerm2;
        IPermission snIdPerm3;

        snIdPerm1 = new StrongNameIdentityPermission(blob, "MyCompany.MyDepartment.*", new Version("1.0.0.0"));
        snIdPerm2 = new StrongNameIdentityPermission(blob, "MyCompany.MyDepartment.MyFile", new Version("1.0.0.0"));

        snIdPerm3 = (StrongNameIdentityPermission)snIdPerm1.Union(snIdPerm2);

        try
        {
            Console.WriteLine("The union of MyCompany.MyDepartment.*" +
            "and MyCompany.MyDepartment.MyFile is " +
            ((StrongNameIdentityPermission)snIdPerm3).Name.ToString());
        }
        catch (Exception e)
        {
            Console.WriteLine("An expected exception was thrown: " + e.Message);
        }


        return returnValue;

    }
    // Intersect creates and returns a new permission that is the intersection of the current
    // permission and the permission specified.
    private bool IntersectDemo()
    {

        bool returnValue = true;

        StrongNameIdentityPermission snIdPerm1, snIdPerm2, snIdPerm3;

        snIdPerm1 = new StrongNameIdentityPermission(blob, "MyCompany.MyDepartment.*", new Version("1.0.0.0"));
        snIdPerm2 = new StrongNameIdentityPermission(blob, "MyCompany.MyDepartment.MyFile", new Version("1.0.0.0"));

        try
        {

            snIdPerm3 = (StrongNameIdentityPermission)snIdPerm1.Intersect(snIdPerm2);

            Console.WriteLine("The intersection of MyCompany.MyDepartment.*"
            + "MyCompany.MyDepartment.MyFile is "
            + ((StrongNameIdentityPermission)snIdPerm3).Name.ToString());

        }
        catch (Exception e)
        {
            Console.WriteLine("An exception was thrown: " + e);
            returnValue = false;
        }

        return returnValue;

    }
    //Copy creates and returns an identical copy of the current permission.
    private bool CopyDemo()
    {
        bool returnValue = true;

        StrongNameIdentityPermission snIdPerm1, snIdPerm2;

        snIdPerm1 = new StrongNameIdentityPermission(blob, "MyCompany.MyDepartment.*", new Version("1.0.0.0"));
        snIdPerm2 = new StrongNameIdentityPermission(PermissionState.None);

        snIdPerm2 = (StrongNameIdentityPermission)snIdPerm1.Copy();
        Console.WriteLine("Result of copy = " + snIdPerm2.ToString() + "\n");

        return returnValue;
    }
    // ToXml creates an XML encoding of the permission and its current state;
    //FromXml reconstructs a permission with the specified state from the XML encoding.
    private bool ToFromXmlDemo()
    {

        bool returnValue = true;

        StrongNameIdentityPermission snIdPerm1, snIdPerm2;

        snIdPerm1 = new StrongNameIdentityPermission(blob, "MyCompany.MyDepartment.*", new Version("1.0.0.0"));    
        snIdPerm2 = new StrongNameIdentityPermission(PermissionState.None);
        snIdPerm2.FromXml(snIdPerm1.ToXml());
        Console.WriteLine("Result of ToFromXml = " + snIdPerm2.ToString() + "\n");

        return returnValue;

    }
    // Invoke all demos.
    public bool RunDemo()
    {

        bool ret = true;
        bool retTmp;
        // Call the IsSubsetOf demo.
        if (retTmp = IsSubsetOfDemo()) Console.Out.WriteLine("IsSubsetOf demo completed successfully.");
        else
            Console.Out.WriteLine("IsSubsetOf demo failed.");
        ret = retTmp && ret;

        // Call the Union demo.
        if (retTmp = UnionDemo()) Console.Out.WriteLine("Union demo completed successfully.");
        else
            Console.Out.WriteLine("Union demo failed.");
        ret = retTmp && ret;

        // Call the Intersect demo.
        if (retTmp = IntersectDemo()) Console.Out.WriteLine("Intersect demo completed successfully.");
        else
            Console.Out.WriteLine("Intersect demo failed.");
        ret = retTmp && ret;


        // Call the Copy demo.
        if (retTmp = CopyDemo()) Console.Out.WriteLine("Copy demo completed successfully");
        else
            Console.Out.WriteLine("Copy demo failed.");
        ret = retTmp && ret;

        // Call the ToFromXml demo.
        if (retTmp = ToFromXmlDemo()) Console.Out.WriteLine("ToFromXml demo completed successfully");
        else
            Console.Out.WriteLine("ToFromXml demo failed.");
        ret = retTmp && ret;

        Console.WriteLine("********************************************************\n");


        return (ret);






    }
    // Test harness.
    public static void Main(String[] args)
    {
        try
        {
            StrongNameIdentityDemo democase = new StrongNameIdentityDemo();
            bool ret = democase.RunDemo();
            if (ret)
            {
                Console.Out.WriteLine("StrongNameIdentity demo completed successfully.");
                Console.Out.WriteLine("Press the Enter key to exit.");
                string consoleInput = Console.ReadLine();
                System.Environment.ExitCode = 100;
            }
            else
            {
                Console.Out.WriteLine("StrongNameIdentity demo failed.");
                Console.Out.WriteLine("Press the Enter key to exit.");
                string consoleInput = Console.ReadLine();
                System.Environment.ExitCode = 101;
            }
        }
        catch (Exception e)
        {
            Console.Out.WriteLine("StrongNameIdentity demo failed.");
            Console.WriteLine(e.ToString());
            Console.Out.WriteLine("Press the Enter key to exit.");
            string consoleInput = Console.ReadLine();
            System.Environment.ExitCode = 101;
        }
        // Catch non-CLSCompliant exceptions.
        catch
        {
            Console.WriteLine("An unexpected non-CLSCompliant exception was thrown.");
        }
    }
}



System.Object
  System.Security.CodeAccessPermission
    System.Security.Permissions.StrongNameIdentityPermission

此类型的任何公共 static(在 Visual Basic 中为 Shared) 成员都是线程安全的。但不保证所有实例成员都是线程安全的。

Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98

.NET Framework 和 .NET Compact Framework 并不是对每个平台的所有版本都提供支持。有关支持的版本的列表,请参见.NET Framework 系统要求

.NET Framework

受以下版本支持:3.5、3.0、2.0、1.1、1.0

社区附加资源

添加
显示:
© 2015 Microsoft