AsymmetricAlgorithm 클래스

정의

모든 비대칭 알고리즘의 구현에서 상속해야 하는 추상 기본 클래스를 나타냅니다.

public ref class AsymmetricAlgorithm abstract : IDisposable
public abstract class AsymmetricAlgorithm : IDisposable
[System.Runtime.InteropServices.ComVisible(true)]
public abstract class AsymmetricAlgorithm : IDisposable
type AsymmetricAlgorithm = class
    interface IDisposable
[<System.Runtime.InteropServices.ComVisible(true)>]
type AsymmetricAlgorithm = class
    interface IDisposable
Public MustInherit Class AsymmetricAlgorithm
Implements IDisposable
상속
AsymmetricAlgorithm
파생
특성
구현

예제

다음 코드 예제에서는 클래스에서 상속된 사용자 지정 비대칭 알고리즘을 구현하는 AsymmetricAlgorithm 방법을 보여 줍니다. 사용자 지정 클래스를 사용하는 방법을 보여 주는 추가 클래스가 제공됩니다.

#using <System.Xml.dll>
#using <System.Security.dll>

using namespace System;
using namespace System::Xml;
using namespace System::Text;
using namespace System::Security::Cryptography;
using namespace System::Reflection;

[assembly: AssemblyKeyFile("CustomCrypto.snk")];
[assembly: AssemblyVersion("1.0.0.0")];
[assembly: CLSCompliant(true)];
namespace Contoso
{
    // Define a CustomCrypto class that inherits from the AsymmetricAlgorithm
    // class.
    public ref class CustomCrypto :
        public System::Security::Cryptography::AsymmetricAlgorithm
        {
            // Declare local member variables.
        private:
            CspParameters^ cryptoServiceParameters;
            array<KeySizes^>^ customValidKeySizes;

            // Initialize a CustomCrypto with the default key size of 8.
        public:
            CustomCrypto()
            {
                customValidKeySizes = 
                    gcnew array<KeySizes^>{gcnew KeySizes(8, 64, 8)};
                this->KeySize = 8;
            }

            // Initialize a CustomCrypto with the specified key size.
        public:
            CustomCrypto(int keySize)
            {
                customValidKeySizes = 
                    gcnew array<KeySizes^>{gcnew KeySizes(8, 64, 8)};
                this->KeySize = keySize;
            }

            // Accessor function for keySizes member variable.
        public:
            property array<KeySizes^>^ LegalKeySizes
            {
                virtual array<KeySizes^>^ get() override
                {
                    return (array<KeySizes^>^)customValidKeySizes->Clone();
                }
            }

            // Modify the KeySizeValue property inherited from the Asymmetric
            // class. Prior to setting the value, ensure it falls within the
            // range identified in the local keySizes member variable.
        public:
            property int KeySize
            {
                virtual int get() override
                {
                    return KeySizeValue;
                }

                virtual void set(int value) override
                {
                    for (int i = 0; i < customValidKeySizes->Length; i++)
                    {
                        if (customValidKeySizes[i]->SkipSize == 0)
                        {
                            if (customValidKeySizes[i]->MinSize == value)
                            {
                                KeySizeValue = value;
                                return;
                            }
                        }
                        else
                        {
                            for (int j = customValidKeySizes[i]->MinSize;
                                j <= customValidKeySizes[i]->MaxSize;
                                j += customValidKeySizes[i]->SkipSize)
                            {
                                if (j == value)
                                {
                                    KeySizeValue = value;
                                    return;
                                }
                            }
                        }
                    }

                    // If the key does not fall within the range identified
                    // in the keySizes member variable, throw an exception.
                    throw gcnew CryptographicException("Invalid key size.");
                }
            }

            // Initialize the parameters with default values.
        public:
            void InitializeParameters()
            {
                cryptoServiceParameters = gcnew CspParameters();
                cryptoServiceParameters->ProviderName = "Contoso";
                cryptoServiceParameters->KeyContainerName = "SecurityBin1";
                cryptoServiceParameters->KeyNumber = 1;
                cryptoServiceParameters->ProviderType = 2;
            }

            // Parse specified xmlString for values to populate the CspParams
            // Expected XML schema:
            //      <ProviderName></ProviderName>
            //      <KeyContainerName></KeyContainerName>
            //      <KeyNumber></KeyNumber>
            //      <ProviderType></ProviderType>
        public:
            virtual void FromXmlString(String^ xmlString) override 
            {
                if (xmlString != nullptr)
                {
                    XmlDocument^ document = gcnew XmlDocument();
                    document->LoadXml(xmlString);
                    XmlNode^ firstNode = document->FirstChild;
                    XmlNodeList^ nodeList;

                    // Assemble parameters from values in each XML element.
                    cryptoServiceParameters = gcnew CspParameters();

                    // KeyContainerName is optional.
                    nodeList = 
                        document->GetElementsByTagName("KeyContainerName");
                    if (nodeList->Count > 0)
                    {
                        cryptoServiceParameters->KeyContainerName =
                            nodeList->Item(0)->InnerText;
                    }

                    // KeyNumber is optional.
                    nodeList = document->GetElementsByTagName("KeyNumber");
                    if (nodeList->Count > 0)
                    {
                        cryptoServiceParameters->KeyNumber =
                            Int32::Parse(nodeList->Item(0)->InnerText);
                    }

                    // ProviderName is optional.
                    nodeList = document->GetElementsByTagName("ProviderName");
                    if (nodeList->Count > 0)
                    {
                        cryptoServiceParameters->ProviderName =
                            nodeList->Item(0)->InnerText;
                    }

                    // ProviderType is optional.
                    nodeList = document->GetElementsByTagName("ProviderType");
                    if (nodeList->Count > 0)
                    {
                        cryptoServiceParameters->ProviderType =
                            Int32::Parse(nodeList->Item(0)->InnerText);
                    }
                }
                else
                {
                    throw gcnew ArgumentNullException("xmlString");
                }
            }

            // Create an XML string representation of the parameters in the
            // current customCrypto object.
        public:
            virtual String^ ToXmlString(bool includePrivateParameters) override
            {
                String^ keyContainerName = "";
                String^ keyNumber = "";
                String^ providerName = "";
                String^ providerType = "";

                if (cryptoServiceParameters != nullptr)
                {
                    keyContainerName = 
                        cryptoServiceParameters->KeyContainerName;
                    keyNumber = cryptoServiceParameters->KeyNumber.ToString();
                    providerName = cryptoServiceParameters->ProviderName;
                    providerType = 
                        cryptoServiceParameters->ProviderType.ToString();
                }

                StringBuilder^ sb = gcnew StringBuilder();
                sb->Append("<CustomCryptoKeyValue>");

                sb->Append("<KeyContainerName>");
                sb->Append(keyContainerName);
                sb->Append("</KeyContainerName>");

                sb->Append("<KeyNumber>");
                sb->Append(keyNumber);
                sb->Append("</KeyNumber>");

                sb->Append("<ProviderName>");
                sb->Append(providerName);
                sb->Append("</ProviderName>");

                sb->Append("<ProviderType>");
                sb->Append(providerType);
                sb->Append("</ProviderType>");

                sb->Append("</CustomCryptoKeyValue>");
                return(sb->ToString());
            }

            // Return the name for the key exchange algorithm.
        public:
            property String^ KeyExchangeAlgorithm 
            {
                virtual String^ get() override
                {
                    return "RSA-PKCS1-KeyEx";
                }
            }

            // Retrieves the name of the signature alogrithm.
            // This example uses the SHA1 algorithm.
            // Due to collision problems with SHA1, Microsoft recommends SHA256 or better.

        public:
            property String^ SignatureAlgorithm
            {
                virtual String^ get() override
                {
                    return "http://www.w3.org/2000/09/xmldsig#rsa-sha1";
                }
            }

            // Required member for implementing the AsymmetricAlgorithm class.
        protected:
            virtual ~CustomCrypto()
            {
            }

            // Call the Create method using the CustomCrypto assembly name.
            // The create function attempts to create a CustomCrypto 
            // object using the assembly name. This functionality requires 
            // modification of the machine.config file. Add the following 
            // section to the configuration element and modify the values 
            // of the cryptoClass to reflect what isinstalled 
            // in your machines GAC.
            //        <cryptoClass CustomCrypto="Contoso.CustomCrypto,
            //          CustomCrypto,
            //          Culture=neutral,
            //          PublicKeyToken=fdb9f9c4851028bf,
            //          Version=1.0.1448.27640" />
            //      <nameEntry name="Contoso.CustomCrypto" 
            //         class="CustomCrypto" />
            //      <nameEntry name="CustomCrypto" class="CustomCrypto" />

        public:
            static CustomCrypto^ Create() 
            {
                return Create("CustomCrypto");
            }

            // Create a CustomCrypto object by calling CrytoConfig's
            // CreateFromName method and casting the type to CustomCrypto.
            // The create function attempts to create a CustomCrypto object 
            // using the assembly name. This functionality requires 
            // modification of the machine.config file. Add the following 
            // section to the configuration element and modify the values 
            // of the cryptoClass to reflect what is installed 
            // in your machines GAC.
            //       <cryptoClass CustomCrypto="Contoso.CustomCrypto,
            //         CustomCrypto,
            //         Culture=neutral,
            //         PublicKeyToken=fdb9f9c4851028bf,
            //         Version=1.0.1448.27640" />
            //     <nameEntry name="Contoso.CustomCrypto" 
            //        class="CustomCrypto" />
            //     <nameEntry name="CustomCrypto" class="CustomCrypto" />

        public:
            static CustomCrypto^ Create(String^ algorithmName) 
            {
                return (CustomCrypto^) 
                    CryptoConfig::CreateFromName(algorithmName);
            }
        };
}
using System;
using System.Xml;
using System.Text;
using System.Security.Cryptography;
using System.Reflection;

[assembly: AssemblyKeyFile("CustomCrypto.snk")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: CLSCompliant(true)]
namespace Contoso
{
    // Define a CustomCrypto class that inherits from the AsymmetricAlgorithm
    // class.
    public class CustomCrypto : 
        System.Security.Cryptography.AsymmetricAlgorithm
    {
        // Declare local member variables.
        private CspParameters cspParameters;
        private readonly KeySizes[] keySizes = {new KeySizes(8, 64, 8)};

        // Initialize a CustomCrypto with the default key size of 8.
        public CustomCrypto()
        {
            this.KeySize = 8;
        }

        // Initialize a CustomCrypto with the specified key size.
        public CustomCrypto(int keySize)
        {
            this.KeySize = keySize;
        }

        // Accessor function for keySizes member variable.
        public override KeySizes[] LegalKeySizes 
        { 
            get { return (KeySizes[])keySizes.Clone(); }
        }

        // Modify the KeySizeValue property inherited from the Asymmetric
        // class. Prior to setting the value, ensure it falls within the
        // range identified in the local keySizes member variable.
        public override int KeySize 
        {
            get { return KeySizeValue; }
            set
            {
                for (int i=0; i < keySizes.Length; i++)
                {
                    if (keySizes[i].SkipSize == 0) 
                    {
                        if (keySizes[i].MinSize == value)
                        {
                            KeySizeValue = value;
                            return;
                        }
                    }
                    else
                    {
                        for (int j = keySizes[i].MinSize;
                            j <= keySizes[i].MaxSize;
                            j += keySizes[i].SkipSize)
                        {
                            if (j == value)
                            {
                                KeySizeValue = value;
                                return;
                            }
                        }
                    }
                }

                // If the key does not fall within the range identified 
                // in the keySizes member variable, throw an exception.
                throw new CryptographicException("Invalid key size.");
            }
        }

        // Initialize the parameters with default values.
        public void InitializeParameters()
        {
            cspParameters = new CspParameters();
            cspParameters.ProviderName = "Contoso";
            cspParameters.KeyContainerName = "SecurityBin1";
            cspParameters.KeyNumber = 1;
            cspParameters.ProviderType = 2;
        }

        // Parse specified xmlString for values to populate the CspParams
        // Expected XML schema:
        //      <ProviderName></ProviderName>
        //      <KeyContainerName></KeyContainerName>
        //      <KeyNumber></KeyNumber>
        //      <ProviderType></ProviderType>
        public override void FromXmlString(string xmlString)
        {
            if (xmlString != null)
            {
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(xmlString);
                XmlNode firstNode = doc.FirstChild;
                XmlNodeList nodeList;

                // Assemble parameters from values in each XML element.
                cspParameters = new CspParameters();

                // KeyContainerName is optional.
                nodeList = doc.GetElementsByTagName("KeyContainerName");
                string keyName = nodeList.Item(0).InnerText;
                if (keyName != null) 
                {
                    cspParameters.KeyContainerName = keyName;
                }

                // KeyNumber is optional.
                nodeList = doc.GetElementsByTagName("KeyNumber");
                string keyNumber = nodeList.Item(0).InnerText;
                if (keyNumber != null) 
                {
                    cspParameters.KeyNumber = Int32.Parse(keyNumber);
                }

                // ProviderName is optional.
                nodeList = doc.GetElementsByTagName("ProviderName");
                string providerName = nodeList.Item(0).InnerText;
                if (providerName != null) 
                {
                    cspParameters.ProviderName = providerName;
                }

                // ProviderType is optional.
                nodeList = doc.GetElementsByTagName("ProviderType");
                string providerType = nodeList.Item(0).InnerText;
                if (providerType != null) 
                {
                    cspParameters.ProviderType = Int32.Parse(providerType);
                }
            }
            else
            {
                throw new ArgumentNullException("xmlString");
            }
        }

        // Create an XML string representation of the parameters in the
        // current customCrypto object.
        public override string ToXmlString(bool includePrivateParameters)
        {
            string keyContainerName = "";
            string keyNumber = "";
            string providerName = "";
            string providerType = "";

            if (cspParameters != null)
            {
                keyContainerName = cspParameters.KeyContainerName;
                keyNumber = cspParameters.KeyNumber.ToString();
                providerName = cspParameters.ProviderName;
                providerType = cspParameters.ProviderType.ToString();
            }

            StringBuilder sb = new StringBuilder();
            sb.Append("<CustomCryptoKeyValue>");

            sb.Append("<KeyContainerName>");
            sb.Append(keyContainerName);
            sb.Append("</KeyContainerName>");

            sb.Append("<KeyNumber>");
            sb.Append(keyNumber);
            sb.Append("</KeyNumber>");

            sb.Append("<ProviderName>");
            sb.Append(providerName);
            sb.Append("</ProviderName>");

            sb.Append("<ProviderType>");
            sb.Append(providerType);
            sb.Append("</ProviderType>");

            sb.Append("</CustomCryptoKeyValue>");
            return(sb.ToString());
        }

        // Return the name for the key exchange algorithm.
        public override string KeyExchangeAlgorithm
        {
            get {return "RSA-PKCS1-KeyEx";}
        }

        // Retrieves the name of the signature alogrithm.
        // This example uses the SHA1 algorithm.
        // Due to collision problems with SHA1, Microsoft recommends SHA256 or better.
        public override string SignatureAlgorithm 
        {
            get {return "http://www.w3.org/2000/09/xmldsig#rsa-sha1";}
        }

        // Required member for implementing the AsymmetricAlgorithm class.
        protected override void Dispose(bool disposing) {}

        // Call the Create method using the CustomCrypto assembly name.
        // The create function attempts to create a CustomCrypto object using
        // the assembly name. This functionality requires modification of the
        // machine.config file. Add the following section to the configuration
        // element and modify the values of the cryptoClass to reflect what is
        // installed in your machines GAC.
        //        <cryptoClass CustomCrypto="Contoso.CustomCrypto, 
        //          CustomCrypto, 
        //          Culture=neutral, 
        //          PublicKeyToken=fdb9f9c4851028bf, 
        //          Version=1.0.1448.27640" />
        //      <nameEntry name="Contoso.CustomCrypto" class="CustomCrypto" />
        //      <nameEntry name="CustomCrypto" class="CustomCrypto" />
        new static public CustomCrypto Create() 
        {
            return Create("CustomCrypto");
        }

        // Create a CustomCrypto object by calling CrytoConfig's
        // CreateFromName method and casting the type to CustomCrypto.
        // The create function attempts to create a CustomCrypto object using
        // the assembly name. This functionality requires modification of the
        // machine.config file. Add the following section to the configuration
        // element and modify the values of the cryptoClass to reflect what is
        // installed in your machines GAC.
        //       <cryptoClass CustomCrypto="Contoso.CustomCrypto, 
        //         CustomCrypto, 
        //         Culture=neutral, 
        //         PublicKeyToken=fdb9f9c4851028bf, 
        //         Version=1.0.1448.27640" />
        //     <nameEntry name="Contoso.CustomCrypto" class="CustomCrypto" />
        //     <nameEntry name="CustomCrypto" class="CustomCrypto" />
        new static public CustomCrypto Create(String algorithmName) 
        {
            return (CustomCrypto) CryptoConfig.CreateFromName(algorithmName);
        }
    }
    class CustomCryptoImpl
    {
        [STAThread]
        static void Main(string[] args)
        {
            // Construct a CustomCrypto object and initialize its
            // CspParameters.
            CustomCrypto customCrypto = new CustomCrypto();
            customCrypto.InitializeParameters();

            // Display properties of the current customCrypto object.
            Console.WriteLine("*** CustomCrypto created with default " + 
                "parameters:");
            DisplayProperties(customCrypto);

            // Release all the resources used by this instance of 
            // CustomCrytpo.
            customCrypto.Clear();

            customCrypto = new CustomCrypto(64);
            // Create new parameters and set them by using the FromXmlString
            // method.
            string parameterXml = "<CustomCryptoKeyValue>";
            parameterXml += "<ProviderName>Contoso</ProviderName>";
            parameterXml += "<KeyContainerName>SecurityBin2";
            parameterXml += "</KeyContainerName>";
            parameterXml += "<KeyNumber>1</KeyNumber>";
            parameterXml += "<ProviderType>2</ProviderType>";
            parameterXml += "</CustomCryptoKeyValue>";
            customCrypto.FromXmlString(parameterXml);

            // Display the properties of a customCrypto object created with
            // custom parameters.
            Console.WriteLine("\n*** " + 
                "CustomCrypto created with custom parameters:");
            DisplayProperties(customCrypto);

            // Create an object by using the assembly name.
            try
            {
                CustomCrypto myCryptoA = CustomCrypto.Create("CustomCrypto");
                if (myCryptoA != null)
                {
                    Console.Write("\n*** " + 
                        "Successfully created CustomCrytpo from");
                    Console.WriteLine(" the Create method.");

                    DisplayProperties(myCryptoA);
                }
                else
                {
                    Console.Write("Unable to create CustomCrytpo from ");
                    Console.WriteLine(" the Create method.");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            
            Console.WriteLine("This sample completed successfully; " +
                "press Enter to exit.");
            Console.ReadLine();
        }
        // Display the properties of the specified CustomCrypto object to the
        // console.
        public static void DisplayProperties(CustomCrypto customCrypto)
        {
            try
            {
                // Retrieve the class description for the customCrypto object.
                string classDescription = customCrypto.ToString();

                Console.WriteLine(classDescription);
                Console.Write("KeyExchangeAlgorithm: ");
                Console.WriteLine(customCrypto.KeyExchangeAlgorithm);
                Console.Write("SignatureAlgorithm: ");
                Console.WriteLine(customCrypto.SignatureAlgorithm);
                Console.WriteLine("KeySize: " + customCrypto.KeySize);
                Console.WriteLine("Parameters described in Xml format:");
                Console.WriteLine(customCrypto.ToXmlString(true));

                // Display the MinSize, MaxSize, and SkipSize properties of 
                // each KeySize item in the local keySizes member variable.
                KeySizes[] legalKeySizes = customCrypto.LegalKeySizes;
                if (legalKeySizes.Length > 0)
                {
                    for (int i=0; i < legalKeySizes.Length; i++)
                    {
                        Console.Write("Keysize" + i + " min, max, step: ");
                        Console.Write(legalKeySizes[i].MinSize + ", ");
                        Console.Write(legalKeySizes[i].MaxSize + ", ");
                        Console.WriteLine(legalKeySizes[i].SkipSize + ", ");
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Caught unexpected exception: " + 
                    ex.ToString());
            }
        }
    }
}
//
// This sample produces the following output:
//
// *** CustomCrypto created with default parameters:
// Contoso.vbCustomCrypto
// KeyExchangeAlgorithm: RSA-PKCS1-KeyEx
// SignatureAlgorithm: http://www.w3.org/2000/09/xmldsig#rsa-sha1
// KeySize: 8
// Parameters described in Xml format:
// <CustomCryptoKeyValue><KeyContainerName>SecurityBin1</KeyContainerName>
// <KeyNumber>1</KeyNumber><ProviderName>Contoso</ProviderName>
// <ProviderType>2</ProviderType></CustomCryptoKeyValue>
// Keysize0 min, max, step: 8, 64, 8, 
// 
// *** CustomCrypto created with custom parameters:
// Contoso.vbCustomCrypto
// KeyExchangeAlgorithm: RSA-PKCS1-KeyEx
// SignatureAlgorithm: http://www.w3.org/2000/09/xmldsig#rsa-sha1
// KeySize: 64
// Parameters described in Xml format:
// <CustomCryptoKeyValue><KeyContainerName>SecurityBin2</KeyContainerName>
// <KeyNumber>1</KeyNumber><ProviderName>Contoso</ProviderName>
// <ProviderType>2</ProviderType></CustomCryptoKeyValue>
// Keysize0 min, max, step: 8, 64, 8, 
// Unable to create CustomCrytpo from  the Create method
// This sample completed successfully; press Exit to continue.
Imports System.Xml
Imports System.Text
Imports System.Security.Cryptography
Imports System.Reflection

<Assembly: AssemblyKeyFile("CustomCrypto.snk")> 
<Assembly: AssemblyVersion("1.0.0.0")> 
<Assembly: CLSCompliant(True)> 
Namespace Contoso
    ' Define a vbCustomCrypto class that inherits from the AsymmetricAlgorithm
    ' class.
    Class vbCustomCrypto
        Inherits System.Security.Cryptography.AsymmetricAlgorithm

        ' Declare local member variables.
        Private cspParameters As CspParameters
        Private ReadOnly keySizes() As keySizes = {New keySizes(8, 64, 8)}

        ' Initialize a vbCustomCrypto with the default key size of 8.
        Public Sub New()
            Me.KeySize = 8
        End Sub

        ' Initialize a vbCustomCrypto with the specified key size.
        Public Sub New(ByVal keySize As Integer)
            Me.KeySize = keySize
        End Sub

        ' Modify the KeySizeValue property inherited from the Asymmetric
        ' class. Prior to setting the value, ensure it falls within the
        ' range identified in the local keySizes member variable.
        Public Overrides Property KeySize() As Integer
            Get
                Return KeySizeValue
            End Get
            Set(ByVal Value As Integer)
                For i As Int16 = 0 To keySizes.Length - 1 Step i
                    If (keySizes(i).SkipSize.Equals(0)) Then
                        If (keySizes(i).MinSize.Equals(Value)) Then
                            KeySizeValue = Value
                            Return
                        End If
                    Else
                        For j As Integer = keySizes(i).MinSize _
                            To keySizes(i).MaxSize _
                            Step keySizes(i).SkipSize
                            If (j.Equals(Value)) Then
                                KeySizeValue = Value
                                Return
                            End If
                        Next
                    End If
                Next
                ' If the key does not fall within the range identified 
                ' in the keySizes member variable, throw an exception.
                Throw New CryptographicException("Invalid key size.")
            End Set
        End Property
        ' Accessor function for keySizes member variable.
        public Overrides Readonly Property LegalKeySizes as KeySizes()
            Get
                Return keySizes
            End Get
        End Property
        ' Initialize the parameters with default values.
        Public Sub InitializeParameters()
            cspParameters = New CspParameters
            cspParameters.ProviderName = "Contoso"
            cspParameters.KeyContainerName = "SecurityBin1"
            cspParameters.KeyNumber = 1
            cspParameters.ProviderType = 2
        End Sub

        ' Parse specified xmlString for values to populate the CspParams
        ' Expected XML schema:
        '      <ProviderName></ProviderName>
        '      <KeyContainerName></KeyContainerName>
        '      <KeyNumber></KeyNumber>
        '      <ProviderType></ProviderType>
        Public Overrides Sub FromXmlString(ByVal xmlString As String)
            If Not xmlString Is Nothing Then
                Dim doc As New XmlDocument
                doc.LoadXml(xmlString)
                Dim firstNode As XmlNode = doc.FirstChild
                Dim nodeList As XmlNodeList

                ' Assemble parameters from values in each XML element.
                cspParameters = New CspParameters

                ' KeyContainerName is optional.
                nodeList = doc.GetElementsByTagName("KeyContainerName")
                Dim keyName As String = nodeList.Item(0).InnerText
                If Not keyName Is Nothing Then
                    cspParameters.KeyContainerName = keyName
                End If

                ' KeyNumber is optional.
                nodeList = doc.GetElementsByTagName("KeyNumber")
                Dim keyNumber As String = nodeList.Item(0).InnerText
                If Not keyNumber Is Nothing Then
                    cspParameters.KeyNumber = Int32.Parse(keyNumber)
                End If

                ' ProviderName is optional.
                nodeList = doc.GetElementsByTagName("ProviderName")
                Dim providerName As String = nodeList.Item(0).InnerText
                If Not providerName Is Nothing Then
                    cspParameters.ProviderName = providerName
                End If

                ' ProviderType is optional.
                nodeList = doc.GetElementsByTagName("ProviderType")
                Dim providerType As String = nodeList.Item(0).InnerText
                If Not providerType Is Nothing Then
                    cspParameters.ProviderType = Int32.Parse(providerType)
                End If
            Else
                Throw New ArgumentNullException("xmlString")
            End If
        End Sub

        ' Create an XML string representation of the parameters in the current
        ' vbCustomCrypto object.
        Public Overrides Function ToXmlString( _
            ByVal includePrivateParameters As Boolean) As String

            Dim keyContainerName As String = ""
            Dim keyNumber As String = ""
            Dim providerName As String = ""
            Dim providerType As String = ""

            If Not cspParameters Is Nothing Then
                keyContainerName = cspParameters.KeyContainerName
                keyNumber = cspParameters.KeyNumber.ToString()
                providerName = cspParameters.ProviderName
                providerType = cspParameters.ProviderType.ToString()
            End If

            Dim xmlBuilder As New StringBuilder
            xmlBuilder.Append("<CustomCryptoKeyValue>")

            xmlBuilder.Append("<KeyContainerName>")
            xmlBuilder.Append(keyContainerName)
            xmlBuilder.Append("</KeyContainerName>")

            xmlBuilder.Append("<KeyNumber>")
            xmlBuilder.Append(keyNumber)
            xmlBuilder.Append("</KeyNumber>")

            xmlBuilder.Append("<ProviderName>")
            xmlBuilder.Append(providerName)
            xmlBuilder.Append("</ProviderName>")

            xmlBuilder.Append("<ProviderType>")
            xmlBuilder.Append(providerType)
            xmlBuilder.Append("</ProviderType>")

            xmlBuilder.Append("</CustomCryptoKeyValue>")
            Return (xmlBuilder.ToString())
        End Function

        ' Return the name for the key exchange algorithm.
        Public Overrides ReadOnly Property KeyExchangeAlgorithm() As String
            Get
                Return "RSA-PKCS1-KeyEx"
            End Get
        End Property

        ' Retrieves the name of the signature alogrithm.
        ' This example uses the SHA1 algorithm.
        ' Due to collision problems with SHA1, Microsoft recommends SHA256 or better.
        Public Overrides ReadOnly Property SignatureAlgorithm() As String
            Get
                Return "http://www.w3.org/2000/09/xmldsig#rsa-sha1"
            End Get
        End Property

        ' Required member for implementing the AsymmetricAlgorithm class.
        Protected Overrides Sub Dispose(ByVal disposing As Boolean)

        End Sub

        ' The create function attempts to create a vbCustomCrypto object using
        ' the assembly name. This functionality requires modification of the
        ' machine.config file. Add the following section to the configuration
        ' element and modify the values of the cryptoClass to reflect what is
        ' installed in your machines GAC.
        '          <cryptoClass vbCustomCrypto="Contoso.vbCustomCrypto, 
        '            vbCustomCrypto, 
        '            Culture=neutral, 
        '            PublicKeyToken=fdb9f9c4851028bf, 
        '            Version=1.0.1448.27640" />
        '        <nameEntry name="Contoso.vbCustomCrypto" 
        '                   class="vbCustomCrypto" />
        '        <nameEntry name="vbCustomCrypto" class="vbCustomCrypto" />
        Public Shadows Function Create() As vbCustomCrypto
            Return Create("vbCustomCrypto")
        End Function

        ' Create a CustomCrypto object by calling CrytoConfig's
        ' CreateFromName method and casting the type to CustomCrypto.
        ' The create function attempts to create a vbCustomCrypto object using
        ' the assembly name. This functionality requires modification of the
        ' machine.config file. Add the following section to the configuration
        ' element and modify the values of the cryptoClass to reflect what is
        ' installed in your machines GAC.
        '          <cryptoClass vbCustomCrypto="Contoso.vbCustomCrypto, 
        '            vbCustomCrypto, 
        '            Culture=neutral, 
        '            PublicKeyToken=fdb9f9c4851028bf, 
        '            Version=1.0.1448.27640" />
        '        <nameEntry name="Contoso.vbCustomCrypto" 
        '                   class="vbCustomCrypto" />
        '        <nameEntry name="vbCustomCrypto" class="vbCustomCrypto" />
        Public Shadows Function Create( _
            ByVal algorithmName As String) As vbCustomCrypto

            Return CType( _
                CryptoConfig.CreateFromName(algorithmName), _
                vbCustomCrypto)

        End Function
    End Class
    Class Form1
        Inherits System.Windows.Forms.Form

        ' Event handler for Run button.
        Private Sub Button1_Click( _
            ByVal sender As System.Object, _
            ByVal e As System.EventArgs) Handles Button1.Click

            tbxOutput.Cursor = Cursors.WaitCursor
            tbxOutput.Text = ""

            ' Construct a CustomCrypto object and initialize its
            ' CspParameters.
            Dim customCrypto As New Contoso.vbCustomCrypto
            customCrypto.InitializeParameters()

            ' Display properties of the current vbCustomCrypto object.
            WriteLine("*** CustomCrypto created with default parameters:")
            DisplayProperties(customCrypto)

            ' Release all the resources used by this instance of CustomCrytpo.
            customCrypto.Clear()

            customCrypto = New Contoso.vbCustomCrypto(64)
            ' Create new parameters and set them by using the
            ' FromXmlString method.
            Dim parameterXml As String = "<CustomCryptoKeyValue>"
            parameterXml += "<ProviderName>Contoso</ProviderName>"
            parameterXml += "<KeyContainerName>SecurityBin2"
            parameterXml += "</KeyContainerName>"
            parameterXml += "<KeyNumber>1</KeyNumber>"
            parameterXml += "<ProviderType>2</ProviderType>"
            parameterXml += "</CustomCryptoKeyValue>"
            customCrypto.FromXmlString(parameterXml)

            ' Display the properties of a customCrypto object created with
            ' custom parameters.
            WriteLine(vbCrLf + "*** " + _
                "CustomCrypto created with custom parameters:")
            DisplayProperties(customCrypto)

            ' Create an object by using the assembly name.
            Try
                Dim createdCrypto As Contoso.vbCustomCrypto
                createdCrypto = customCrypto.Create("vbCustomCrypto")

                If (Not createdCrypto Is Nothing) Then
                    Write(vbCrLf + "*** Successfully created vbCustomCrytpo ")
                    WriteLine("from the Create method.")

                    DisplayProperties(createdCrypto)
                Else
                    Write("Unable to create CustomCrytpo from ")
                    WriteLine(" the Create method.")
                End If
            Catch ex As Exception
                WriteLine(ex.ToString())
            End Try

            ' Align interface and conclude application.
            WriteLine("This sample completed successfully;" + _
                " press Exit to continue.")

            ' Reset the cursor.
            tbxOutput.Cursor = Cursors.Default
        End Sub
        ' Display the properties of the specified CustomCrypto object to
        ' the output texbox.
        Public Sub DisplayProperties( _
            ByVal customCrypto As Contoso.vbCustomCrypto)

            Try
                ' Retrieve the class description for the customCrypto object.
                Dim classDescription As String = customCrypto.ToString()

                WriteLine(classDescription)
                WriteLine("KeyExchangeAlgorithm: " + _
                    customCrypto.KeyExchangeAlgorithm)
                WriteLine("SignatureAlgorithm: " + _
                    customCrypto.SignatureAlgorithm)
                WriteLine("KeySize: " + customCrypto.KeySize.ToString())
                WriteLine("Parameters described in Xml format:")
                WriteLine(customCrypto.ToXmlString(True))

                ' Display the MinSize, MaxSize, and SkipSize properties of 
                ' each KeySize item in the local keySizes member variable.
                Dim legalKeySizes() As KeySizes = customCrypto.LegalKeySizes
                If (legalKeySizes.Length > 0) Then
                    For i As Integer = 0 To legalKeySizes.Length - 1 Step 1
                        Write("Keysize" + i.ToString() + " min, max, step: ")
                        Write(legalKeySizes(i).MinSize.ToString() + ", ")
                        Write(legalKeySizes(i).MaxSize.ToString() + ", ")
                        Write(legalKeySizes(i).SkipSize.ToString() + ", ")
                        WriteLine("")
                    Next
                End If
            Catch ex As Exception
                WriteLine("Caught unexpected exception: " + ex.ToString())
            End Try
        End Sub
        ' Write the specified message and carriage return to the output
        ' textbox.
        Private Sub WriteLine(ByVal message As String)
            tbxOutput.AppendText(message + vbCrLf)
        End Sub
        ' Write the specified message to the output textbox.
        Private Sub Write(ByVal message As String)
            tbxOutput.AppendText(message)
        End Sub
        ' Event handler for Exit button.
        Private Sub Button2_Click( _
            ByVal sender As System.Object, _
            ByVal e As System.EventArgs) Handles Button2.Click

            Application.Exit()
        End Sub


        Public Sub New()
            MyBase.New()

            'This call is required by the Windows Form Designer.
            InitializeComponent()

            'Add any initialization after the InitializeComponent() call

        End Sub

        'Form overrides dispose to clean up the component list.
        Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
            If disposing Then
                If Not (components Is Nothing) Then
                    components.Dispose()
                End If
            End If
            MyBase.Dispose(disposing)
        End Sub

        'Required by the Windows Form Designer
        Private components As System.ComponentModel.IContainer

        'NOTE: The following procedure is required by the Windows Form 
        'Designer. It can be modified using the Windows Form Designer. 
        'Do not modify it using the code editor.
        Friend WithEvents Panel2 As System.Windows.Forms.Panel
        Friend WithEvents Panel1 As System.Windows.Forms.Panel
        Friend WithEvents Button1 As System.Windows.Forms.Button
        Friend WithEvents Button2 As System.Windows.Forms.Button
        Friend WithEvents tbxOutput As System.Windows.Forms.RichTextBox
        <System.Diagnostics.DebuggerStepThrough()> _
        Private Sub InitializeComponent()
            Me.Panel2 = New System.Windows.Forms.Panel
            Me.Button1 = New System.Windows.Forms.Button
            Me.Button2 = New System.Windows.Forms.Button
            Me.Panel1 = New System.Windows.Forms.Panel
            Me.tbxOutput = New System.Windows.Forms.RichTextBox
            Me.Panel2.SuspendLayout()
            Me.Panel1.SuspendLayout()
            Me.SuspendLayout()
            '
            'Panel2
            '
            Me.Panel2.Controls.Add(Me.Button1)
            Me.Panel2.Controls.Add(Me.Button2)
            Me.Panel2.Dock = System.Windows.Forms.DockStyle.Bottom
            Me.Panel2.DockPadding.All = 20
            Me.Panel2.Location = New System.Drawing.Point(0, 320)
            Me.Panel2.Name = "Panel2"
            Me.Panel2.Size = New System.Drawing.Size(616, 64)
            Me.Panel2.TabIndex = 1
            '
            'Button1
            '
            Me.Button1.Dock = System.Windows.Forms.DockStyle.Right
            Me.Button1.Font = New System.Drawing.Font( _
                "Microsoft Sans Serif", _
                9.0!, _
                System.Drawing.FontStyle.Regular, _
                System.Drawing.GraphicsUnit.Point, _
                CType(0, Byte))
            Me.Button1.Location = New System.Drawing.Point(446, 20)
            Me.Button1.Name = "Button1"
            Me.Button1.Size = New System.Drawing.Size(75, 24)
            Me.Button1.TabIndex = 2
            Me.Button1.Text = "&Run"
            '
            'Button2
            '
            Me.Button2.Dock = System.Windows.Forms.DockStyle.Right
            Me.Button2.Font = New System.Drawing.Font( _
                "Microsoft Sans Serif", _
                9.0!, _
                System.Drawing.FontStyle.Regular, _
                System.Drawing.GraphicsUnit.Point, _
                CType(0, Byte))
            Me.Button2.Location = New System.Drawing.Point(521, 20)
            Me.Button2.Name = "Button2"
            Me.Button2.Size = New System.Drawing.Size(75, 24)
            Me.Button2.TabIndex = 3
            Me.Button2.Text = "E&xit"
            '
            'Panel1
            '
            Me.Panel1.Controls.Add(Me.tbxOutput)
            Me.Panel1.Dock = System.Windows.Forms.DockStyle.Fill
            Me.Panel1.DockPadding.All = 20
            Me.Panel1.Location = New System.Drawing.Point(0, 0)
            Me.Panel1.Name = "Panel1"
            Me.Panel1.Size = New System.Drawing.Size(616, 320)
            Me.Panel1.TabIndex = 2
            '
            'tbxOutput
            '
            Me.tbxOutput.AccessibleDescription = _
                "Displays output from application."
            Me.tbxOutput.AccessibleName = "Output textbox."
            Me.tbxOutput.Dock = System.Windows.Forms.DockStyle.Fill
            Me.tbxOutput.Location = New System.Drawing.Point(20, 20)
            Me.tbxOutput.Name = "tbxOutput"
            Me.tbxOutput.Size = New System.Drawing.Size(576, 280)
            Me.tbxOutput.TabIndex = 1
            Me.tbxOutput.Text = "Click the Run button to run the application."
            '
            'Form1
            '
            Me.AutoScaleBaseSize = New System.Drawing.Size(6, 15)
            Me.ClientSize = New System.Drawing.Size(616, 384)
            Me.Controls.Add(Me.Panel1)
            Me.Controls.Add(Me.Panel2)
            Me.Name = "Form1"
            Me.Text = "AsymmetricAlgorithm"
            Me.Panel2.ResumeLayout(False)
            Me.Panel1.ResumeLayout(False)
            Me.ResumeLayout(False)

        End Sub

    End Class
End Namespace
'
' This sample produces the following output:
'
' *** CustomCrypto created with default parameters:
' Contoso.vbCustomCrypto
' KeyExchangeAlgorithm: RSA-PKCS1-KeyEx
' SignatureAlgorithm: http://www.w3.org/2000/09/xmldsig#rsa-sha1
' KeySize: 8
' Parameters described in Xml format:
' <CustomCryptoKeyValue><KeyContainerName>SecurityBin1</KeyContainerName>
' <KeyNumber>1</KeyNumber><ProviderName>Contoso</ProviderName>
' <ProviderType>2</ProviderType></CustomCryptoKeyValue>
' Keysize0 min, max, step: 8, 64, 8, 
' 
' *** CustomCrypto created with custom parameters:
' Contoso.vbCustomCrypto
' KeyExchangeAlgorithm: RSA-PKCS1-KeyEx
' SignatureAlgorithm: http://www.w3.org/2000/09/xmldsig#rsa-sha1
' KeySize: 64
' Parameters described in Xml format:
' <CustomCryptoKeyValue><KeyContainerName>SecurityBin2</KeyContainerName>
' <KeyNumber>1</KeyNumber><ProviderName>Contoso</ProviderName>
' <ProviderType>2</ProviderType></CustomCryptoKeyValue>
' Keysize0 min, max, step: 8, 64, 8, 
' Unable to create CustomCrytpo from  the Create method
' This sample completed successfully; press Enter to exit.

다음은 사용자 지정 클래스를 사용하는 방법을 보여 주는 추가 클래스입니다.

#using <System.Xml.dll>
#using <System.Security.dll>

using namespace System;
using namespace System::Xml;
using namespace System::Text;
using namespace System::Security::Cryptography;

// Display the properties of the specified CustomCrypto object to the
// console.
static void DisplayProperties(Contoso::CustomCrypto^ customCryptoAlgorithm)
{
    // Retrieve the class description for the customCrypto object.
    String^ classDescription = customCryptoAlgorithm->ToString();

    Console::WriteLine(classDescription);
    Console::WriteLine("KeyExchangeAlgorithm: {0}",
        customCryptoAlgorithm->KeyExchangeAlgorithm);
    Console::WriteLine("SignatureAlgorithm: {0}",
        customCryptoAlgorithm->SignatureAlgorithm);
    Console::WriteLine("KeySize: {0}",
        customCryptoAlgorithm->KeySize);
    Console::WriteLine("Parameters described in Xml format:");
    Console::WriteLine(customCryptoAlgorithm->ToXmlString(true));

    // Display the MinSize, MaxSize, and SkipSize properties of
    // each KeySize item in the local keySizes member variable.
    array<KeySizes^>^ legalKeySizes = customCryptoAlgorithm->LegalKeySizes;
    for (int i = 0; i < legalKeySizes->Length; i++)
    {
        Console::WriteLine(
            "Keysize{0} min, max, step: {1}, {2}, {3}, ", i,
            legalKeySizes[i]->MinSize,
            legalKeySizes[i]->MaxSize,
            legalKeySizes[i]->SkipSize);
    }
}

[STAThread]
int main()
{
    // Construct a CustomCrypto object and initialize its
    // CspParameters.
    Contoso::CustomCrypto^ customCryptoAlgorithm = gcnew Contoso::CustomCrypto();
    customCryptoAlgorithm->InitializeParameters();

    // Display properties of the current customCrypto object.
    Console::WriteLine(
        "*** CustomCrypto created with default parameters:");
    DisplayProperties(customCryptoAlgorithm);

    // Release all the resources used by this instance of
    // CustomCrypto.
    customCryptoAlgorithm->Clear();

    customCryptoAlgorithm = gcnew Contoso::CustomCrypto(64);
    // Create new parameters and set them by using the FromXmlString
    // method.
    String^ parameterXml = "<CustomCryptoKeyValue>" +
        "<ProviderName>Contoso</ProviderName>" +
        "<KeyContainerName>SecurityBin2</KeyContainerName>" +
        "<KeyNumber>1</KeyNumber>" +
        "<ProviderType>2</ProviderType>" +
        "</CustomCryptoKeyValue>";
    customCryptoAlgorithm->FromXmlString(parameterXml);

    // Display the properties of a customCrypto object created with
    // custom parameters.
    Console::WriteLine(
        "{0}*** CustomCrypto created with custom parameters:", Environment::NewLine);
    DisplayProperties(customCryptoAlgorithm);

    // Create an object by using the assembly name.
    Contoso::CustomCrypto^ cryptoFromAssembly =
        Contoso::CustomCrypto::Create("CustomCrypto");
    if (cryptoFromAssembly != nullptr)
    {
        Console::WriteLine("{0}*** Successfully created " +
            "CustomCrypto from the Create method.", Environment::NewLine);
        DisplayProperties(cryptoFromAssembly);
    }
    else
    {
        Console::WriteLine("Unable to create CustomCrypto from " +
            "the Create method.");
    }

    Console::WriteLine(
        "This sample completed successfully; press Enter to exit.");
    Console::ReadLine();
}

//
// This sample produces the following output:
//
// *** CustomCrypto created with default parameters:
// Contoso.vbCustomCrypto
// KeyExchangeAlgorithm: RSA-PKCS1-KeyEx
// SignatureAlgorithm: http://www.w3.org/2000/09/xmldsig#rsa-sha1
// KeySize: 8
// Parameters described in Xml format:
// <CustomCryptoKeyValue><KeyContainerName>SecurityBin1</KeyContainerName>
// <KeyNumber>1</KeyNumber><ProviderName>Contoso</ProviderName>
// <ProviderType>2</ProviderType></CustomCryptoKeyValue>
// Keysize0 min, max, step: 8, 64, 8,
//
// *** CustomCrypto created with custom parameters:
// Contoso.vbCustomCrypto
// KeyExchangeAlgorithm: RSA-PKCS1-KeyEx
// SignatureAlgorithm: http://www.w3.org/2000/09/xmldsig#rsa-sha1
// KeySize: 64
// Parameters described in Xml format:
// <CustomCryptoKeyValue><KeyContainerName>SecurityBin2</KeyContainerName>
// <KeyNumber>1</KeyNumber><ProviderName>Contoso</ProviderName>
// <ProviderType>2</ProviderType></CustomCryptoKeyValue>
// Keysize0 min, max, step: 8, 64, 8,
// Unable to create CustomCrypto from the Create method
// This sample completed successfully; press Enter to exit.
    class CustomCryptoImpl
    {
        [STAThread]
        static void Main(string[] args)
        {
            // Construct a CustomCrypto object and initialize its
            // CspParameters.
            CustomCrypto customCrypto = new CustomCrypto();
            customCrypto.InitializeParameters();

            // Display properties of the current customCrypto object.
            Console.WriteLine("*** CustomCrypto created with default " + 
                "parameters:");
            DisplayProperties(customCrypto);

            // Release all the resources used by this instance of 
            // CustomCrytpo.
            customCrypto.Clear();

            customCrypto = new CustomCrypto(64);
            // Create new parameters and set them by using the FromXmlString
            // method.
            string parameterXml = "<CustomCryptoKeyValue>";
            parameterXml += "<ProviderName>Contoso</ProviderName>";
            parameterXml += "<KeyContainerName>SecurityBin2";
            parameterXml += "</KeyContainerName>";
            parameterXml += "<KeyNumber>1</KeyNumber>";
            parameterXml += "<ProviderType>2</ProviderType>";
            parameterXml += "</CustomCryptoKeyValue>";
            customCrypto.FromXmlString(parameterXml);

            // Display the properties of a customCrypto object created with
            // custom parameters.
            Console.WriteLine("\n*** " + 
                "CustomCrypto created with custom parameters:");
            DisplayProperties(customCrypto);

            // Create an object by using the assembly name.
            try
            {
                CustomCrypto myCryptoA = CustomCrypto.Create("CustomCrypto");
                if (myCryptoA != null)
                {
                    Console.Write("\n*** " + 
                        "Successfully created CustomCrytpo from");
                    Console.WriteLine(" the Create method.");

                    DisplayProperties(myCryptoA);
                }
                else
                {
                    Console.Write("Unable to create CustomCrytpo from ");
                    Console.WriteLine(" the Create method.");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            
            Console.WriteLine("This sample completed successfully; " +
                "press Enter to exit.");
            Console.ReadLine();
        }
        // Display the properties of the specified CustomCrypto object to the
        // console.
        public static void DisplayProperties(CustomCrypto customCrypto)
        {
            try
            {
                // Retrieve the class description for the customCrypto object.
                string classDescription = customCrypto.ToString();

                Console.WriteLine(classDescription);
                Console.Write("KeyExchangeAlgorithm: ");
                Console.WriteLine(customCrypto.KeyExchangeAlgorithm);
                Console.Write("SignatureAlgorithm: ");
                Console.WriteLine(customCrypto.SignatureAlgorithm);
                Console.WriteLine("KeySize: " + customCrypto.KeySize);
                Console.WriteLine("Parameters described in Xml format:");
                Console.WriteLine(customCrypto.ToXmlString(true));

                // Display the MinSize, MaxSize, and SkipSize properties of 
                // each KeySize item in the local keySizes member variable.
                KeySizes[] legalKeySizes = customCrypto.LegalKeySizes;
                if (legalKeySizes.Length > 0)
                {
                    for (int i=0; i < legalKeySizes.Length; i++)
                    {
                        Console.Write("Keysize" + i + " min, max, step: ");
                        Console.Write(legalKeySizes[i].MinSize + ", ");
                        Console.Write(legalKeySizes[i].MaxSize + ", ");
                        Console.WriteLine(legalKeySizes[i].SkipSize + ", ");
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Caught unexpected exception: " + 
                    ex.ToString());
            }
        }
    }
}
//
// This sample produces the following output:
//
// *** CustomCrypto created with default parameters:
// Contoso.vbCustomCrypto
// KeyExchangeAlgorithm: RSA-PKCS1-KeyEx
// SignatureAlgorithm: http://www.w3.org/2000/09/xmldsig#rsa-sha1
// KeySize: 8
// Parameters described in Xml format:
// <CustomCryptoKeyValue><KeyContainerName>SecurityBin1</KeyContainerName>
// <KeyNumber>1</KeyNumber><ProviderName>Contoso</ProviderName>
// <ProviderType>2</ProviderType></CustomCryptoKeyValue>
// Keysize0 min, max, step: 8, 64, 8, 
// 
// *** CustomCrypto created with custom parameters:
// Contoso.vbCustomCrypto
// KeyExchangeAlgorithm: RSA-PKCS1-KeyEx
// SignatureAlgorithm: http://www.w3.org/2000/09/xmldsig#rsa-sha1
// KeySize: 64
// Parameters described in Xml format:
// <CustomCryptoKeyValue><KeyContainerName>SecurityBin2</KeyContainerName>
// <KeyNumber>1</KeyNumber><ProviderName>Contoso</ProviderName>
// <ProviderType>2</ProviderType></CustomCryptoKeyValue>
// Keysize0 min, max, step: 8, 64, 8, 
// Unable to create CustomCrytpo from  the Create method
// This sample completed successfully; press Exit to continue.
    Class Form1
        Inherits System.Windows.Forms.Form

        ' Event handler for Run button.
        Private Sub Button1_Click( _
            ByVal sender As System.Object, _
            ByVal e As System.EventArgs) Handles Button1.Click

            tbxOutput.Cursor = Cursors.WaitCursor
            tbxOutput.Text = ""

            ' Construct a CustomCrypto object and initialize its
            ' CspParameters.
            Dim customCrypto As New Contoso.vbCustomCrypto
            customCrypto.InitializeParameters()

            ' Display properties of the current vbCustomCrypto object.
            WriteLine("*** CustomCrypto created with default parameters:")
            DisplayProperties(customCrypto)

            ' Release all the resources used by this instance of CustomCrytpo.
            customCrypto.Clear()

            customCrypto = New Contoso.vbCustomCrypto(64)
            ' Create new parameters and set them by using the
            ' FromXmlString method.
            Dim parameterXml As String = "<CustomCryptoKeyValue>"
            parameterXml += "<ProviderName>Contoso</ProviderName>"
            parameterXml += "<KeyContainerName>SecurityBin2"
            parameterXml += "</KeyContainerName>"
            parameterXml += "<KeyNumber>1</KeyNumber>"
            parameterXml += "<ProviderType>2</ProviderType>"
            parameterXml += "</CustomCryptoKeyValue>"
            customCrypto.FromXmlString(parameterXml)

            ' Display the properties of a customCrypto object created with
            ' custom parameters.
            WriteLine(vbCrLf + "*** " + _
                "CustomCrypto created with custom parameters:")
            DisplayProperties(customCrypto)

            ' Create an object by using the assembly name.
            Try
                Dim createdCrypto As Contoso.vbCustomCrypto
                createdCrypto = customCrypto.Create("vbCustomCrypto")

                If (Not createdCrypto Is Nothing) Then
                    Write(vbCrLf + "*** Successfully created vbCustomCrytpo ")
                    WriteLine("from the Create method.")

                    DisplayProperties(createdCrypto)
                Else
                    Write("Unable to create CustomCrytpo from ")
                    WriteLine(" the Create method.")
                End If
            Catch ex As Exception
                WriteLine(ex.ToString())
            End Try

            ' Align interface and conclude application.
            WriteLine("This sample completed successfully;" + _
                " press Exit to continue.")

            ' Reset the cursor.
            tbxOutput.Cursor = Cursors.Default
        End Sub
        ' Display the properties of the specified CustomCrypto object to
        ' the output texbox.
        Public Sub DisplayProperties( _
            ByVal customCrypto As Contoso.vbCustomCrypto)

            Try
                ' Retrieve the class description for the customCrypto object.
                Dim classDescription As String = customCrypto.ToString()

                WriteLine(classDescription)
                WriteLine("KeyExchangeAlgorithm: " + _
                    customCrypto.KeyExchangeAlgorithm)
                WriteLine("SignatureAlgorithm: " + _
                    customCrypto.SignatureAlgorithm)
                WriteLine("KeySize: " + customCrypto.KeySize.ToString())
                WriteLine("Parameters described in Xml format:")
                WriteLine(customCrypto.ToXmlString(True))

                ' Display the MinSize, MaxSize, and SkipSize properties of 
                ' each KeySize item in the local keySizes member variable.
                Dim legalKeySizes() As KeySizes = customCrypto.LegalKeySizes
                If (legalKeySizes.Length > 0) Then
                    For i As Integer = 0 To legalKeySizes.Length - 1 Step 1
                        Write("Keysize" + i.ToString() + " min, max, step: ")
                        Write(legalKeySizes(i).MinSize.ToString() + ", ")
                        Write(legalKeySizes(i).MaxSize.ToString() + ", ")
                        Write(legalKeySizes(i).SkipSize.ToString() + ", ")
                        WriteLine("")
                    Next
                End If
            Catch ex As Exception
                WriteLine("Caught unexpected exception: " + ex.ToString())
            End Try
        End Sub
        ' Write the specified message and carriage return to the output
        ' textbox.
        Private Sub WriteLine(ByVal message As String)
            tbxOutput.AppendText(message + vbCrLf)
        End Sub
        ' Write the specified message to the output textbox.
        Private Sub Write(ByVal message As String)
            tbxOutput.AppendText(message)
        End Sub
        ' Event handler for Exit button.
        Private Sub Button2_Click( _
            ByVal sender As System.Object, _
            ByVal e As System.EventArgs) Handles Button2.Click

            Application.Exit()
        End Sub


        Public Sub New()
            MyBase.New()

            'This call is required by the Windows Form Designer.
            InitializeComponent()

            'Add any initialization after the InitializeComponent() call

        End Sub

        'Form overrides dispose to clean up the component list.
        Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
            If disposing Then
                If Not (components Is Nothing) Then
                    components.Dispose()
                End If
            End If
            MyBase.Dispose(disposing)
        End Sub

        'Required by the Windows Form Designer
        Private components As System.ComponentModel.IContainer

        'NOTE: The following procedure is required by the Windows Form 
        'Designer. It can be modified using the Windows Form Designer. 
        'Do not modify it using the code editor.
        Friend WithEvents Panel2 As System.Windows.Forms.Panel
        Friend WithEvents Panel1 As System.Windows.Forms.Panel
        Friend WithEvents Button1 As System.Windows.Forms.Button
        Friend WithEvents Button2 As System.Windows.Forms.Button
        Friend WithEvents tbxOutput As System.Windows.Forms.RichTextBox
        <System.Diagnostics.DebuggerStepThrough()> _
        Private Sub InitializeComponent()
            Me.Panel2 = New System.Windows.Forms.Panel
            Me.Button1 = New System.Windows.Forms.Button
            Me.Button2 = New System.Windows.Forms.Button
            Me.Panel1 = New System.Windows.Forms.Panel
            Me.tbxOutput = New System.Windows.Forms.RichTextBox
            Me.Panel2.SuspendLayout()
            Me.Panel1.SuspendLayout()
            Me.SuspendLayout()
            '
            'Panel2
            '
            Me.Panel2.Controls.Add(Me.Button1)
            Me.Panel2.Controls.Add(Me.Button2)
            Me.Panel2.Dock = System.Windows.Forms.DockStyle.Bottom
            Me.Panel2.DockPadding.All = 20
            Me.Panel2.Location = New System.Drawing.Point(0, 320)
            Me.Panel2.Name = "Panel2"
            Me.Panel2.Size = New System.Drawing.Size(616, 64)
            Me.Panel2.TabIndex = 1
            '
            'Button1
            '
            Me.Button1.Dock = System.Windows.Forms.DockStyle.Right
            Me.Button1.Font = New System.Drawing.Font( _
                "Microsoft Sans Serif", _
                9.0!, _
                System.Drawing.FontStyle.Regular, _
                System.Drawing.GraphicsUnit.Point, _
                CType(0, Byte))
            Me.Button1.Location = New System.Drawing.Point(446, 20)
            Me.Button1.Name = "Button1"
            Me.Button1.Size = New System.Drawing.Size(75, 24)
            Me.Button1.TabIndex = 2
            Me.Button1.Text = "&Run"
            '
            'Button2
            '
            Me.Button2.Dock = System.Windows.Forms.DockStyle.Right
            Me.Button2.Font = New System.Drawing.Font( _
                "Microsoft Sans Serif", _
                9.0!, _
                System.Drawing.FontStyle.Regular, _
                System.Drawing.GraphicsUnit.Point, _
                CType(0, Byte))
            Me.Button2.Location = New System.Drawing.Point(521, 20)
            Me.Button2.Name = "Button2"
            Me.Button2.Size = New System.Drawing.Size(75, 24)
            Me.Button2.TabIndex = 3
            Me.Button2.Text = "E&xit"
            '
            'Panel1
            '
            Me.Panel1.Controls.Add(Me.tbxOutput)
            Me.Panel1.Dock = System.Windows.Forms.DockStyle.Fill
            Me.Panel1.DockPadding.All = 20
            Me.Panel1.Location = New System.Drawing.Point(0, 0)
            Me.Panel1.Name = "Panel1"
            Me.Panel1.Size = New System.Drawing.Size(616, 320)
            Me.Panel1.TabIndex = 2
            '
            'tbxOutput
            '
            Me.tbxOutput.AccessibleDescription = _
                "Displays output from application."
            Me.tbxOutput.AccessibleName = "Output textbox."
            Me.tbxOutput.Dock = System.Windows.Forms.DockStyle.Fill
            Me.tbxOutput.Location = New System.Drawing.Point(20, 20)
            Me.tbxOutput.Name = "tbxOutput"
            Me.tbxOutput.Size = New System.Drawing.Size(576, 280)
            Me.tbxOutput.TabIndex = 1
            Me.tbxOutput.Text = "Click the Run button to run the application."
            '
            'Form1
            '
            Me.AutoScaleBaseSize = New System.Drawing.Size(6, 15)
            Me.ClientSize = New System.Drawing.Size(616, 384)
            Me.Controls.Add(Me.Panel1)
            Me.Controls.Add(Me.Panel2)
            Me.Name = "Form1"
            Me.Text = "AsymmetricAlgorithm"
            Me.Panel2.ResumeLayout(False)
            Me.Panel1.ResumeLayout(False)
            Me.ResumeLayout(False)

        End Sub

    End Class
End Namespace
'
' This sample produces the following output:
'
' *** CustomCrypto created with default parameters:
' Contoso.vbCustomCrypto
' KeyExchangeAlgorithm: RSA-PKCS1-KeyEx
' SignatureAlgorithm: http://www.w3.org/2000/09/xmldsig#rsa-sha1
' KeySize: 8
' Parameters described in Xml format:
' <CustomCryptoKeyValue><KeyContainerName>SecurityBin1</KeyContainerName>
' <KeyNumber>1</KeyNumber><ProviderName>Contoso</ProviderName>
' <ProviderType>2</ProviderType></CustomCryptoKeyValue>
' Keysize0 min, max, step: 8, 64, 8, 
' 
' *** CustomCrypto created with custom parameters:
' Contoso.vbCustomCrypto
' KeyExchangeAlgorithm: RSA-PKCS1-KeyEx
' SignatureAlgorithm: http://www.w3.org/2000/09/xmldsig#rsa-sha1
' KeySize: 64
' Parameters described in Xml format:
' <CustomCryptoKeyValue><KeyContainerName>SecurityBin2</KeyContainerName>
' <KeyNumber>1</KeyNumber><ProviderName>Contoso</ProviderName>
' <ProviderType>2</ProviderType></CustomCryptoKeyValue>
' Keysize0 min, max, step: 8, 64, 8, 
' Unable to create CustomCrytpo from  the Create method
' This sample completed successfully; press Enter to exit.

설명

공개 키 알고리즘이라고도 하는 비대칭 암호화 알고리즘을 사용하려면 발신자와 수신자 모두 프라이빗 키와 공개 키와 같은 관련 키 쌍을 유지 관리해야 합니다. 두 키는 모두 엔터티에 고유합니다. 공개 키는 누구나 사용할 수 있습니다. 이 키는 수신기로 전송되는 데이터를 인코딩하는 데 사용됩니다. 프라이빗 키는 수신자가 비공개로 유지해야 합니다. 이 키는 수신기의 공개 키를 사용하여 인코딩된 메시지를 디코딩하는 데 사용됩니다. 클래스는 RSACryptoServiceProvider 공개 키 알고리즘의 구현입니다. 공개 키 암호화 및 알고리즘에 대한 자세한 내용은 Cryptographic Services의 "공개 키 암호화" 섹션을 참조하세요. 강력한 이름 도구(Sn.exe)를 사용하여 키 쌍을 만드는 방법에 대한 자세한 내용은 방법: Public-Private 키 쌍 만들기를 참조하세요.

공개 키 시스템을 사용하여 디지털 서명을 구성할 수 있습니다. 디지털 서명은 데이터의 무결성을 보호하는 데 사용됩니다. 예를 들어 공개 키 시스템을 사용하여 메시지에 디지털 서명하기 위해 보낸 사람 먼저 메시지에 해시 함수를 적용하여 메시지 다이제스트를 만듭니다. 그런 다음 보낸 사람의 개인 키를 사용하여 메시지 다이제스트를 암호화하여 보낸 사람의 개인 서명을 만듭니다. 메시지와 서명을 받으면 수신자는 보낸 사람의 공개 키를 사용하여 서명의 암호를 해독하여 메시지 다이제스트를 복구하고 발신자가 사용한 것과 동일한 해시 알고리즘을 사용하여 메시지를 해시합니다. 수신기가 계산하는 메시지 다이제스트가 보낸 사람으로부터 받은 메시지 다이제스트와 일치하는 경우 수신자는 전송 중에 메시지가 변경되지 않았다고 가정할 수 있습니다. 보낸 사람의 공개 키는 일반적인 지식이므로 누구나 서명을 확인할 수 있습니다. 이 기술은 메시지의 비밀을 유지하지 않습니다. 메시지가 비밀이 되려면 암호화해야 합니다.

이 .NET Framework 디지털 서명 알고리즘DSACryptoServiceProvider을 구현하는 , , RSACryptoServiceProviderECDsa (기본 클래스) 및 ECDsaCng클래스를 제공합니다.

네임스페이 System.Security.Cryptography 스는 및 DSA 에 대해서만 구체적인 클래스를 RSA 제공합니다.

RSA 알고리즘을 사용하여 XML 데이터를 암호화 및 암호 해독하고 XML 디지털 서명을 만들고 확인하는 방법을 알아보려면 다음 문서를 참조하세요.

생성자

AsymmetricAlgorithm()

AsymmetricAlgorithm 클래스의 새 인스턴스를 초기화합니다.

필드

KeySizeValue

비대칭 알고리즘에서 사용하는 키 모듈러스의 크기(비트 단위)를 나타냅니다.

LegalKeySizesValue

비대칭 알고리즘에서 지원하는 키 크기를 지정합니다.

속성

KeyExchangeAlgorithm

파생 클래스에 재정의하는 경우 키 교환 알고리즘의 이름을 가져옵니다. 그렇지 않으면 NotImplementedException이 throw됩니다.

KeySize

비대칭 알고리즘에서 사용하는 키 모듈러스의 크기(비트 단위)를 가져오거나 설정합니다.

LegalKeySizes

비대칭 알고리즘에서 지원하는 키 크기를 가져옵니다.

SignatureAlgorithm

파생 클래스에서 구현하는 경우 서명 알고리즘 이름을 가져옵니다. 그렇지 않으면 항상 NotImplementedException이 throw됩니다.

메서드

Clear()

AsymmetricAlgorithm 클래스에서 사용하는 모든 리소스를 해제합니다.

Create()
사용되지 않음.
사용되지 않음.

비대칭 알고리즘을 수행하는 데 사용하는 기본 암호화 개체를 만듭니다.

Create(String)
사용되지 않음.

비대칭 알고리즘의 지정된 구현에 대한 인스턴스를 만듭니다.

Dispose()

AsymmetricAlgorithm 클래스의 현재 인스턴스에서 사용하는 모든 리소스를 해제합니다.

Dispose(Boolean)

AsymmetricAlgorithm 클래스에 사용되는 관리되지 않는 리소스를 해제하고, 필요에 따라 관리되는 리소스를 해제합니다.

Equals(Object)

지정된 개체가 현재 개체와 같은지 확인합니다.

(다음에서 상속됨 Object)
ExportEncryptedPkcs8PrivateKey(ReadOnlySpan<Byte>, PbeParameters)

바이트 기반 암호를 사용하여 PKCS#8 EncryptedPrivateKeyInfo 형식의 현재 키를 내보냅니다.

ExportEncryptedPkcs8PrivateKey(ReadOnlySpan<Char>, PbeParameters)

문자 기반 암호를 사용하여 PKCS#8 EncryptedPrivateKeyInfo 형식의 현재 키를 내보냅니다.

ExportEncryptedPkcs8PrivateKeyPem(ReadOnlySpan<Byte>, PbeParameters)

PEM 인코딩된 바이트 기반 암호를 사용하여 PKCS#8 EncryptedPrivateKeyInfo 형식으로 현재 키를 내보냅니다.

ExportEncryptedPkcs8PrivateKeyPem(ReadOnlySpan<Char>, PbeParameters)

PEM 인코딩된 문자 기반 암호를 사용하여 PKCS#8 EncryptedPrivateKeyInfo 형식으로 현재 키를 내보냅니다.

ExportPkcs8PrivateKey()

PKCS#8 PrivateKeyInfo 형식으로 현재 키를 내보냅니다.

ExportPkcs8PrivateKeyPem()

현재 키를 PKCS#8 PrivateKeyInfo 형식, PEM 인코딩 형식으로 내보냅니다.

ExportSubjectPublicKeyInfo()

X.509 SubjectPublicKeyInfo 형식으로 된 현재 키의 퍼블릭 키 부분을 내보냅니다.

ExportSubjectPublicKeyInfoPem()

현재 키의 공개 키 부분을 PEM 인코딩된 X.509 SubjectPublicKeyInfo 형식으로 내보냅니다.

FromXmlString(String)

파생 클래스에서 재정의되는 경우 XML 문자열에서 AsymmetricAlgorithm 개체를 다시 생성합니다. 그렇지 않으면 NotImplementedException이 throw됩니다.

GetHashCode()

기본 해시 함수로 작동합니다.

(다음에서 상속됨 Object)
GetType()

현재 인스턴스의 Type을 가져옵니다.

(다음에서 상속됨 Object)
ImportEncryptedPkcs8PrivateKey(ReadOnlySpan<Byte>, ReadOnlySpan<Byte>, Int32)

파생 클래스에서 재정의되는 경우, 바이트 기반 암호로 해독한 다음 이 개체의 키를 대체하여 PKCS#8 EncryptedPrivateKeyInfo 구조에서 퍼블릭/프라이빗 키 쌍을 가져옵니다.

ImportEncryptedPkcs8PrivateKey(ReadOnlySpan<Char>, ReadOnlySpan<Byte>, Int32)

파생 클래스에서 재정의되는 경우, 문자 기반 암호로 해독한 다음 이 개체의 키를 대체하여 PKCS#8 EncryptedPrivateKeyInfo 구조에서 퍼블릭/프라이빗 키 쌍을 가져옵니다.

ImportFromEncryptedPem(ReadOnlySpan<Char>, ReadOnlySpan<Byte>)

파생 클래스에서 재정의할 때 암호화된 RFC 7468 PEM으로 인코딩된 키를 가져와 이 개체의 키를 바꿉니다.

ImportFromEncryptedPem(ReadOnlySpan<Char>, ReadOnlySpan<Char>)

파생 클래스에서 재정의할 때 암호화된 RFC 7468 PEM으로 인코딩된 키를 가져와 이 개체의 키를 바꿉니다.

ImportFromPem(ReadOnlySpan<Char>)

파생 클래스에서 재정의할 때 RFC 7468 텍스트로 인코딩된 키를 가져와 이 개체의 키를 바꿉니다.

ImportPkcs8PrivateKey(ReadOnlySpan<Byte>, Int32)

파생 클래스에서 재정의되는 경우, 해독한 다음 이 개체의 키를 대체하여 PKCS#8 PrivateKeyInfo 구조에서 퍼블릭/프라이빗 키 쌍을 가져옵니다.

ImportSubjectPublicKeyInfo(ReadOnlySpan<Byte>, Int32)

파생 클래스에서 재정의되는 경우, 해독한 다음 이 개체의 키를 대체하여 X.509 SubjectPublicKeyInfo 구조에서 퍼블릭 키를 가져옵니다.

MemberwiseClone()

현재 Object의 단순 복사본을 만듭니다.

(다음에서 상속됨 Object)
ToString()

현재 개체를 나타내는 문자열을 반환합니다.

(다음에서 상속됨 Object)
ToXmlString(Boolean)

파생 클래스에서 재정의되는 경우 현재 AsymmetricAlgorithm 개체의 XML 문자열 표현을 만들고 반환합니다. 그렇지 않으면 NotImplementedException이 throw됩니다.

TryExportEncryptedPkcs8PrivateKey(ReadOnlySpan<Byte>, PbeParameters, Span<Byte>, Int32)

파생 클래스에서 재정의되는 경우, 바이트 기반 암호를 사용하여 PKCS#8 EncryptedPrivateKeyInfo 형식의 현재 키를 제공된 버퍼로 내보내려고 시도합니다.

TryExportEncryptedPkcs8PrivateKey(ReadOnlySpan<Char>, PbeParameters, Span<Byte>, Int32)

파생 클래스에서 재정의되는 경우, 문자 기반 암호를 사용하여 PKCS#8 EncryptedPrivateKeyInfo 형식의 현재 키를 제공된 버퍼로 내보내려고 시도합니다.

TryExportEncryptedPkcs8PrivateKeyPem(ReadOnlySpan<Byte>, PbeParameters, Span<Char>, Int32)

PEM 인코딩된 바이트 기반 암호를 사용하여 PKCS#8 EncryptedPrivateKeyInfo 형식으로 현재 키를 내보내려고 시도합니다.

TryExportEncryptedPkcs8PrivateKeyPem(ReadOnlySpan<Char>, PbeParameters, Span<Char>, Int32)

PEM 인코딩된 문자 기반 암호를 사용하여 PKCS#8 EncryptedPrivateKeyInfo 형식으로 현재 키를 내보냅니다.

TryExportPkcs8PrivateKey(Span<Byte>, Int32)

파생 클래스에서 재정의되는 경우, PKCS#8 PrivateKeyInfo 형식의 현재 키를 제공된 버퍼로 내보내려고 시도합니다.

TryExportPkcs8PrivateKeyPem(Span<Char>, Int32)

PEM으로 인코딩된 PKCS#8 PrivateKeyInfo 형식의 현재 키를 제공된 버퍼로 내보내려고 시도합니다.

TryExportSubjectPublicKeyInfo(Span<Byte>, Int32)

파생 클래스에서 재정의되는 경우, X.509 SubjectPublicKeyInfo 형식의 현재 키를 제공된 버퍼로 내보내려고 시도합니다.

TryExportSubjectPublicKeyInfoPem(Span<Char>, Int32)

PEM으로 인코딩된 X.509 SubjectPublicKeyInfo 형식의 현재 키를 제공된 버퍼로 내보내려고 시도합니다.

명시적 인터페이스 구현

IDisposable.Dispose()

이 API는 제품 인프라를 지원하며 코드에서 직접 사용되지 않습니다.

이 멤버에 대한 설명은 Dispose()를 참조하세요.

적용 대상

추가 정보