RSACryptoServiceProvider Class
TOC
Collapse the table of content
Expand the table of content

RSACryptoServiceProvider Class

 

Performs asymmetric encryption and decryption using the implementation of the RSA algorithm provided by the cryptographic service provider (CSP). This class cannot be inherited.

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

System.Object
  System.Security.Cryptography.AsymmetricAlgorithm
    System.Security.Cryptography.RSA
      System.Security.Cryptography.RSACryptoServiceProvider

[ComVisibleAttribute(true)]
public sealed class RSACryptoServiceProvider : RSA, ICspAsymmetricAlgorithm

NameDescription
System_CAPS_pubmethodRSACryptoServiceProvider()

Initializes a new instance of the RSACryptoServiceProvider class using the default key.

System_CAPS_pubmethodRSACryptoServiceProvider(CspParameters)

Initializes a new instance of the RSACryptoServiceProvider class with the specified parameters.

System_CAPS_pubmethodRSACryptoServiceProvider(Int32)

Initializes a new instance of the RSACryptoServiceProvider class with the specified key size.

System_CAPS_pubmethodRSACryptoServiceProvider(Int32, CspParameters)

Initializes a new instance of the RSACryptoServiceProvider class with the specified key size and parameters.

NameDescription
System_CAPS_pubpropertyCspKeyContainerInfo

Gets a CspKeyContainerInfo object that describes additional information about a cryptographic key pair.

System_CAPS_pubpropertyKeyExchangeAlgorithm

Gets the name of the key exchange algorithm available with this implementation of RSA.(Overrides RSA.KeyExchangeAlgorithm.)

System_CAPS_pubpropertyKeySize

Gets the size of the current key.(Overrides AsymmetricAlgorithm.KeySize.)

System_CAPS_pubpropertyLegalKeySizes

Gets the key sizes that are supported by the asymmetric algorithm.(Inherited from AsymmetricAlgorithm.)

System_CAPS_pubpropertyPersistKeyInCsp

Gets or sets a value indicating whether the key should be persisted in the cryptographic service provider (CSP).

System_CAPS_pubpropertyPublicOnly

Gets a value that indicates whether the RSACryptoServiceProvider object contains only a public key.

System_CAPS_pubpropertySignatureAlgorithm

Gets the name of the signature algorithm available with this implementation of RSA.(Overrides RSA.SignatureAlgorithm.)

System_CAPS_pubpropertySystem_CAPS_staticUseMachineKeyStore

Gets or sets a value indicating whether the key should be persisted in the computer's key store instead of the user profile store.

NameDescription
System_CAPS_pubmethodClear()

Releases all resources used by the AsymmetricAlgorithm class.(Inherited from AsymmetricAlgorithm.)

System_CAPS_pubmethodDecrypt(Byte[], Boolean)

Decrypts data with the RSA algorithm.

System_CAPS_pubmethodDecrypt(Byte[], RSAEncryptionPadding)

Decrypts data that was previously encrypted with the RSA algorithm by using the specified padding. (Overrides RSA.Decrypt(Byte[], RSAEncryptionPadding).)

System_CAPS_pubmethodDecryptValue(Byte[])

This method is not supported in the current version.(Overrides RSA.DecryptValue(Byte[]).)

System_CAPS_pubmethodDispose()

Releases all resources used by the current instance of the AsymmetricAlgorithm class.(Inherited from AsymmetricAlgorithm.)

System_CAPS_pubmethodEncrypt(Byte[], Boolean)

Encrypts data with the RSA algorithm.

System_CAPS_pubmethodEncrypt(Byte[], RSAEncryptionPadding)

Encrypts data with the RSA algorithm using the specified padding. (Overrides RSA.Encrypt(Byte[], RSAEncryptionPadding).)

System_CAPS_pubmethodEncryptValue(Byte[])

This method is not supported in the current version.(Overrides RSA.EncryptValue(Byte[]).)

System_CAPS_pubmethodEquals(Object)

Determines whether the specified object is equal to the current object.(Inherited from Object.)

System_CAPS_pubmethodExportCspBlob(Boolean)

Exports a blob containing the key information associated with an RSACryptoServiceProvider object.

System_CAPS_pubmethodExportParameters(Boolean)
System_CAPS_pubmethodFromXmlString(String)

Initializes an RSA object from the key information from an XML string.(Inherited from RSA.)

System_CAPS_pubmethodGetHashCode()

Serves as the default hash function. (Inherited from Object.)

System_CAPS_pubmethodGetType()

Gets the Type of the current instance.(Inherited from Object.)

System_CAPS_pubmethodImportCspBlob(Byte[])

Imports a blob that represents RSA key information.

System_CAPS_pubmethodImportParameters(RSAParameters)

Imports the specified RSAParameters.(Overrides RSA.ImportParameters(RSAParameters).)

System_CAPS_pubmethodSignData(Byte[], HashAlgorithmName, RSASignaturePadding)

Computes the hash value of the specified byte array using the specified hash algorithm and padding mode, and signs the resulting hash value. (Inherited from RSA.)

System_CAPS_pubmethodSignData(Byte[], Int32, Int32, HashAlgorithmName, RSASignaturePadding)

Computes the hash value of a portion of the specified byte array using the specified hash algorithm and padding mode, and signs the resulting hash value. (Inherited from RSA.)

System_CAPS_pubmethodSignData(Byte[], Int32, Int32, Object)

Computes the hash value of a subset of the specified byte array using the specified hash algorithm, and signs the resulting hash value.

System_CAPS_pubmethodSignData(Byte[], Object)

Computes the hash value of the specified byte array using the specified hash algorithm, and signs the resulting hash value.

System_CAPS_pubmethodSignData(Stream, HashAlgorithmName, RSASignaturePadding)

Computes the hash value of the specified stream using the specified hash algorithm and padding mode, and signs the resulting hash value.(Inherited from RSA.)

System_CAPS_pubmethodSignData(Stream, Object)

Computes the hash value of the specified input stream using the specified hash algorithm, and signs the resulting hash value.

System_CAPS_pubmethodSignHash(Byte[], HashAlgorithmName, RSASignaturePadding)

Computes the signature for the specified hash value by encrypting it with the private key using the specified padding. (Overrides RSA.SignHash(Byte[], HashAlgorithmName, RSASignaturePadding).)

System_CAPS_pubmethodSignHash(Byte[], String)

Computes the signature for the specified hash value by encrypting it with the private key.

System_CAPS_pubmethodToString()

Returns a string that represents the current object.(Inherited from Object.)

System_CAPS_pubmethodToXmlString(Boolean)

Creates and returns an XML string containing the key of the current RSA object.(Inherited from RSA.)

System_CAPS_pubmethodVerifyData(Byte[], Byte[], HashAlgorithmName, RSASignaturePadding)

Verifies that a digital signature is valid by calculating the hash value of the specified data using the specified hash algorithm and padding, and comparing it to the provided signature. (Inherited from RSA.)

System_CAPS_pubmethodVerifyData(Byte[], Int32, Int32, Byte[], HashAlgorithmName, RSASignaturePadding)

Verifies that a digital signature is valid by calculating the hash value of the data in a portion of a byte array using the specified hash algorithm and padding, and comparing it to the provided signature. (Inherited from RSA.)

System_CAPS_pubmethodVerifyData(Byte[], Object, Byte[])

Verifies that a digital signature is valid by determining the hash value in the signature using the provided public key and comparing it to the hash value of the provided data.

System_CAPS_pubmethodVerifyData(Stream, Byte[], HashAlgorithmName, RSASignaturePadding)

Verifies that a digital signature is valid by calculating the hash value of the specified stream using the specified hash algorithm and padding, and comparing it to the provided signature. (Inherited from RSA.)

System_CAPS_pubmethodVerifyHash(Byte[], Byte[], HashAlgorithmName, RSASignaturePadding)

Verifies that a digital signature is valid by determining the hash value in the signature using the specified hashing algorithm and padding, and comparing it to the provided hash value. (Overrides RSA.VerifyHash(Byte[], Byte[], HashAlgorithmName, RSASignaturePadding).)

System_CAPS_pubmethodVerifyHash(Byte[], String, Byte[])

Verifies that a digital signature is valid by determining the hash value in the signature using the provided public key and comparing it to the provided hash value.

This is the default implementation of RSA.

The RSACryptoServiceProvider supports key sizes from 384 bits to 16384 bits in increments of 8 bits if you have the Microsoft Enhanced Cryptographic Provider installed. It supports key sizes from 384 bits to 512 bits in increments of 8 bits if you have the Microsoft Base Cryptographic Provider installed.

Valid key sizes are dependent on the cryptographic service provider (CSP) that is used by the RSACryptoServiceProvider instance. Windows CSPs enable keys sizes of 384 to 16384 bits for Windows versions prior to Windows 8.1, and key sizes of 512 to 16384 bits for Windows 8.1. For more information, see CryptGenKey function in the Windows documentation.

Unlike the RSA implementation in unmanaged CAPI, the RSACryptoServiceProvider class reverses the order of an encrypted array of bytes after encryption and before decryption. By default, data encrypted by the RSACryptoServiceProvider class cannot be decrypted by the CAPI CryptDecrypt function and data encrypted by the CAPI CryptEncrypt method cannot be decrypted by the RSACryptoServiceProvider class.

If you do not compensate for the reverse ordering when interoperating between APIs, the RSACryptoServiceProvider class throws a CryptographicException.

To interoperate with CAPI, you must manually reverse the order of encrypted bytes before the encrypted data interoperates with another API. You can easily reverse the order of a managed byte array by calling the Array.Reverse method.

The following code example uses the RSACryptoServiceProvider class to encrypt a string into an array of bytes and then decrypt the bytes back into a string.

using System;
using System.Security.Cryptography;
using System.Text;

class RSACSPSample
{

    static void Main()
    {
        try
        {
            //Create a UnicodeEncoder to convert between byte array and string.
            UnicodeEncoding ByteConverter = new UnicodeEncoding();

            //Create byte arrays to hold original, encrypted, and decrypted data.
            byte[] dataToEncrypt = ByteConverter.GetBytes("Data to Encrypt");
            byte[] encryptedData;
            byte[] decryptedData;

            //Create a new instance of RSACryptoServiceProvider to generate
            //public and private key data.
            using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
            {

                //Pass the data to ENCRYPT, the public key information 
                //(using RSACryptoServiceProvider.ExportParameters(false),
                //and a boolean flag specifying no OAEP padding.
                encryptedData = RSAEncrypt(dataToEncrypt, RSA.ExportParameters(false), false);

                //Pass the data to DECRYPT, the private key information 
                //(using RSACryptoServiceProvider.ExportParameters(true),
                //and a boolean flag specifying no OAEP padding.
                decryptedData = RSADecrypt(encryptedData, RSA.ExportParameters(true), false);

                //Display the decrypted plaintext to the console. 
                Console.WriteLine("Decrypted plaintext: {0}", ByteConverter.GetString(decryptedData));
            }
        }
        catch (ArgumentNullException)
        {
            //Catch this exception in case the encryption did
            //not succeed.
            Console.WriteLine("Encryption failed.");

        }
    }

    static public byte[] RSAEncrypt(byte[] DataToEncrypt, RSAParameters RSAKeyInfo, bool DoOAEPPadding)
    {
        try
        {
            byte[] encryptedData;
            //Create a new instance of RSACryptoServiceProvider.
            using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
            {

                //Import the RSA Key information. This only needs
                //toinclude the public key information.
                RSA.ImportParameters(RSAKeyInfo);

                //Encrypt the passed byte array and specify OAEP padding.  
                //OAEP padding is only available on Microsoft Windows XP or
                //later.  
                encryptedData = RSA.Encrypt(DataToEncrypt, DoOAEPPadding);
            }
            return encryptedData;
        }
        //Catch and display a CryptographicException  
        //to the console.
        catch (CryptographicException e)
        {
            Console.WriteLine(e.Message);

            return null;
        }

    }

    static public byte[] RSADecrypt(byte[] DataToDecrypt, RSAParameters RSAKeyInfo, bool DoOAEPPadding)
    {
        try
        {
            byte[] decryptedData;
            //Create a new instance of RSACryptoServiceProvider.
            using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
            {
                //Import the RSA Key information. This needs
                //to include the private key information.
                RSA.ImportParameters(RSAKeyInfo);

                //Decrypt the passed byte array and specify OAEP padding.  
                //OAEP padding is only available on Microsoft Windows XP or
                //later.  
                decryptedData = RSA.Decrypt(DataToDecrypt, DoOAEPPadding);
            }
            return decryptedData;
        }
        //Catch and display a CryptographicException  
        //to the console.
        catch (CryptographicException e)
        {
            Console.WriteLine(e.ToString());

            return null;
        }

    }
}

The following code example exports the key information created using the RSACryptoServiceProvider into an RSAParameters object.

try
{
    //Create a new RSACryptoServiceProvider object.
    using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
    {


        //Export the key information to an RSAParameters object.
        //Pass false to export the public key information or pass
        //true to export public and private key information.
        RSAParameters RSAParams = RSA.ExportParameters(false);
    }


}
catch (CryptographicException e)
{
    //Catch this exception in case the encryption did
    //not succeed.
    Console.WriteLine(e.Message);

}

.NET Framework
Available since 1.1
Windows Phone Silverlight
Available since 7.1

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

Return to top
Show:
© 2016 Microsoft