This documentation is archived and is not being maintained.

KeyContainerPermission Class

Controls the ability to access key containers. This class cannot be inherited.

Namespace:  System.Security.Permissions
Assembly:  mscorlib (in mscorlib.dll)

'Declaration
<SerializableAttribute> _
<ComVisibleAttribute(True)> _
Public NotInheritable Class KeyContainerPermission _
	Inherits CodeAccessPermission _
	Implements IUnrestrictedPermission
'Usage
Dim instance As KeyContainerPermission

This permission is used to provide limited access to key containers.

The following code example shows the behavior of the KeyContainerPermission class methods.

NoteNote:

The code example is intended to show the behavior of the methods, not to demonstrate their use. In general, the methods of permission classes are used by the security infrastructure; they are not typically used in applications. Generally, only the constructors are used in application code. The created instance validates or controls resource access by using inherited CodeAccessPermission methods such as Demand.

Imports System
Imports System.Security
Imports System.Security.Permissions
Imports System.Security.Cryptography



Public Class KeyContainerPermissionDemo
    Private Shared cspParams As New CspParameters()
    Private Shared rsa As New RSACryptoServiceProvider()
    Private Shared providerName As String 
    Private Shared providerType As Integer 
    Private Shared myKeyContainerName As String 
    ' Create three KeyContainerPermissionAccessEntry objects, each with a different constructor. 
    Private Shared keyContainerPermAccEntry1 As _
        New KeyContainerPermissionAccessEntry("MyKeyContainer", KeyContainerPermissionFlags.Create)
    Private Shared keyContainerPermAccEntry2 As _
        New KeyContainerPermissionAccessEntry(cspParams, KeyContainerPermissionFlags.Open)
    Private Shared keyContainerPermAccEntry3 As _
        New KeyContainerPermissionAccessEntry("Machine", providerName, providerType, _
            myKeyContainerName, 1, KeyContainerPermissionFlags.Open)


    Public Shared Function Main() As Integer 
        Try 
            ' Create a key container for use in the sample.
            GenKey_SaveInContainer("MyKeyContainer")
            ' Initialize property values for creating a KeyContainerPermissionAccessEntry object.
            myKeyContainerName = rsa.CspKeyContainerInfo.KeyContainerName
            providerName = rsa.CspKeyContainerInfo.ProviderName
            providerType = rsa.CspKeyContainerInfo.ProviderType
            cspParams.KeyContainerName = myKeyContainerName
            cspParams.ProviderName = providerName
            cspParams.ProviderType = providerType

            ' Display the KeyContainerPermissionAccessEntry properties using  
            ' the third KeyContainerPermissionAccessEntry object.
            DisplayAccessEntryMembers()
            ' Add access entry objects to a key container permission. 
            Dim keyContainerPerm1 As New KeyContainerPermission(PermissionState.Unrestricted)
            Console.WriteLine("Is the permission unrestricted? " + _
                keyContainerPerm1.IsUnrestricted().ToString())
            keyContainerPerm1.AccessEntries.Add(keyContainerPermAccEntry1)
            keyContainerPerm1.AccessEntries.Add(keyContainerPermAccEntry2)
            ' Display the permission.
            System.Console.WriteLine(keyContainerPerm1.ToXml().ToString())

            ' Create an array of KeyContainerPermissionAccessEntry objects 
            Dim keyContainerPermAccEntryArray As KeyContainerPermissionAccessEntry() = _
                {keyContainerPermAccEntry1, keyContainerPermAccEntry2}

            ' Create a new KeyContainerPermission using the array. 
            Dim keyContainerPerm2 As _
                New KeyContainerPermission(KeyContainerPermissionFlags.AllFlags, keyContainerPermAccEntryArray)
            DisplayPermissionMembers(keyContainerPerm2, keyContainerPermAccEntryArray)

            ' Demonstrate the effect of a deny for opening a key container.
            DenyOpen()
            ' Demonstrate the deletion of a key container.           
            DeleteContainer()

            Console.WriteLine("Press the Enter key to exit.")
            Console.Read()
            Return 0
            ' Close the current try block that did not expect an exception. 
        Catch e As Exception
            Console.WriteLine("Unexpected exception thrown:  " + e.Message)
            Return 0
        End Try 

    End Function 'Main


    Private Shared Sub DisplayAccessEntryMembers()
        Console.WriteLine(vbLf + "KeycontainerName is " + _
            keyContainerPermAccEntry3.KeyContainerName)
        Console.WriteLine("KeySpec is " + IIf(1 = keyContainerPermAccEntry3.KeySpec, _
            "AT_KEYEXCHANGE ", "AT_SIGNATURE"))
        Console.WriteLine("KeyStore is " + keyContainerPermAccEntry3.KeyStore)
        Console.WriteLine("ProviderName is " + keyContainerPermAccEntry3.ProviderName)
        Console.WriteLine("ProviderType is " + IIf(1 = keyContainerPermAccEntry3.ProviderType, _
            "PROV_RSA_FULL", keyContainerPermAccEntry3.ProviderType.ToString()))
        Console.WriteLine("Hashcode = " + keyContainerPermAccEntry3.GetHashCode().ToString())
        Console.WriteLine("Are the KeyContainerPermissionAccessEntry objects equal? " + _
            keyContainerPermAccEntry3.Equals(keyContainerPermAccEntry2).ToString())

    End Sub 'DisplayAccessEntryMembers

    Private Shared Sub DisplayPermissionMembers(ByVal keyContainerPermParam As _
        KeyContainerPermission, ByVal keyContainerPermAccEntryArrayParam() _
        As KeyContainerPermissionAccessEntry)
        Dim keyContainerPerm2 As KeyContainerPermission = keyContainerPermParam
        Dim keyContainerPermAccEntryArray As KeyContainerPermissionAccessEntry() = _
            keyContainerPermAccEntryArrayParam
        ' Display the KeyContainerPermission properties.
        Console.WriteLine(vbLf + "Flags value is " + keyContainerPerm2.Flags.ToString())
        Dim keyContainerPerm3 As KeyContainerPermission = _
            CType(keyContainerPerm2.Copy(), KeyContainerPermission)
        Console.WriteLine("Is the copy equal to the original? " + _
            keyContainerPerm3.Equals(keyContainerPerm2).ToString())
        ' Perform an XML roundtrip.
        keyContainerPerm3.FromXml(keyContainerPerm2.ToXml())
        Console.WriteLine("Was the XML roundtrip successful? " + _
            keyContainerPerm3.Equals(keyContainerPerm2).ToString())
        Dim keyContainerPerm4 As New KeyContainerPermission(KeyContainerPermissionFlags.Open, _
            keyContainerPermAccEntryArray)
        Dim keyContainerPerm5 As KeyContainerPermission = _
            CType(keyContainerPerm2.Intersect(keyContainerPerm4), KeyContainerPermission)
        Console.WriteLine("Flags value after the intersection is " + _
            keyContainerPerm5.Flags.ToString())
        keyContainerPerm5 = CType(keyContainerPerm2.Union(keyContainerPerm4), _
            KeyContainerPermission)
        Console.WriteLine("Flags value after the union is " + _
            keyContainerPerm5.Flags.ToString())
        Console.WriteLine("Is one permission a subset of the other? " + _
            keyContainerPerm4.IsSubsetOf(keyContainerPerm2).ToString())

    End Sub 'DisplayPermissionMembers

    Private Shared Sub GenKey_SaveInContainer(ByVal containerName As String)
        ' Create the CspParameters object and set the key container  
        ' name used to store the RSA key pair.
        cspParams = New CspParameters()

        cspParams.KeyContainerName = containerName

        ' Create a new instance of RSACryptoServiceProvider that accesses 
        ' the key container identified by the containerName parameter.
        rsa = New RSACryptoServiceProvider(cspParams)

        ' Display the key information to the console.
        Console.WriteLine(vbLf + "Key added to container: " + vbLf + "  {0}", _
            rsa.ToXmlString(True))

    End Sub 'GenKey_SaveInContainer

    Private Shared Sub GetKeyFromContainer(ByVal containerName As String)
        Try
            cspParams = New CspParameters()
            cspParams.KeyContainerName = containerName

            ' Create a new instance of RSACryptoServiceProvider that accesses 
            ' the key container identified by the containerName parameter. 
            ' If the key container does not exist, a new one is created.
            rsa = New RSACryptoServiceProvider(cspParams)

            ' Use the rsa object to access the key.  
            ' Display the key information to the console.
            Console.WriteLine(vbLf + "Key retrieved from container : " + _
                vbLf + " {0}", rsa.ToXmlString(True))
            Console.WriteLine("KeycontainerName is " + rsa.CspKeyContainerInfo.KeyContainerName)
            Console.WriteLine("ProviderName is " + rsa.CspKeyContainerInfo.ProviderName)
            Console.WriteLine("ProviderType is " + IIf(1 = _
                rsa.CspKeyContainerInfo.ProviderType, "PROV_RSA_FULL", _
                rsa.CspKeyContainerInfo.ProviderType.ToString()))
        Catch e As Exception
            Console.WriteLine("Exception thrown:  " + e.Message)
        End Try 

    End Sub 'GetKeyFromContainer

    Private Shared Sub DeleteKeyContainer(ByVal containerName As String)
        ' Create the CspParameters object and set the key container  
        ' name used to store the RSA key pair.
        cspParams = New CspParameters()
        cspParams.KeyContainerName = containerName

        ' Create a new instance of RSACryptoServiceProvider that accesses 
        ' the key container.
        rsa = New RSACryptoServiceProvider(cspParams)

        ' Do not persist the key entry, effectively deleting the key.
        rsa.PersistKeyInCsp = False 

        ' Call Clear to release the key container resources.
        rsa.Clear()
        Console.WriteLine(vbLf + "Key container released.")

    End Sub 'DeleteKeyContainer

    Private Shared Sub DenyOpen()
        Try 
            ' Create a KeyContainerPermission with the right to open the key container. 
            Dim keyContainerPerm As New KeyContainerPermission(KeyContainerPermissionFlags.Open)

            ' Demonstrate the results of a deny for an open action.
            keyContainerPerm.Deny()

            ' The next line causes an exception to be thrown when the infrastructure code attempts  
            ' to open the key container. 
            Dim info As New CspKeyContainerInfo(cspParams)
        Catch e As Exception
            Console.WriteLine("Expected exception thrown: " + e.Message)
        End Try 

        ' Revert the deny.
        CodeAccessPermission.RevertDeny()

    End Sub 'DenyOpen

    Private Shared Sub DeleteContainer()
        Try 
            ' Create a KeyContainerPermission with the right to create a key container. 
            Dim keyContainerPerm As New KeyContainerPermission(KeyContainerPermissionFlags.Create)

            ' Deny the ability to create a key container. 
            ' This deny is used to show the key container has been successfully deleted.
            keyContainerPerm.Deny()

            ' Retrieve the key from the container. 
            ' This code executes successfully because the key container already exists. 
            ' The deny for permission to create a key container does not affect this method call.
            GetKeyFromContainer("MyKeyContainer")

            ' Delete the key and the container.
            DeleteKeyContainer("MyKeyContainer")

            ' Attempt to obtain the key from the deleted key container. 
            ' This time the method call results in an exception because of 
            ' an attempt to create a new key container.
            Console.WriteLine(vbLf + _
                "Attempt to create a new key container with create permission denied.")
            GetKeyFromContainer("MyKeyContainer")
        Catch e As CryptographicException
            Console.WriteLine("Expected exception thrown: " + e.Message)
        End Try 

    End Sub 'DeleteContainer
End Class 'KeyContainerPermissionDemo

System.Object
  System.Security.CodeAccessPermission
    System.Security.Permissions.KeyContainerPermission

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

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

The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

.NET Framework

Supported in: 3.5, 3.0, 2.0
Show: