5 out of 9 rated this helpful - Rate this topic

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.

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

Namespace:  System.Security.Cryptography
Assembly:  mscorlib (in mscorlib.dll)
[ComVisibleAttribute(true)]
public sealed class RSACryptoServiceProvider : RSA, 
	ICspAsymmetricAlgorithm

The RSACryptoServiceProvider type exposes the following members.

  Name Description
Public method RSACryptoServiceProvider() Initializes a new instance of the RSACryptoServiceProvider class using the default key.
Public method RSACryptoServiceProvider(CspParameters) Initializes a new instance of the RSACryptoServiceProvider class with the specified parameters.
Public method RSACryptoServiceProvider(Int32) Initializes a new instance of the RSACryptoServiceProvider class with the specified key size.
Public method RSACryptoServiceProvider(Int32, CspParameters) Initializes a new instance of the RSACryptoServiceProvider class with the specified key size and parameters.
Top
  Name Description
Public property CspKeyContainerInfo Gets a CspKeyContainerInfo object that describes additional information about a cryptographic key pair.
Public property KeyExchangeAlgorithm Gets the name of the key exchange algorithm available with this implementation of RSA. (Overrides AsymmetricAlgorithm.KeyExchangeAlgorithm.)
Public property KeySize Gets the size of the current key. (Overrides AsymmetricAlgorithm.KeySize.)
Public property LegalKeySizes Gets the key sizes that are supported by the asymmetric algorithm. (Inherited from AsymmetricAlgorithm.)
Public property PersistKeyInCsp Gets or sets a value indicating whether the key should be persisted in the cryptographic service provider (CSP).
Public property PublicOnly Gets a value that indicates whether the RSACryptoServiceProvider object contains only a public key.
Public property SignatureAlgorithm Gets the name of the signature algorithm available with this implementation of RSA. (Overrides AsymmetricAlgorithm.SignatureAlgorithm.)
Public property Static member UseMachineKeyStore Gets or sets a value indicating whether the key should be persisted in the computer's key store instead of the user profile store.
Top
  Name Description
Public method Clear Releases all resources used by the AsymmetricAlgorithm class. (Inherited from AsymmetricAlgorithm.)
Public method Decrypt Decrypts data with the RSA algorithm.
Public method DecryptValue This method is not supported in the current version. (Overrides RSA.DecryptValue(Byte[]).)
Public method Dispose() Releases all resources used by the current instance of the AsymmetricAlgorithm class. (Inherited from AsymmetricAlgorithm.)
Protected method Dispose(Boolean) Releases the unmanaged resources used by the AsymmetricAlgorithm class and optionally releases the managed resources. (Inherited from AsymmetricAlgorithm.)
Public method Encrypt Encrypts data with the RSA algorithm.
Public method EncryptValue This method is not supported in the current version. (Overrides RSA.EncryptValue(Byte[]).)
Public method Equals(Object) Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
Public method ExportCspBlob Exports a blob containing the key information associated with an RSACryptoServiceProvider object.
Public method ExportParameters Exports the RSAParameters. (Overrides RSA.ExportParameters(Boolean).)
Protected method Finalize Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method FromXmlString Initializes an RSA object from the key information from an XML string. (Inherited from RSA.)
Public method GetHashCode Serves as a hash function for a particular type. (Inherited from Object.)
Public method GetType Gets the Type of the current instance. (Inherited from Object.)
Public method ImportCspBlob Imports a blob that represents RSA key information.
Public method ImportParameters Imports the specified RSAParameters. (Overrides RSA.ImportParameters(RSAParameters).)
Protected method MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.)
Public method SignData(Byte[], Object) Computes the hash value of the specified byte array using the specified hash algorithm, and signs the resulting hash value.
Public method SignData(Stream, Object) Computes the hash value of the specified input stream using the specified hash algorithm, and signs the resulting hash value.
Public method SignData(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.
Public method SignHash Computes the signature for the specified hash value by encrypting it with the private key.
Public method ToString Returns a string that represents the current object. (Inherited from Object.)
Public method ToXmlString Creates and returns an XML string containing the key of the current RSA object. (Inherited from RSA.)
Public method VerifyData 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.
Public method VerifyHash 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.
Top
  Name Description
Protected field KeySizeValue Represents the size, in bits, of the key modulus used by the asymmetric algorithm. (Inherited from AsymmetricAlgorithm.)
Protected field LegalKeySizesValue Specifies the key sizes that are supported by the asymmetric algorithm. (Inherited from AsymmetricAlgorithm.)
Top

This is the default implementation of RSA.

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

Interoperation with the Microsoft Cryptographic API (CAPI)

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.
			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

Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ
Newbie Help
A few helpful hints (based on 3.5 sp1):
This object is a wrapper for an unmanaged API so ensure you use .Clear() in a try... finally block or a Using block (VB.NET) to dispose of your object.
Creating a new instance of this class will ALWAYS create a new private key (keypair). You can then overwrite it if needed by importing your own key using ImportCSPBlob, ImportParameters or FromXMLString.
If you want to persist your private key in a container, then you must initialise your object using CSPParameters and specify the KeyContainerName. This will set the persist flag on the object on initialisation. If you do not specify any parameters when initialising the object then the key will not persist.
It is important to note that the same KeyContainerName can hold 2 keys - one for each cspParams.KeyNumber (Encryption and Signature). ImportCSPBlob may change the cspParams.KeyNumber. If the BLOB was generated by the strong name tool then you must set cspParams.KeyNumber = KeyNumber.Signature (default is Keynumber.Encryption) in order to read the correct key from the container later. 
The default container location is in a user profile. You can set this to machine in the CSPParameters object. The user version does not work well with websites as user profiles are not loaded by default. You need to use the machine version or change some IIS settings (there's a post about this out there somewhere).
Use cspParams.Flags += CspProviderFlags.UseNonExportableKey to protect your key from export, if necessary.
Public keys CANNOT be stored in containers. This is not stated anywhere in the documentation. Use ToXMLString instead or figure something else out (strong name tool has a nice ability to write out a byte array in csv format - good for hardcording the public key into source code, although I imagine this is not recommended practice).
From what I can gather, RSACryptoServiceProvider is not really designed to be used with the strong name tool. The private key (keypair) can be imported as is using ImportCSPBlob (set KeyNumber.Signature as above). The public key needs to have the first 12 bytes (an extra header) stripped before doing this.

'Example: Load up public key from strong name tool csv file (hardcoded in app)
Dim key As Byte() = {0, 36, ...}
or
'Example: Load up public key from strong name tool public key file
Dim key As Byte() = File.ReadAllBytes(Me.txtPublicKeyPath.Text)
or
'Example: Load up public key from strongly named assembly
Dim key As Byte() = Assembly.GetExecutingAssembly.GetName().GetPublicKey()
' Strip first 12 bytes (from all the above as all came from strong name tool)
Dim tmpKey As Byte() = New Byte(key.Length - 13) {}
Array.Copy(key, 12, tmpKey, 0, tmpKey.Length)
'Create a new RSA signing key and import key. 
Dim cspParams As CspParameters = New CspParameters()
'Use MachineKeyStore to get around some permissions problems with the user store with websites (or tweak iis setting to load user profile).
cspParams.Flags = CspProviderFlags.UseMachineKeyStore
'KeyNumber not really needed to look at public key, but is needed to persist private key from strong name tool.
cspParams.KeyNumber = KeyNumber.Signature
'Note: we don't want to persist this key, so we are not specifying KeyContainerName here. 
'If you want to persist a key in a container, specify KeyContainerName.
Using rsaKey As New RSACryptoServiceProvider(cspParams)
    rsaKey.ImportCspBlob(tmpKey)
    ' Verify the signature of the signed XML.
    Dim result As Boolean = VerifyXml(xmlLicence, rsaKey)
    If result = False Then
 ...
    End If
End Using

CSPBLOB Encoding differences
http://www.vsj.co.uk/dotnet/display.asp?id=590
http://www.jensign.com/JavaScience/dotnet/JKeyNet/