Export (0) Print
Expand All
0 out of 2 rated this helpful - Rate this topic

RSAOAEPKeyExchangeFormatter Class

Creates Optimal Asymmetric Encryption Padding (OAEP) key exchange data using RSA.

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

[ComVisibleAttribute(true)] 
public ref class RSAOAEPKeyExchangeFormatter : public AsymmetricKeyExchangeFormatter
/** @attribute ComVisibleAttribute(true) */ 
public class RSAOAEPKeyExchangeFormatter extends AsymmetricKeyExchangeFormatter
ComVisibleAttribute(true) 
public class RSAOAEPKeyExchangeFormatter extends AsymmetricKeyExchangeFormatter

Key exchange allows a sender to create secret information, for example, random data that can be used as a key in a symmetric encryption algorithm, and use encryption to send it to the intended recipient.

Use RSAOAEPKeyExchangeDeformatter to receive the key exchange and extract the secret information from it.

Caution noteCaution

It is highly recommended that you not attempt to create your own key exchange method from the basic functionality provided, because many details of the operation must be performed carefully in order for the key exchange to be successful.

The following code example demonstrates how to use members of the RSAOAEPKeyExchangeFormatter class.

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

ref class RSAEncoder
{
private:
   // Use a member variable to hold the RSA key for encoding and decoding.
   RSA^ rsaKey;

public:
   [STAThread]
   static void Main()
   {
      String^ message = L"A phrase to be encoded.";
      RSAEncoder^ rsaEncoder = gcnew RSAEncoder;
      rsaEncoder->InitializeKey( RSA::Create() );
      Console::WriteLine( L"Encoding the following message:" );
      Console::WriteLine( message );
      array<Byte>^encodedMessage = rsaEncoder->EncodeMessage( message );
      Console::WriteLine( L"Resulting message encoded:" );
      Console::WriteLine( Encoding::ASCII->GetString( encodedMessage ) );
      String^ decodedMessage = rsaEncoder->DecodeMessage( encodedMessage );
      Console::WriteLine( L"Resulting message decoded:" );
      Console::WriteLine( decodedMessage );
      
      // Construct a formatter to demonstrate how to set each property.
      rsaEncoder->ConstructFormatter();
      
      // Construct a deformatter to demonstrate how to set each property.
      rsaEncoder->ConstructDeformatter();
      Console::WriteLine( L"This sample completed successfully, "
         L" press enter to continue." );
      Console::ReadLine();
   }


private:
   // Initialize an rsaKey member variable with the specified RSA key.
   void InitializeKey( RSA^ key )
   {
      rsaKey = key;
   }

   // Use the RSAOAEPKeyExchangeDeformatter class to decode the
   // specified message.
   array<Byte>^ EncodeMessage( String^ message )
   {
      array<Byte>^encodedMessage = nullptr;
      try
      {
         
         // Construct a formatter with the specified RSA key.
         RSAOAEPKeyExchangeFormatter^ keyEncryptor =
            gcnew RSAOAEPKeyExchangeFormatter( rsaKey );

         // Convert the message to bytes to create the encrypted data.
         array<Byte>^byteMessage = Encoding::ASCII->GetBytes( message );
         encodedMessage = keyEncryptor->CreateKeyExchange( byteMessage );
      }
      catch ( Exception^ ex ) 
      {
         Console::WriteLine( L"Unexpected exception caught:{0}", ex );
      }

      return encodedMessage;
   }

   // Use the RSAOAEPKeyExchangeDeformatter class to decode the
   // specified message.
   String^ DecodeMessage( array<Byte>^encodedMessage )
   {
      String^ decodedMessage = nullptr;
      try
      {
         // Construct a deformatter with the specified RSA key.
         RSAOAEPKeyExchangeDeformatter^ keyDecryptor =
            gcnew RSAOAEPKeyExchangeDeformatter( rsaKey );

         // Decrypt the encoded message.
         array<Byte>^decodedBytes = keyDecryptor->DecryptKeyExchange( encodedMessage );

         // Retrieve a string representation of the decoded message.
         decodedMessage = Encoding::ASCII->GetString( decodedBytes );
      }
      catch ( Exception^ ex ) 
      {
         Console::WriteLine( L"Unexpected exception caught:{0}", ex );
      }

      return decodedMessage;
   }


   // Create an RSAOAEPKeyExchangeFormatter object with a new RSA key.
   // Display its properties to the console.
   void ConstructFormatter()
   {
      // Construct an empty Optimal Asymmetric Encryption Padding (OAEP)
      // key exchange.
      RSAOAEPKeyExchangeFormatter^ rsaFormatter = gcnew RSAOAEPKeyExchangeFormatter;

      // Create an RSA and set it into the specified
      // RSAOAEPKeyExchangeFormatter.
      RSA^ key = RSA::Create();
      rsaFormatter->SetKey( key );

      // Create a random number using the RNGCryptoServiceProvider provider.
      RNGCryptoServiceProvider^ ring = gcnew RNGCryptoServiceProvider;
      rsaFormatter->Rng = ring;

      // Export InverseQ and set it into the RSAOAEPKeyExchangeFormatter.
      rsaFormatter->Parameter = key->ExportParameters( true ).InverseQ;

      Console::WriteLine();
      Console::WriteLine( L"**{0}**", rsaFormatter );
      Console::Write( L"The following random number was generated using the " );
      Console::WriteLine( L"class:" );
      Console::WriteLine( rsaFormatter->Rng );
      Console::WriteLine();
      Console::Write( L"The RSA formatter contains the following InverseQ" );
      Console::WriteLine( L" parameter:" );
      Console::WriteLine( Encoding::ASCII->GetString( rsaFormatter->Parameter ) );
      Console::WriteLine();
      
      String^ xmlParameters = rsaFormatter->Parameters;

      Console::WriteLine( L"The RSA formatter has the following parameters:" );
      Console::WriteLine( xmlParameters );
   }

   // Create an RSAOAEPKeyExchangeDeformatter object with a new RSA key.
   // Display its properties to the console.
   void ConstructDeformatter()
   {
      // Construct an empty OAEP key exchange.
      RSAOAEPKeyExchangeDeformatter^ rsaDeformatter =
         gcnew RSAOAEPKeyExchangeDeformatter;

      // Create an RSAKey and set it into the specified
      // RSAOAEPKeyExchangeFormatter.
      RSA^ key = RSA::Create();
      rsaDeformatter->SetKey( key );

      Console::WriteLine();
      Console::WriteLine( L"**{0}**", rsaDeformatter );
      
      String^ xmlParameters = rsaDeformatter->Parameters;

      Console::WriteLine();
      Console::WriteLine( L"The RSA deformatter has the following " );
      Console::WriteLine( L"parameters:{0}", xmlParameters );
   }
};

int main()
{
   RSAEncoder::Main();
}

//
// This sample produces the following output:
//
// Encoding the following message:
// A phrase to be encoded.
// Resulting message encoded: %?}T:v??xu?eD)YucItjwuALH HB,Uj??2xq?.?s45
// ?f?L2?=X?CPzWx???"q5?6&N"AE,Z+T?(]S?_7~,?G{?VV!:S?df?
// Resulting message decoded:
// A phrase to be encoded.
//
// **System.Security.Cryptography.RSAOAEPKeyExchangeFormatter**
// The following random number was generated using the class:
// System.Security.Cryptography.RNGCryptoServiceProvider
//
// The RSA formatter contains the following InverseQ parameter:
// 3MM??]D#?mBq_;:ws^1?ko??,_ ??A[hyWcP$?`v.>@?^!dU%\?H0N'??Ca?Ns
//
// The RSA formatter has the following parameters:
//
//
// **System.Security.Cryptography.RSAOAEPKeyExchangeDeformatter**
//
// The RSA deformatter has the following
// parameters:
// This sample completed successfully,  press enter to continue.

import System.*;
import System.Security.Cryptography.*;
import System.Text.*;

class RSAEncoder
{
    // Use a member variable to hold the RSA key for encoding and decoding.
    private RSA rsaKey;

    /** @attribute STAThread()
     */
    public static void main(String[] args)
    {
        String message = "A phrase to be encoded.";
        RSAEncoder rsaEncoder = new RSAEncoder();
        rsaEncoder.InitializeKey(RSA.Create());
        Console.WriteLine("Encoding the following message:");
        Console.WriteLine(message);
        ubyte encodedMessage[] = rsaEncoder.EncodeMessage(message);
        Console.WriteLine("Resulting message encoded:");
        Console.WriteLine(Encoding.get_ASCII().GetString(encodedMessage));
        String decodedMessage = rsaEncoder.DecodeMessage(encodedMessage);
        Console.WriteLine("Resulting message decoded:");
        Console.WriteLine(decodedMessage);
        // Construct a formatter to demonstrate how to set each property.
        rsaEncoder.ConstructFormatter();
        // Construct a deformatter to demonstrate how to set each property.
        rsaEncoder.ConstructDeformatter();

        Console.WriteLine("This sample completed successfully, " 
            + " press enter to continue.");
        Console.ReadLine();
    } //main

    // Initialize an rsaKey member variable with the specified RSA key.
    private void InitializeKey(RSA key)
    {
        rsaKey = key;
    } //InitializeKey

    // Use the RSAOAEPKeyExchangeDeformatter class to decode the 
    // specified message.
    private ubyte[] EncodeMessage(String message)
    {
        ubyte encodedMessage[] = null;
        try {
            // Construct a formatter with the specified RSA key.
            RSAOAEPKeyExchangeFormatter keyEncryptor 
                = new RSAOAEPKeyExchangeFormatter(rsaKey);

            // Convert the message to bytes to create the encrypted data.
            ubyte byteMessage[] = Encoding.get_ASCII().GetBytes(message);
            encodedMessage = keyEncryptor.CreateKeyExchange(byteMessage);
        } 
        catch (System.Exception ex) {
            Console.WriteLine("Unexpected exception caught:" + ex.ToString());
        }
        return encodedMessage;
    } //EncodeMessage

    // Use the RSAOAEPKeyExchangeDeformatter class to decode the
    // specified message.
    private String DecodeMessage(ubyte encodedMessage[])
    {
        String decodedMessage = null;
        try {
            // Construct a deformatter with the specified RSA key.
            RSAOAEPKeyExchangeDeformatter keyDecryptor 
                = new RSAOAEPKeyExchangeDeformatter(rsaKey);

            // Decrypt the encoded message.
            ubyte decodedBytes[] = keyDecryptor.
                DecryptKeyExchange(encodedMessage);

            // Retrieve a string representation of the decoded message.
            decodedMessage = Encoding.get_ASCII().GetString(decodedBytes);
        }
        catch (System.Exception ex) {
            Console.WriteLine("Unexpected exception caught:" + ex.ToString());
        }
        return decodedMessage;
    } //DecodeMessage

    // Create an RSAOAEPKeyExchangeFormatter object with a new RSA key.
    // Display its properties to the console.
    private void ConstructFormatter()
    {
        // Construct an empty Optimal Asymmetric Encryption Padding (OAEP)
        // key exchange.
        RSAOAEPKeyExchangeFormatter rsaFormatter 
            = new RSAOAEPKeyExchangeFormatter();

        // Create an RSA and set it into the specified 
        // RSAOAEPKeyExchangeFormatter.
        RSA key = RSA.Create();
        rsaFormatter.SetKey(key);

        // Create a random number using the RNGCryptoServiceProvider provider.
        RNGCryptoServiceProvider ring = new RNGCryptoServiceProvider();
        rsaFormatter.set_Rng(ring);

        // Export InverseQ and set it into the RSAOAEPKeyExchangeFormatter.
        rsaFormatter.set_Parameter(key.ExportParameters(true).InverseQ);

        Console.WriteLine();
        Console.WriteLine("**" + rsaFormatter.ToString() + "**");
        Console.Write("The following random number was generated using the ");
        Console.WriteLine("class:");
        Console.WriteLine(rsaFormatter.get_Rng());

        Console.WriteLine();
        Console.Write("The RSA formatter contains the following InverseQ");
        Console.WriteLine(" parameter:");
        Console.WriteLine(Encoding.get_ASCII().GetString(rsaFormatter.
            get_Parameter()));

        Console.WriteLine();
        String xmlParameters = rsaFormatter.get_Parameters();

        Console.WriteLine("The RSA formatter has the following parameters:");
        Console.WriteLine(xmlParameters);
    } //ConstructFormatter

    // Create an RSAOAEPKeyExchangeDeformatter object with a new RSA key.
    // Display its properties to the console.
    private void ConstructDeformatter()
    {
        // Construct an empty OAEP key exchange.
        RSAOAEPKeyExchangeDeformatter rsaDeformatter 
            = new RSAOAEPKeyExchangeDeformatter();
        // Create an RSAKey and set it into the specified 
        // RSAOAEPKeyExchangeFormatter.
        RSA key = RSA.Create();
        rsaDeformatter.SetKey(key);
        Console.WriteLine();
        Console.WriteLine("**" + rsaDeformatter.ToString() + "**");
        String xmlParameters = rsaDeformatter.get_Parameters();
        Console.WriteLine();
        Console.WriteLine("The RSA deformatter has the following ");
        Console.WriteLine("parameters:" + xmlParameters);
    } //ConstructDeformatter
} //RSAEncoder
//
// This sample produces the following output:
//
// Encoding the following message:
// A phrase to be encoded.
// Resulting message encoded: %?}T:v??xu?eD)YucItjwuALH HB,Uj??2xq?.?s45
// ?f?L2?=X?CPzWx???"q5?6&N"AE,Z+T?(]S?_7~,?G{?VV!:S?df?
// Resulting message decoded:
// A phrase to be encoded.
//
// **System.Security.Cryptography.RSAOAEPKeyExchangeFormatter**
// The following random number was generated using the class:
// System.Security.Cryptography.RNGCryptoServiceProvider
//
// The RSA formatter contains the following InverseQ parameter:
// 3MM??]D#?mBq_;:ws^1?ko??,_ ??A[hyWcP$?`v.>@?^!dU%\?H0N'??Ca?Ns
//
// The RSA formatter has the following parameters:
//
//
// **System.Security.Cryptography.RSAOAEPKeyExchangeDeformatter**
//
// The RSA deformatter has the following
// parameters:
// This sample completed successfully,  press enter to continue.

System.Object
   System.Security.Cryptography.AsymmetricKeyExchangeFormatter
    System.Security.Cryptography.RSAOAEPKeyExchangeFormatter
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

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

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

.NET Framework

Supported in: 2.0, 1.1, 1.0
Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

ADD
Show:
© 2014 Microsoft. All rights reserved.