RSAKeyValue Class

 

Represents the <RSAKeyValue> element of an XML signature.

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

System::Object
  System.Security.Cryptography.Xml::KeyInfoClause
    System.Security.Cryptography.Xml::RSAKeyValue

[HostProtectionAttribute(SecurityAction::LinkDemand, MayLeakOnAbort = true)]
public ref class RSAKeyValue : KeyInfoClause

NameDescription
System_CAPS_pubmethodRSAKeyValue()

Initializes a new instance of the RSAKeyValue class with a new randomly generated RSA public key.

System_CAPS_pubmethodRSAKeyValue(RSA^)

Initializes a new instance of the RSAKeyValue class with the specified RSA public key.

NameDescription
System_CAPS_pubpropertyKey

Gets or sets the instance of RSA that holds the public key.

NameDescription
System_CAPS_pubmethodEquals(Object^)

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

System_CAPS_protmethodFinalize()

Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection.(Inherited from Object.)

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_pubmethodGetXml()

Returns the XML representation of the RSA key clause.(Overrides KeyInfoClause::GetXml().)

System_CAPS_pubmethodLoadXml(XmlElement^)

Loads an RSA key clause from an XML element.(Overrides KeyInfoClause::LoadXml(XmlElement^).)

System_CAPS_protmethodMemberwiseClone()

Creates a shallow copy of the current Object.(Inherited from Object.)

System_CAPS_pubmethodToString()

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

The RSAKeyValue class represents the <RSAKeyValue> element of an XML signature defined by the XML digital signature specification. The <RSAKeyValue> element is the subelement of the <KeyInfo> element (represented by the KeyInfo class) that describes an RSA public key. The <RSAKeyValue> element contains the public key that corresponds to the private key used to digitally sign a document. A recipient of the document uses the public key to validate the XML signature.

Use the RSAKeyValue class whenever you want to add a public key to your XML digital signature.

If a key is not explicitly supplied to the constructor, a new RSA key pair is randomly generated.

For more information about the <RSAKeyValue> element, see the W3C specification at www.w3.org/TR/xmldsig-core/.

The following code example demonstrates how to generate and verify an enveloped XML signature using the RSAKeyValue object.

//
// This example signs an XML file using an
// envelope signature. It then verifies the 
// signed XML.
//
#using <System.Security.dll>
#using <System.Xml.dll>

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

// Sign an XML file and save the signature in a new file.
void SignXmlFile( String^ FileName, String^ SignedFileName, RSA^ Key )
{

   // Create a new XML document.
   XmlDocument^ doc = gcnew XmlDocument;

   // Format the document to ignore white spaces.
   doc->PreserveWhitespace = false;

   // Load the passed XML file using its name.
   doc->Load( gcnew XmlTextReader( FileName ) );

   // Create a SignedXml object.
   SignedXml^ signedXml = gcnew SignedXml( doc );

   // Add the key to the SignedXml document. 
   signedXml->SigningKey = Key;

   // Create a reference to be signed.
   Reference^ reference = gcnew Reference;
   reference->Uri = "";

   // Add an enveloped transformation to the reference.
   XmlDsigEnvelopedSignatureTransform^ env = gcnew XmlDsigEnvelopedSignatureTransform;
   reference->AddTransform( env );

   // Add the reference to the SignedXml object.
   signedXml->AddReference( reference );

   // Add an RSAKeyValue KeyInfo (optional; helps recipient find key to validate).
   KeyInfo^ keyInfo = gcnew KeyInfo;
   keyInfo->AddClause( gcnew RSAKeyValue( safe_cast<RSA^>(Key) ) );
   signedXml->KeyInfo = keyInfo;

   // Compute the signature.
   signedXml->ComputeSignature();

   // Get the XML representation of the signature and save
   // it to an XmlElement object.
   XmlElement^ xmlDigitalSignature = signedXml->GetXml();

   // Append the element to the XML document.
   doc->DocumentElement->AppendChild( doc->ImportNode( xmlDigitalSignature, true ) );
   if ( (doc->FirstChild)->GetType() == XmlDeclaration::typeid )
   {
      doc->RemoveChild( doc->FirstChild );
   }


   // Save the signed XML document to a file specified
   // using the passed string.
   XmlTextWriter^ xmltw = gcnew XmlTextWriter( SignedFileName,gcnew UTF8Encoding( false ) );
   doc->WriteTo( xmltw );
   xmltw->Close();
}


// Verify the signature of an XML file and return the result.
Boolean VerifyXmlFile( String^ Name )
{

   // Create a new XML document.
   XmlDocument^ xmlDocument = gcnew XmlDocument;

   // Format using white spaces.
   xmlDocument->PreserveWhitespace = true;

   // Load the passed XML file into the document. 
   xmlDocument->Load( Name );

   // Create a new SignedXml object and pass it
   // the XML document class.
   SignedXml^ signedXml = gcnew SignedXml( xmlDocument );

   // Find the "Signature" node and create a new
   // XmlNodeList object.
   XmlNodeList^ nodeList = xmlDocument->GetElementsByTagName( "Signature" );

   // Load the signature node.
   signedXml->LoadXml( safe_cast<XmlElement^>(nodeList->Item( 0 )) );

   // Check the signature and return the result.
   return signedXml->CheckSignature();
}


// Create example data to sign.
void CreateSomeXml( String^ FileName )
{

   // Create a new XmlDocument object.
   XmlDocument^ document = gcnew XmlDocument;

   // Create a new XmlNode object.
   XmlNode^ node = document->CreateNode( XmlNodeType::Element, "", "MyElement", "samples" );

   // Add some text to the node.
   node->InnerText = "Example text to be signed.";

   // Append the node to the document.
   document->AppendChild( node );

   // Save the XML document to the file name specified.
   XmlTextWriter^ xmltw = gcnew XmlTextWriter( FileName,gcnew UTF8Encoding( false ) );
   document->WriteTo( xmltw );
   xmltw->Close();
}

int main()
{
   try
   {

      // Generate a signing key.
      RSACryptoServiceProvider^ Key = gcnew RSACryptoServiceProvider;

      // Create an XML file to sign.
      CreateSomeXml( "Example.xml" );
      Console::WriteLine( "New XML file created." );

      // Sign the XML that was just created and save it in a 
      // new file.
      SignXmlFile( "Example.xml", "SignedExample.xml", Key );
      Console::WriteLine( "XML file signed." );

      // Verify the signature of the signed XML.
      Console::WriteLine( "Verifying signature..." );
      bool result = VerifyXmlFile( "SignedExample.xml" );

      // Display the results of the signature verification to
      // the console.
      if ( result )
      {
         Console::WriteLine( "The XML signature is valid." );
      }
      else
      {
         Console::WriteLine( "The XML signature is not valid." );
      }
   }
   catch ( CryptographicException^ e ) 
   {
      Console::WriteLine( e->Message );
   }

}

The following code example demonstrates how to generate and verify a detached XML signature using the RSAKeyValue object.

//
// This example signs a file specified by a URI 
// using a detached signature. It then verifies  
// the signed XML.
//
#using <System.Security.dll>
#using <System.Xml.dll>

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

// Sign an XML file and save the signature in a new file.
void SignDetachedResource( String^ URIString, String^ XmlSigFileName, RSA^ Key )
{

   // Create a SignedXml object.
   SignedXml^ signedXml = gcnew SignedXml;

   // Assign the key to the SignedXml object.
   signedXml->SigningKey = Key;

   // Create a reference to be signed.
   Reference^ reference = gcnew Reference;

   // Add the passed URI to the reference object.
   reference->Uri = URIString;

   // Add the reference to the SignedXml object.
   signedXml->AddReference( reference );

   // Add an RSAKeyValue KeyInfo (optional; helps recipient find key to validate).
   KeyInfo^ keyInfo = gcnew KeyInfo;
   keyInfo->AddClause( gcnew RSAKeyValue( safe_cast<RSA^>(Key) ) );
   signedXml->KeyInfo = keyInfo;

   // Compute the signature.
   signedXml->ComputeSignature();

   // Get the XML representation of the signature and save
   // it to an XmlElement object.
   XmlElement^ xmlDigitalSignature = signedXml->GetXml();

   // Save the signed XML document to a file specified
   // using the passed string.
   XmlTextWriter^ xmltw = gcnew XmlTextWriter( XmlSigFileName,gcnew UTF8Encoding( false ) );
   xmlDigitalSignature->WriteTo( xmltw );
   xmltw->Close();
}


// Verify the signature of an XML file and return the result.
Boolean VerifyDetachedSignature( String^ XmlSigFileName )
{

   // Create a new XML document.
   XmlDocument^ xmlDocument = gcnew XmlDocument;

   // Load the passed XML file into the document.
   xmlDocument->Load( XmlSigFileName );

   // Create a new SignedXMl object.
   SignedXml^ signedXml = gcnew SignedXml;

   // Find the "Signature" node and create a new
   // XmlNodeList object.
   XmlNodeList^ nodeList = xmlDocument->GetElementsByTagName( "Signature" );

   // Load the signature node.
   signedXml->LoadXml( safe_cast<XmlElement^>(nodeList->Item( 0 )) );

   // Check the signature and return the result.
   return signedXml->CheckSignature();
}



[STAThread]
int main()
{
   array<String^>^args = Environment::GetCommandLineArgs();

   // The URI to sign.
   String^ resourceToSign = "http://www.microsoft.com";

   // The name of the file to which to save the XML signature.
   String^ XmlFileName = "xmldsig.xml";
   try
   {

      // Generate a signing key.
      RSACryptoServiceProvider^ Key = gcnew RSACryptoServiceProvider;
      Console::WriteLine( "Signing: {0}", resourceToSign );

      // Sign the detached resourceand save the signature in an XML file.
      SignDetachedResource( resourceToSign, XmlFileName, Key );
      Console::WriteLine( "XML signature was succesfully computed and saved to {0}.", XmlFileName );

      // Verify the signature of the signed XML.
      Console::WriteLine( "Verifying signature..." );

      //Verify the XML signature in the XML file.
      bool result = VerifyDetachedSignature( XmlFileName );

      // Display the results of the signature verification to 
      // the console.
      if ( result )
      {
         Console::WriteLine( "The XML signature is valid." );
      }
      else
      {
         Console::WriteLine( "The XML signature is not valid." );
      }
   }
   catch ( CryptographicException^ e ) 
   {
      Console::WriteLine( e->Message );
   }

}

.NET Framework
Available since 1.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: