SignedXml クラス
アセンブリ: System.Security (system.security.dll 内)


SignedXml クラスは、.NET Framework での XML 署名および検証 (XMLDSIG) に使用されるメイン クラスです。XMLDSIG は、XML ドキュメントまたは URI (Uniform Resource Identifier) でアドレス指定できるその他のデータの全体または一部を署名および検証するための、標準に基づく、相互運用ができる方法です。.NET Framework XMLDSIG クラスは、W3C (World Wide Web Consortium) の XML 署名および検証に関する仕様 (http://www.w3.org/TR/xmldsig-core/) を実装します。
SignedXml クラスは、アプリケーション間または組織間で署名付きの XML データを標準的な方法で共有する必要がある場合に必ず使用します。このクラスを使用して署名されたデータは、W3C の XMLDSIG に関する仕様に準拠する実装によって検証できます。
XMLDSIG は <Signature> 要素を作成します。この要素は、XML ドキュメントまたは URI でアドレス指定できるその他のデータのデジタル署名を格納します。<Signature> 要素は、署名を検証するためのキーがある場所に関する情報、および署名に使用されている暗号アルゴリズムに関する情報をオプションで格納できます。
SignedXml クラスでは、次の 3 種類の XML デジタル署名を作成できます。
デタッチ シグネチャ |
-
キー情報を含めません。このオプションを選択した場合は、デジタル署名を交換する前に当事者の双方がアルゴリズムとキーについて合意している必要があります。
-
<RetrievalMethod> 要素の URI 属性にキーの場所を含めます。当事者の双方がキーの場所についてあらかじめ合意している必要があり、この場所を秘密にしておく必要があります。
-
<KeyName> 要素内に、キーにマップされる文字列名を含めます。暗号化されたデータを交換する前に当事者の双方がキー名のマップについて合意している必要があり、このマップを秘密にしておく必要があります。

エンベロープ シグネチャを使用して XML ドキュメント全体について署名および検証を行うコードの例を次に示します。
' ' This example signs an XML file using an ' envelope signature. It then verifies the ' signed XML. ' Imports System Imports System.Security.Cryptography Imports System.Security.Cryptography.X509Certificates Imports System.Security.Cryptography.Xml Imports System.Text Imports System.Xml Public Class SignVerifyEnvelope Overloads Public Shared Sub Main(args() As [String]) Try ' Generate a signing key. Dim Key As New 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...") Dim result As Boolean = VerifyXmlFile("SignedExample.xml", Key) ' Display the results of the signature verification to ' the console. If result Then Console.WriteLine("The XML signature is valid.") Else Console.WriteLine("The XML signature is not valid.") End If Catch e As CryptographicException Console.WriteLine(e.Message) End Try End Sub ' Sign an XML file and save the signature in a new file. This method does not ' save the public key within the XML file. This file cannot be verified unless ' the verifying code has the key with which it was signed. Public Shared Sub SignXmlFile(FileName As String, SignedFileName As String, Key As RSA) ' Create a new XML document. Dim doc As New XmlDocument() ' Load the passed XML file using its name. doc.Load(New XmlTextReader(FileName)) ' Create a SignedXml object. Dim signedXml As New SignedXml(doc) ' Add the key to the SignedXml document. signedXml.SigningKey = Key ' Create a reference to be signed. Dim reference As New Reference() reference.Uri = "" ' Add an enveloped transformation to the reference. Dim env As New XmlDsigEnvelopedSignatureTransform() reference.AddTransform(env) ' Add the reference to the SignedXml object. signedXml.AddReference(reference) ' Compute the signature. signedXml.ComputeSignature() ' Get the XML representation of the signature and save ' it to an XmlElement object. Dim xmlDigitalSignature As XmlElement = signedXml.GetXml() ' Append the element to the XML document. doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, True)) If TypeOf doc.FirstChild Is XmlDeclaration Then doc.RemoveChild(doc.FirstChild) End If ' Save the signed XML document to a file specified ' using the passed string. Dim xmltw As New XmlTextWriter(SignedFileName, New UTF8Encoding(False)) doc.WriteTo(xmltw) xmltw.Close() End Sub ' Verify the signature of an XML file against an asymetric ' algorithm and return the result. Public Shared Function VerifyXmlFile(Name As [String], Key As RSA) As [Boolean] ' Create a new XML document. Dim xmlDocument As New XmlDocument() ' Load the passed XML file into the document. xmlDocument.Load(Name) ' Create a new SignedXml object and pass it ' the XML document class. Dim signedXml As New SignedXml(xmlDocument) ' Find the "Signature" node and create a new ' XmlNodeList object. Dim nodeList As XmlNodeList = xmlDocument.GetElementsByTagName("Signature") ' Load the signature node. signedXml.LoadXml(CType(nodeList(0), XmlElement)) ' Check the signature and return the result. Return signedXml.CheckSignature(Key) End Function ' Create example data to sign. Public Shared Sub CreateSomeXml(FileName As String) ' Create a new XmlDocument object. Dim document As New XmlDocument() ' Create a new XmlNode object. Dim node As XmlNode = 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. Dim xmltw As New XmlTextWriter(FileName, New UTF8Encoding(False)) document.WriteTo(xmltw) xmltw.Close() End Sub End Class
// // This example signs an XML file using an // envelope signature. It then verifies the // signed XML. // using System; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Security.Cryptography.Xml; using System.Text; using System.Xml; public class SignVerifyEnvelope { public static void Main(String[] args) { try { // Generate a signing key. RSACryptoServiceProvider Key = new 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", Key); // 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); } } // Sign an XML file and save the signature in a new file. This method does not // save the public key within the XML file. This file cannot be verified unless // the verifying code has the key with which it was signed. public static void SignXmlFile(string FileName, string SignedFileName, RSA Key) { // Create a new XML document. XmlDocument doc = new XmlDocument(); // Load the passed XML file using its name. doc.Load(new XmlTextReader(FileName)); // Create a SignedXml object. SignedXml signedXml = new SignedXml(doc); // Add the key to the SignedXml document. signedXml.SigningKey = Key; // Create a reference to be signed. Reference reference = new Reference(); reference.Uri = ""; // Add an enveloped transformation to the reference. XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform(); reference.AddTransform(env); // Add the reference to the SignedXml object. signedXml.AddReference(reference); // 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 is XmlDeclaration) { doc.RemoveChild(doc.FirstChild); } // Save the signed XML document to a file specified // using the passed string. XmlTextWriter xmltw = new XmlTextWriter(SignedFileName, new UTF8Encoding(false)); doc.WriteTo(xmltw); xmltw.Close(); } // Verify the signature of an XML file against an asymetric // algorithm and return the result. public static Boolean VerifyXmlFile(String Name, RSA Key) { // Create a new XML document. XmlDocument xmlDocument = new XmlDocument(); // 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 = new SignedXml(xmlDocument); // Find the "Signature" node and create a new // XmlNodeList object. XmlNodeList nodeList = xmlDocument.GetElementsByTagName("Signature"); // Load the signature node. signedXml.LoadXml((XmlElement)nodeList[0]); // Check the signature and return the result. return signedXml.CheckSignature(Key); } // Create example data to sign. public static void CreateSomeXml(string FileName) { // Create a new XmlDocument object. XmlDocument document = new 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 = new XmlTextWriter(FileName, new UTF8Encoding(false)); document.WriteTo(xmltw); xmltw.Close(); } }
// // 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. This method does not // save the public key within the XML file. This file cannot be verified unless // the verifying code has the key with which it was signed. void SignXmlFile( String^ FileName, String^ SignedFileName, RSA^ Key ) { // Create a new XML document. XmlDocument^ doc = gcnew XmlDocument; // 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 ); // 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 against an asymmetric // algorithm and return the result. Boolean VerifyXmlFile( String^ Name, RSA^ Key ) { // Create a new XML document. XmlDocument^ xmlDocument = gcnew XmlDocument; // 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( Key ); } // 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", Key ); // 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 ); } }
デタッチ シグネチャを使用して、URI (Uniform Resource Identifier) によるアドレス指定が可能なオブジェクトについて署名および検査を行う方法を次のコード例に示します。
' ' This example signs a file specified by a URI ' using a detached signature. It then verifies ' the signed XML. ' Imports System Imports System.Security.Cryptography Imports System.Security.Cryptography.Xml Imports System.Text Imports System.Xml Class XMLDSIGDetached <STAThread()> _ Overloads Shared Sub Main(args() As String) ' The URI to sign. Dim resourceToSign As String = "http://www.microsoft.com" ' The name of the file to which to save the XML signature. Dim XmlFileName As String = "xmldsig.xml" Try ' Generate a signing key. Dim Key As New 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 against the key. Dim result As Boolean = VerifyDetachedSignature(XmlFileName, Key) ' Display the results of the signature verification to ' the console. If result Then Console.WriteLine("The XML signature is valid.") Else Console.WriteLine("The XML signature is not valid.") End If Catch e As CryptographicException Console.WriteLine(e.Message) End Try End Sub ' Sign an XML file and save the signature in a new file. This method does not ' save the public key within the XML file. This file cannot be verified unless ' the verifying code has the key with which it was signed. Public Shared Sub SignDetachedResource(URIString As String, XmlSigFileName As String, Key As RSA) ' Create a SignedXml object. Dim signedXml As New SignedXml() ' Assign the key to the SignedXml object. signedXml.SigningKey = Key ' Create a reference to be signed. Dim reference As New Reference() ' Add the passed URI to the reference object. reference.Uri = URIString ' Add the reference to the SignedXml object. signedXml.AddReference(reference) ' Compute the signature. signedXml.ComputeSignature() ' Get the XML representation of the signature and save ' it to an XmlElement object. Dim xmlDigitalSignature As XmlElement = signedXml.GetXml() ' Save the signed XML document to a file specified ' using the passed string. Dim xmltw As New XmlTextWriter(XmlSigFileName, New UTF8Encoding(False)) xmlDigitalSignature.WriteTo(xmltw) xmltw.Close() End Sub ' Verify the signature of an XML file against an asymetric ' algorithm and return the result. Public Shared Function VerifyDetachedSignature(XmlSigFileName As String, Key As RSA) As [Boolean] ' Create a new XML document. Dim xmlDocument As New XmlDocument() ' Load the passedXML file into the document. xmlDocument.Load(XmlSigFileName) ' Create a new SignedXml object. Dim signedXml As New SignedXml() ' Find the "Signature" node and create a new ' XmlNodeList object. Dim nodeList As XmlNodeList = xmlDocument.GetElementsByTagName("Signature") ' Load the signature node. signedXml.LoadXml(CType(nodeList(0), XmlElement)) ' Check the signature against the passed asymetric key ' and return the result. Return signedXml.CheckSignature(Key) End Function End Class
// // This example signs a file specified by a URI // using a detached signature. It then verifies // the signed XML. // using System; using System.Security.Cryptography; using System.Security.Cryptography.Xml; using System.Text; using System.Xml; class XMLDSIGDetached { [STAThread] static void Main(string[] args) { // 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 = new 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 against the key. bool result = VerifyDetachedSignature(XmlFileName, Key); // 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); } } // Sign an XML file and save the signature in a new file. This method does not // save the public key within the XML file. This file cannot be verified unless // the verifying code has the key with which it was signed. public static void SignDetachedResource(string URIString, string XmlSigFileName, RSA Key) { // Create a SignedXml object. SignedXml signedXml = new SignedXml(); // Assign the key to the SignedXml object. signedXml.SigningKey = Key; // Create a reference to be signed. Reference reference = new Reference(); // Add the passed URI to the reference object. reference.Uri = URIString; // Add the reference to the SignedXml object. signedXml.AddReference(reference); // 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 = new XmlTextWriter(XmlSigFileName, new UTF8Encoding(false)); xmlDigitalSignature.WriteTo(xmltw); xmltw.Close(); } // Verify the signature of an XML file against an asymetric // algorithm and return the result. public static Boolean VerifyDetachedSignature(string XmlSigFileName, RSA Key) { // Create a new XML document. XmlDocument xmlDocument = new XmlDocument(); // Load the passedXML file into the document. xmlDocument.Load(XmlSigFileName); // Create a new SignedXml object. SignedXml signedXml = new SignedXml(); // Find the "Signature" node and create a new // XmlNodeList object. XmlNodeList nodeList = xmlDocument.GetElementsByTagName("Signature"); // Load the signature node. signedXml.LoadXml((XmlElement)nodeList[0]); // Check the signature against the passed asymetric key // and return the result. return signedXml.CheckSignature(Key); } }
// // This example signs a file specified by a URI // using a detached signature. It then verifies // the signed XML. // #using <System.dll> #using <System.Xml.dll> #using <System.Security.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. This method does not // save the public key within the XML file. This file cannot be verified unless // the verifying code has the key with which it was signed. 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 ); // 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 against an asymetric // algorithm and return the result. static Boolean VerifyDetachedSignature( String^ XmlSigFileName, RSA^ Key ) { // Create a new XML document. XmlDocument^ xmlDocument = gcnew XmlDocument; // Load the passedXML 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( dynamic_cast<XmlElement^>(nodeList[ 0 ]) ); // Check the signature against the passed asymetric key // and return the result. return signedXml->CheckSignature( Key ); } int main() { // 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 against the key. bool result = VerifyDetachedSignature( XmlFileName, Key ); // 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 ); } }
// // This example signs a file specified by a URI // using a detached signature. It then verifies // the signed XML. // import System.*; import System.Security.Cryptography.*; import System.Security.Cryptography.Xml.*; import System.Text.*; import System.Xml.*; class XMLDSIGDetached { /** @attribute STAThread() */ public static void main(String[] args) { // 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 = new 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 against the key. boolean result = VerifyDetachedSignature(xmlFileName, key).booleanValue(); // 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.get_Message()); } } //main // Sign an XML file and save the signature in a new file. // This method does not save the public key within the // XML file. This file cannot be verified unless // the verifying code has the key with which it was signed. public static void SignDetachedResource(String uriString, String xmlSigFileName, RSA key) { // Create a SignedXml object. SignedXml signedXml = new SignedXml(); // Assign the key to the SignedXml object. signedXml.set_SigningKey(key); // Create a reference to be signed. Reference reference = new Reference(); // Add the passed URI to the reference object. reference.set_Uri(uriString); // Add a transformation if the URI is an XML file. if (uriString.EndsWith("xml")) { reference.AddTransform(new XmlDsigC14NTransform()); } // Add the reference to the SignedXml object. signedXml.AddReference(reference); // 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 = new XmlTextWriter(xmlSigFileName, new UTF8Encoding(false)); xmlDigitalSignature.WriteTo(xmlTW); xmlTW.Close(); } //SignDetachedResource // Verify the signature of an XML file against an asymetric // algorithm and return the result. public static Boolean VerifyDetachedSignature(String xmlSigFileName, RSA key) { // Create a new XML document. XmlDocument xmlDocument = new XmlDocument(); // Load the passedXML file into the document. xmlDocument.Load(xmlSigFileName); // Create a new SignedXml object. SignedXml signedXml = new SignedXml(); // Find the "Signature" node and create a new // XmlNodeList object. XmlNodeList nodeList = xmlDocument.GetElementsByTagName("Signature"); // Load the signature node. signedXml.LoadXml(((XmlElement)(nodeList.get_ItemOf(0)))); // Check the signature against the passed asymetric key // and return the result. return new Boolean(signedXml.CheckSignature(key)); } //VerifyDetachedSignature } //XMLDSIGDetached
エンベロープ シグネチャを使用して XML ドキュメントの単一の要素について署名および検証を行うコードの例を次に示します。
' This example signs an XML file using an ' envelope signature. It then verifies the ' signed XML. ' Imports System Imports System.Security.Cryptography Imports System.Security.Cryptography.Xml Imports System.Text Imports System.Xml Module SignVerifyEnvelope Sub Main(ByVal args() As String) ' Generate a signing key. Dim Key As New RSACryptoServiceProvider() Try ' Specify an element to sign. Dim elements As String() = New String() {"#tag1"} ' Sign an XML file and save the signature to a ' new file. SignXmlFile("Test.xml", "SignedExample.xml", Key, elements) Console.WriteLine("XML file signed.") ' Verify the signature of the signed XML. Console.WriteLine("Verifying signature...") Dim result As Boolean = VerifyXmlFile("SignedExample.xml") ' Display the results of the signature verification to \ ' the console. If result Then Console.WriteLine("The XML signature is valid.") Else Console.WriteLine("The XML signature is not valid.") End If Catch e As CryptographicException Console.WriteLine(e.Message) Finally ' Clear resources associated with the ' RSACryptoServiceProvider. Key.Clear() End Try End Sub ' Sign an XML file and save the signature in a new file. Sub SignXmlFile(ByVal FileName As String, ByVal SignedFileName As String, ByVal Key As RSA, ByVal ElementsToSign() As String) ' Check the arguments. If FileName Is Nothing Then Throw New ArgumentNullException("FileName") End If If SignedFileName Is Nothing Then Throw New ArgumentNullException("SignedFileName") End If If Key Is Nothing Then Throw New ArgumentNullException("Key") End If If ElementsToSign Is Nothing Then Throw New ArgumentNullException("ElementsToSign") End If ' Create a new XML document. Dim doc As New XmlDocument() ' Format the document to ignore white spaces. doc.PreserveWhitespace = False ' Load the passed XML file using it's name. doc.Load(New XmlTextReader(FileName)) ' Create a SignedXml object. Dim signedXml As New SignedXml(doc) ' Add the key to the SignedXml document. signedXml.SigningKey = Key ' Loop through each passed element to sign ' and create a reference. Dim s As String For Each s In ElementsToSign ' Create a reference to be signed. Dim reference As New Reference() reference.Uri = s ' Add an enveloped transformation to the reference. Dim env As New XmlDsigEnvelopedSignatureTransform() reference.AddTransform(env) ' Add the reference to the SignedXml object. signedXml.AddReference(reference) Next s ' Add an RSAKeyValue KeyInfo (optional; helps recipient find key to validate). Dim keyInfo As New KeyInfo() keyInfo.AddClause(New RSAKeyValue(CType(Key, RSA))) signedXml.KeyInfo = keyInfo ' Compute the signature. signedXml.ComputeSignature() ' Get the XML representation of the signature and save ' it to an XmlElement object. Dim xmlDigitalSignature As XmlElement = signedXml.GetXml() ' Append the element to the XML document. doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, True)) If TypeOf doc.FirstChild Is XmlDeclaration Then doc.RemoveChild(doc.FirstChild) End If ' Save the signed XML document to a file specified ' using the passed string. Dim xmltw As New XmlTextWriter(SignedFileName, New UTF8Encoding(False)) doc.WriteTo(xmltw) xmltw.Close() End Sub ' Verify the signature of an XML file and return the result. Function VerifyXmlFile(ByVal Name As String) As [Boolean] ' Check the arguments. If Name Is Nothing Then Throw New ArgumentNullException("Name") End If ' Create a new XML document. Dim xmlDocument As New 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. Dim signedXml As New SignedXml(xmlDocument) ' Find the "Signature" node and create a new ' XmlNodeList object. Dim nodeList As XmlNodeList = xmlDocument.GetElementsByTagName("Signature") ' Load the signature node. signedXml.LoadXml(CType(nodeList(0), XmlElement)) ' Check the signature and return the result. Return signedXml.CheckSignature() End Function End Module
// // This example signs an XML file using an // envelope signature. It then verifies the // signed XML. // using System; using System.Security.Cryptography; using System.Security.Cryptography.Xml; using System.Text; using System.Xml; public class SignVerifyEnvelope { public static void Main(String[] args) { // Generate a signing key. RSACryptoServiceProvider Key = new RSACryptoServiceProvider(); try { // Specify an element to sign. string[] elements = { "#tag1" }; // Sign an XML file and save the signature to a // new file. SignXmlFile("Test.xml", "SignedExample.xml", Key, elements); 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); } finally { // Clear resources associated with the // RSACryptoServiceProvider. Key.Clear(); } } // Sign an XML file and save the signature in a new file. public static void SignXmlFile(string FileName, string SignedFileName, RSA Key, string[] ElementsToSign) { // Check the arguments. if (FileName == null) throw new ArgumentNullException("FileName"); if (SignedFileName == null) throw new ArgumentNullException("SignedFileName"); if (Key == null) throw new ArgumentNullException("Key"); if (ElementsToSign == null) throw new ArgumentNullException("ElementsToSign"); // Create a new XML document. XmlDocument doc = new XmlDocument(); // Format the document to ignore white spaces. doc.PreserveWhitespace = false; // Load the passed XML file using it's name. doc.Load(new XmlTextReader(FileName)); // Create a SignedXml object. SignedXml signedXml = new SignedXml(doc); // Add the key to the SignedXml document. signedXml.SigningKey = Key; // Loop through each passed element to sign // and create a reference. foreach (string s in ElementsToSign) { // Create a reference to be signed. Reference reference = new Reference(); reference.Uri = s; // Add an enveloped transformation to the reference. XmlDsigEnvelopedSignatureTransform env = new 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 = new KeyInfo(); keyInfo.AddClause(new RSAKeyValue((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 is XmlDeclaration) { doc.RemoveChild(doc.FirstChild); } // Save the signed XML document to a file specified // using the passed string. XmlTextWriter xmltw = new XmlTextWriter(SignedFileName, new UTF8Encoding(false)); doc.WriteTo(xmltw); xmltw.Close(); } // Verify the signature of an XML file and return the result. public static Boolean VerifyXmlFile(String Name) { // Check the arguments. if (Name == null) throw new ArgumentNullException("Name"); // Create a new XML document. XmlDocument xmlDocument = new 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 = new SignedXml(xmlDocument); // Find the "Signature" node and create a new // XmlNodeList object. XmlNodeList nodeList = xmlDocument.GetElementsByTagName("Signature"); // Load the signature node. signedXml.LoadXml((XmlElement)nodeList[0]); // Check the signature and return the result. return signedXml.CheckSignature(); } }
// // This example signs an XML file using an // envelope signature. It then verifies the // signed XML. // #using <System.Xml.dll> #using <System.Security.dll> #using <System.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. static void SignXmlFile( String^ FileName, String^ SignedFileName, RSA^ Key, array<String^>^ElementsToSign ) { // Check the arguments. if ( FileName == nullptr ) throw gcnew ArgumentNullException( L"FileName" ); if ( SignedFileName == nullptr ) throw gcnew ArgumentNullException( L"SignedFileName" ); if ( Key == nullptr ) throw gcnew ArgumentNullException( L"Key" ); if ( ElementsToSign == nullptr ) throw gcnew ArgumentNullException( L"ElementsToSign" ); // 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 it's 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; // Loop through each passed element to sign // and create a reference. System::Collections::IEnumerator^ myEnum = ElementsToSign->GetEnumerator(); while ( myEnum->MoveNext() ) { String^ s = safe_cast<String^>(myEnum->Current); // Create a reference to be signed. Reference^ reference = gcnew Reference; reference->Uri = s; // 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( dynamic_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 ( dynamic_cast<XmlDeclaration^>(doc->FirstChild) ) { 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. static Boolean VerifyXmlFile( String^ Name ) { // Check the arguments. if ( Name == nullptr ) throw gcnew ArgumentNullException( L"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( L"Signature" ); // Load the signature node. signedXml->LoadXml( dynamic_cast<XmlElement^>(nodeList->Item( 0 )) ); // Check the signature and return the result. return signedXml->CheckSignature(); } int main() { // Generate a signing key. RSACryptoServiceProvider^ Key = gcnew RSACryptoServiceProvider; try { // Specify an element to sign. array<String^>^elements = {L"#tag1"}; // Sign an XML file and save the signature to a // new file. SignXmlFile( L"Test.xml", L"SignedExample.xml", Key, elements ); Console::WriteLine( L"XML file signed." ); // Verify the signature of the signed XML. Console::WriteLine( L"Verifying signature..." ); bool result = VerifyXmlFile( L"SignedExample.xml" ); // Display the results of the signature verification to // the console. if ( result ) { Console::WriteLine( L"The XML signature is valid." ); } else { Console::WriteLine( L"The XML signature is not valid." ); } } catch ( CryptographicException^ e ) { Console::WriteLine( e->Message ); } finally { // Clear resources associated with the // RSACryptoServiceProvider. Key->Clear(); } return 1; }

System.Security.Cryptography.Xml.SignedXml


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
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。


SignedXml コンストラクタ ()
アセンブリ: System.Security (system.security.dll 内)


エンベロープ シグネチャを使用して XML ドキュメント全体について署名および検証を行うコードの例を次に示します。
' This example signs an XML file using an ' envelope signature. It then verifies the ' signed XML. ' Imports System Imports System.Security.Cryptography Imports System.Security.Cryptography.Xml Imports System.Text Imports System.Xml Module SignVerifyEnvelope Sub Main(ByVal args() As String) ' Generate a signing key. Dim Key As New RSACryptoServiceProvider() Try ' Sign an XML file and save the signature to a ' new file. SignXmlFile("Test.xml", "SignedExample.xml", Key) Console.WriteLine("XML file signed.") ' Verify the signature of the signed XML. Console.WriteLine("Verifying signature...") Dim result As Boolean = VerifyXmlFile("SignedExample.xml") ' Display the results of the signature verification to ' the console. If result Then Console.WriteLine("The XML signature is valid.") Else Console.WriteLine("The XML signature is not valid.") End If Catch e As CryptographicException Console.WriteLine(e.Message) Finally ' Clear resources associated with the ' RSACryptoServiceProvider. Key.Clear() End Try End Sub ' Sign an XML file and save the signature in a new file. Sub SignXmlFile(ByVal FileName As String, ByVal SignedFileName As String, ByVal Key As RSA) ' Check the arguments. If FileName Is Nothing Then Throw New ArgumentNullException("FileName") End If If SignedFileName Is Nothing Then Throw New ArgumentNullException("SignedFileName") End If If Key Is Nothing Then Throw New ArgumentNullException("Key") End If ' Create a new XML document. Dim doc As New XmlDocument() ' Format the document to ignore white spaces. doc.PreserveWhitespace = False ' Load the passed XML file using it's name. doc.Load(New XmlTextReader(FileName)) ' Create a SignedXml object. Dim signedXml As New SignedXml(doc) ' Add the key to the SignedXml document. signedXml.SigningKey = Key ' Get the signature object from the SignedXml object. Dim XMLSignature As Signature = signedXml.Signature ' Create a reference to be signed. Pass "" ' to specify that all of the current XML ' document should be signed. Dim reference As New Reference("") ' Add an enveloped transformation to the reference. Dim env As New XmlDsigEnvelopedSignatureTransform() reference.AddTransform(env) ' Add the Reference object to the Signature object. XMLSignature.SignedInfo.AddReference(reference) ' Add an RSAKeyValue KeyInfo (optional; helps recipient find key to validate). Dim keyInfo As New KeyInfo() keyInfo.AddClause(New RSAKeyValue(CType(Key, RSA))) ' Add the KeyInfo object to the Reference object. XMLSignature.KeyInfo = keyInfo ' Compute the signature. signedXml.ComputeSignature() ' Get the XML representation of the signature and save ' it to an XmlElement object. Dim xmlDigitalSignature As XmlElement = signedXml.GetXml() ' Append the element to the XML document. doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, True)) If TypeOf doc.FirstChild Is XmlDeclaration Then doc.RemoveChild(doc.FirstChild) End If ' Save the signed XML document to a file specified ' using the passed string. Dim xmltw As New XmlTextWriter(SignedFileName, New UTF8Encoding(False)) doc.WriteTo(xmltw) xmltw.Close() End Sub ' Verify the signature of an XML file and return the result. Function VerifyXmlFile(ByVal Name As String) As [Boolean] ' Check the arguments. If Name Is Nothing Then Throw New ArgumentNullException("Name") End If ' Create a new XML document. Dim xmlDocument As New 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. Dim signedXml As New SignedXml(xmlDocument) ' Find the "Signature" node and create a new ' XmlNodeList object. Dim nodeList As XmlNodeList = xmlDocument.GetElementsByTagName("Signature") ' Load the signature node. signedXml.LoadXml(CType(nodeList(0), XmlElement)) ' Check the signature and return the result. Return signedXml.CheckSignature() End Function End Module
// // This example signs an XML file using an // envelope signature. It then verifies the // signed XML. // using System; using System.Security.Cryptography; using System.Security.Cryptography.Xml; using System.Text; using System.Xml; public class SignVerifyEnvelope { public static void Main(String[] args) { // Generate a signing key. RSACryptoServiceProvider Key = new RSACryptoServiceProvider(); try { // Sign an XML file and save the signature to a // new file. SignXmlFile("Test.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); } finally { // Clear resources associated with the // RSACryptoServiceProvider. Key.Clear(); } } // Sign an XML file and save the signature in a new file. public static void SignXmlFile(string FileName, string SignedFileName, RSA Key) { // Check the arguments. if (FileName == null) throw new ArgumentNullException("FileName"); if (SignedFileName == null) throw new ArgumentNullException("SignedFileName"); if (Key == null) throw new ArgumentNullException("Key"); // Create a new XML document. XmlDocument doc = new XmlDocument(); // Format the document to ignore white spaces. doc.PreserveWhitespace = false; // Load the passed XML file using it's name. doc.Load(new XmlTextReader(FileName)); // Create a SignedXml object. SignedXml signedXml = new SignedXml(doc); // Add the key to the SignedXml document. signedXml.SigningKey = Key; // Get the signature object from the SignedXml object. Signature XMLSignature = signedXml.Signature; // Create a reference to be signed. Pass "" // to specify that all of the current XML // document should be signed. Reference reference = new Reference(""); // Add an enveloped transformation to the reference. XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform(); reference.AddTransform(env); // Add the Reference object to the Signature object. XMLSignature.SignedInfo.AddReference(reference); // Add an RSAKeyValue KeyInfo (optional; helps recipient find key to validate). KeyInfo keyInfo = new KeyInfo(); keyInfo.AddClause(new RSAKeyValue((RSA)Key)); // Add the KeyInfo object to the Reference object. XMLSignature.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 is XmlDeclaration) { doc.RemoveChild(doc.FirstChild); } // Save the signed XML document to a file specified // using the passed string. XmlTextWriter xmltw = new XmlTextWriter(SignedFileName, new UTF8Encoding(false)); doc.WriteTo(xmltw); xmltw.Close(); } // Verify the signature of an XML file and return the result. public static Boolean VerifyXmlFile(String Name) { // Check the arguments. if (Name == null) throw new ArgumentNullException("Name"); // Create a new XML document. XmlDocument xmlDocument = new 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 = new SignedXml(xmlDocument); // Find the "Signature" node and create a new // XmlNodeList object. XmlNodeList nodeList = xmlDocument.GetElementsByTagName("Signature"); // Load the signature node. signedXml.LoadXml((XmlElement)nodeList[0]); // Check the signature and return the result. return signedXml.CheckSignature(); } }
// // This example signs an XML file using an // envelope signature. It then verifies the // signed XML. // #using <System.Xml.dll> #using <System.Security.dll> #using <System.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. static void SignXmlFile( String^ FileName, String^ SignedFileName, RSA^ Key ) { // Check the arguments. if ( FileName == nullptr ) throw gcnew ArgumentNullException( L"FileName" ); if ( SignedFileName == nullptr ) throw gcnew ArgumentNullException( L"SignedFileName" ); if ( Key == nullptr ) throw gcnew ArgumentNullException( L"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 it's 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; // Get the signature object from the SignedXml object. Signature^ XMLSignature = signedXml->Signature; // Create a reference to be signed. Pass "" // to specify that all of the current XML // document should be signed. Reference^ reference = gcnew Reference( L"" ); // Add an enveloped transformation to the reference. XmlDsigEnvelopedSignatureTransform^ env = gcnew XmlDsigEnvelopedSignatureTransform; reference->AddTransform( env ); // Add the Reference object to the Signature object. XMLSignature->SignedInfo->AddReference( reference ); // Add an RSAKeyValue KeyInfo (optional; helps recipient find key to validate). KeyInfo^ keyInfo = gcnew KeyInfo; keyInfo->AddClause( gcnew RSAKeyValue( dynamic_cast<RSA^>(Key) ) ); // Add the KeyInfo object to the Reference object. XMLSignature->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 ( dynamic_cast<XmlDeclaration^>(doc->FirstChild) ) { 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. static Boolean VerifyXmlFile( String^ Name ) { // Check the arguments. if ( Name == nullptr ) throw gcnew ArgumentNullException( L"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( L"Signature" ); // Load the signature node. signedXml->LoadXml( dynamic_cast<XmlElement^>(nodeList->Item( 0 )) ); // Check the signature and return the result. return signedXml->CheckSignature(); } int main() { // Generate a signing key. RSACryptoServiceProvider^ Key = gcnew RSACryptoServiceProvider; try { // Sign an XML file and save the signature to a // new file. SignXmlFile( L"Test.xml", L"SignedExample.xml", Key ); Console::WriteLine( L"XML file signed." ); // Verify the signature of the signed XML. Console::WriteLine( L"Verifying signature..." ); bool result = VerifyXmlFile( L"SignedExample.xml" ); // Display the results of the signature verification to // the console. if ( result ) { Console::WriteLine( L"The XML signature is valid." ); } else { Console::WriteLine( L"The XML signature is not valid." ); } } catch ( CryptographicException^ e ) { Console::WriteLine( e->Message ); } finally { // Clear resources associated with the // RSACryptoServiceProvider. Key->Clear(); } return 1; }
URI (Uniform Resource Identifier) によるアドレス指定が可能なオブジェクトについて、デタッチ シグネチャを使用して署名および検証を行うコードの例を次に示します。
' This example signs a URL using an ' envelope signature. It then verifies the ' signed XML. ' Imports System Imports System.Security.Cryptography Imports System.Security.Cryptography.Xml Imports System.Text Imports System.Xml Module SignVerifyEnvelope Sub Main(ByVal args() As String) ' Generate a signing key. Dim Key As New RSACryptoServiceProvider() Try ' Sign the detached resource and save the signature in an XML file. SignDetachedResource("http://www.microsoft.com", "SignedExample.xml", Key) Console.WriteLine("XML file signed.") ' Verify the signature of the signed XML. Console.WriteLine("Verifying signature...") Dim result As Boolean = VerifyXmlFile("SignedExample.xml") ' Display the results of the signature verification to \ ' the console. If result Then Console.WriteLine("The XML signature is valid.") Else Console.WriteLine("The XML signature is not valid.") End If Catch e As CryptographicException Console.WriteLine(e.Message) Finally ' Clear resources associated with the ' RSACryptoServiceProvider. Key.Clear() End Try End Sub ' Sign an XML file and save the signature in a new file. Sub SignDetachedResource(ByVal URIString As String, ByVal XmlSigFileName As String, ByVal Key As RSA) ' Check the arguments. If URIString Is Nothing Then Throw New ArgumentNullException("URIString") End If If XmlSigFileName Is Nothing Then Throw New ArgumentNullException("XmlSigFileName") End If If Key Is Nothing Then Throw New ArgumentNullException("Key") End If ' Create a SignedXml object. Dim signedXml As New SignedXml() ' Assign the key to the SignedXml object. signedXml.SigningKey = Key ' Get the signature object from the SignedXml object. Dim XMLSignature As Signature = signedXml.Signature ' Create a reference to be signed. Dim reference As New Reference() ' Add the passed URI to the reference object. reference.Uri = URIString ' Add the Reference object to the Signature object. XMLSignature.SignedInfo.AddReference(reference) ' Add an RSAKeyValue KeyInfo (optional; helps recipient find key to validate). Dim keyInfo As New KeyInfo() keyInfo.AddClause(New RSAKeyValue(CType(Key, RSA))) ' Add the KeyInfo object to the Reference object. XMLSignature.KeyInfo = keyInfo ' Compute the signature. signedXml.ComputeSignature() ' Get the XML representation of the signature and save ' it to an XmlElement object. Dim xmlDigitalSignature As XmlElement = signedXml.GetXml() ' Save the signed XML document to a file specified ' using the passed string. Dim xmltw As New XmlTextWriter(XmlSigFileName, New UTF8Encoding(False)) xmlDigitalSignature.WriteTo(xmltw) xmltw.Close() End Sub ' Verify the signature of an XML file and return the result. Function VerifyXmlFile(ByVal Name As String) As [Boolean] ' Check the arguments. If Name Is Nothing Then Throw New ArgumentNullException("Name") End If ' Create a new XML document. Dim xmlDocument As New 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. Dim signedXml As New SignedXml(xmlDocument) ' Find the "Signature" node and create a new ' XmlNodeList object. Dim nodeList As XmlNodeList = xmlDocument.GetElementsByTagName("Signature") ' Load the signature node. signedXml.LoadXml(CType(nodeList(0), XmlElement)) ' Check the signature and return the result. Return signedXml.CheckSignature() End Function End Module
// // This example signs a URL using an // envelope signature. It then verifies the // signed XML. // using System; using System.Security.Cryptography; using System.Security.Cryptography.Xml; using System.Text; using System.Xml; public class SignVerifyEnvelope { public static void Main(String[] args) { // Generate a signing key. RSACryptoServiceProvider Key = new RSACryptoServiceProvider(); try { // Sign the detached resource and save the signature in an XML file. SignDetachedResource("http://www.microsoft.com", "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); } finally { // Clear resources associated with the // RSACryptoServiceProvider. Key.Clear(); } } // Sign an XML file and save the signature in a new file. public static void SignDetachedResource(string URIString, string XmlSigFileName, RSA Key) { // Check the arguments. if (URIString == null) throw new ArgumentNullException("URIString"); if (XmlSigFileName == null) throw new ArgumentNullException("XmlSigFileName"); if (Key == null) throw new ArgumentNullException("Key"); // Create a SignedXml object. SignedXml signedXml = new SignedXml(); // Assign the key to the SignedXml object. signedXml.SigningKey = Key; // Get the signature object from the SignedXml object. Signature XMLSignature = signedXml.Signature; // Create a reference to be signed. Reference reference = new Reference(); // Add the passed URI to the reference object. reference.Uri = URIString; // Add the Reference object to the Signature object. XMLSignature.SignedInfo.AddReference(reference); // Add an RSAKeyValue KeyInfo (optional; helps recipient find key to validate). KeyInfo keyInfo = new KeyInfo(); keyInfo.AddClause(new RSAKeyValue((RSA)Key)); // Add the KeyInfo object to the Reference object. XMLSignature.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 = new XmlTextWriter(XmlSigFileName, new UTF8Encoding(false)); xmlDigitalSignature.WriteTo(xmltw); xmltw.Close(); } // Verify the signature of an XML file and return the result. public static Boolean VerifyXmlFile(String Name) { // Check the arguments. if (Name == null) throw new ArgumentNullException("Name"); // Create a new XML document. XmlDocument xmlDocument = new 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 = new SignedXml(xmlDocument); // Find the "Signature" node and create a new // XmlNodeList object. XmlNodeList nodeList = xmlDocument.GetElementsByTagName("Signature"); // Load the signature node. signedXml.LoadXml((XmlElement)nodeList[0]); // Check the signature and return the result. return signedXml.CheckSignature(); } }
// // This example signs a URL using an // envelope signature. It then verifies the // signed XML. // #using <System.dll> #using <System.Xml.dll> #using <System.Security.dll> using namespace System; using namespace System::Security::Cryptography; using namespace System::Security::Cryptography::Xml; using namespace System::Text; using namespace System::Xml; namespace Sample { public ref class SignVerifyEnvelope { public: static void Work() { // Generate a signing key. RSACryptoServiceProvider^ key = gcnew RSACryptoServiceProvider(); try { // Sign the detached resource and save the // signature in an XML file. SignDetachedResource("http://www.microsoft.com" , "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."); } Console::ReadLine(); } catch (CryptographicException^ ex) { Console::WriteLine(ex->Message); } finally { // Clear resources associated with the // RSACryptoServiceProvider. key->Clear(); } } // Sign an XML file and save the signature in a new file. static void SignDetachedResource(String^ uri, String^ xmlFileName, RSA^ key) { // Check the arguments. if (uri->Length == 0) { throw gcnew ArgumentException("uri"); } if (xmlFileName->Length == 0) { throw gcnew ArgumentException("xmlFileName"); } if (key->KeySize == 0) { throw gcnew ArgumentException("key"); } // Create a SignedXml object. SignedXml^ signedXml = gcnew SignedXml(); // Assign the key to the SignedXml object. signedXml->SigningKey = key; // Get the signature object from the SignedXml object. Signature^ xmlSignature = signedXml->Signature; // Create a reference to be signed. Reference^ reference = gcnew Reference(); // Add the passed URI to the reference object. reference->Uri = uri; // Add the Reference object to the Signature object. xmlSignature->SignedInfo->AddReference(reference); // Add an RSAKeyValue KeyInfo (optional; helps recipient // find key to validate). KeyInfo^ keyInfo = gcnew KeyInfo(); keyInfo->AddClause( gcnew RSAKeyValue(key)); // Add the KeyInfo object to the Reference object. xmlSignature->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^ xmlTextWriter = gcnew XmlTextWriter( xmlFileName, gcnew UTF8Encoding(false)); xmlDigitalSignature->WriteTo(xmlTextWriter); xmlTextWriter->Close(); } // Verify the signature of an XML file and return the result. static Boolean VerifyXmlFile(String^ documentName) { // Check the arguments. if (documentName->Length == 0) { throw gcnew ArgumentException("documentName"); } // 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(documentName); // 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( (XmlElement^) nodeList->Item(0)); // Check the signature and return the result. return signedXml->CheckSignature(); } }; } int main() { Sample::SignVerifyEnvelope::Work(); }
エンベロープ シグネチャを使用して XML ドキュメントの単一の要素について署名および検証を行うコードの例を次に示します。
' This example signs an XML file using an ' envelope signature. It then verifies the ' signed XML. ' Imports System Imports System.Security.Cryptography Imports System.Security.Cryptography.Xml Imports System.Text Imports System.Xml Module SignVerifyEnvelope Sub Main(ByVal args() As String) ' Generate a signing key. Dim Key As New RSACryptoServiceProvider() Try ' Specify an element to sign. Dim elements As String() = New String() {"#tag1"} ' Sign an XML file and save the signature to a ' new file. SignXmlFile("Test.xml", "SignedExample.xml", Key, elements) Console.WriteLine("XML file signed.") ' Verify the signature of the signed XML. Console.WriteLine("Verifying signature...") Dim result As Boolean = VerifyXmlFile("SignedExample.xml") ' Display the results of the signature verification to \ ' the console. If result Then Console.WriteLine("The XML signature is valid.") Else Console.WriteLine("The XML signature is not valid.") End If Catch e As CryptographicException Console.WriteLine(e.Message) Finally ' Clear resources associated with the ' RSACryptoServiceProvider. Key.Clear() End Try End Sub ' Sign an XML file and save the signature in a new file. Sub SignXmlFile(ByVal FileName As String, ByVal SignedFileName As String, ByVal Key As RSA, ByVal ElementsToSign() As String) ' Check the arguments. If FileName Is Nothing Then Throw New ArgumentNullException("FileName") End If If SignedFileName Is Nothing Then Throw New ArgumentNullException("SignedFileName") End If If Key Is Nothing Then Throw New ArgumentNullException("Key") End If If ElementsToSign Is Nothing Then Throw New ArgumentNullException("ElementsToSign") End If ' Create a new XML document. Dim doc As New XmlDocument() ' Format the document to ignore white spaces. doc.PreserveWhitespace = False ' Load the passed XML file using it's name. doc.Load(New XmlTextReader(FileName)) ' Create a SignedXml object. Dim signedXml As New SignedXml(doc) ' Add the key to the SignedXml document. signedXml.SigningKey = Key ' Loop through each passed element to sign ' and create a reference. Dim s As String For Each s In ElementsToSign ' Create a reference to be signed. Dim reference As New Reference() reference.Uri = s ' Add an enveloped transformation to the reference. Dim env As New XmlDsigEnvelopedSignatureTransform() reference.AddTransform(env) ' Add the reference to the SignedXml object. signedXml.AddReference(reference) Next s ' Add an RSAKeyValue KeyInfo (optional; helps recipient find key to validate). Dim keyInfo As New KeyInfo() keyInfo.AddClause(New RSAKeyValue(CType(Key, RSA))) signedXml.KeyInfo = keyInfo ' Compute the signature. signedXml.ComputeSignature() ' Get the XML representation of the signature and save ' it to an XmlElement object. Dim xmlDigitalSignature As XmlElement = signedXml.GetXml() ' Append the element to the XML document. doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, True)) If TypeOf doc.FirstChild Is XmlDeclaration Then doc.RemoveChild(doc.FirstChild) End If ' Save the signed XML document to a file specified ' using the passed string. Dim xmltw As New XmlTextWriter(SignedFileName, New UTF8Encoding(False)) doc.WriteTo(xmltw) xmltw.Close() End Sub ' Verify the signature of an XML file and return the result. Function VerifyXmlFile(ByVal Name As String) As [Boolean] ' Check the arguments. If Name Is Nothing Then Throw New ArgumentNullException("Name") End If ' Create a new XML document. Dim xmlDocument As New 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. Dim signedXml As New SignedXml(xmlDocument) ' Find the "Signature" node and create a new ' XmlNodeList object. Dim nodeList As XmlNodeList = xmlDocument.GetElementsByTagName("Signature") ' Load the signature node. signedXml.LoadXml(CType(nodeList(0), XmlElement)) ' Check the signature and return the result. Return signedXml.CheckSignature() End Function End Module
// // This example signs an XML file using an // envelope signature. It then verifies the // signed XML. // using System; using System.Security.Cryptography; using System.Security.Cryptography.Xml; using System.Text; using System.Xml; public class SignVerifyEnvelope { public static void Main(String[] args) { // Generate a signing key. RSACryptoServiceProvider Key = new RSACryptoServiceProvider(); try { // Specify an element to sign. string[] elements = { "#tag1" }; // Sign an XML file and save the signature to a // new file. SignXmlFile("Test.xml", "SignedExample.xml", Key, elements); 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); } finally { // Clear resources associated with the // RSACryptoServiceProvider. Key.Clear(); } } // Sign an XML file and save the signature in a new file. public static void SignXmlFile(string FileName, string SignedFileName, RSA Key, string[] ElementsToSign) { // Check the arguments. if (FileName == null) throw new ArgumentNullException("FileName"); if (SignedFileName == null) throw new ArgumentNullException("SignedFileName"); if (Key == null) throw new ArgumentNullException("Key"); if (ElementsToSign == null) throw new ArgumentNullException("ElementsToSign"); // Create a new XML document. XmlDocument doc = new XmlDocument(); // Format the document to ignore white spaces. doc.PreserveWhitespace = false; // Load the passed XML file using it's name. doc.Load(new XmlTextReader(FileName)); // Create a SignedXml object. SignedXml signedXml = new SignedXml(doc); // Add the key to the SignedXml document. signedXml.SigningKey = Key; // Loop through each passed element to sign // and create a reference. foreach (string s in ElementsToSign) { // Create a reference to be signed. Reference reference = new Reference(); reference.Uri = s; // Add an enveloped transformation to the reference. XmlDsigEnvelopedSignatureTransform env = new 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 = new KeyInfo(); keyInfo.AddClause(new RSAKeyValue((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 is XmlDeclaration) { doc.RemoveChild(doc.FirstChild); } // Save the signed XML document to a file specified // using the passed string. XmlTextWriter xmltw = new XmlTextWriter(SignedFileName, new UTF8Encoding(false)); doc.WriteTo(xmltw); xmltw.Close(); } // Verify the signature of an XML file and return the result. public static Boolean VerifyXmlFile(String Name) { // Check the arguments. if (Name == null) throw new ArgumentNullException("Name"); // Create a new XML document. XmlDocument xmlDocument = new 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 = new SignedXml(xmlDocument); // Find the "Signature" node and create a new // XmlNodeList object. XmlNodeList nodeList = xmlDocument.GetElementsByTagName("Signature"); // Load the signature node. signedXml.LoadXml((XmlElement)nodeList[0]); // Check the signature and return the result. return signedXml.CheckSignature(); } }
// // This example signs an XML file using an // envelope signature. It then verifies the // signed XML. // #using <System.Xml.dll> #using <System.Security.dll> #using <System.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. static void SignXmlFile( String^ FileName, String^ SignedFileName, RSA^ Key, array<String^>^ElementsToSign ) { // Check the arguments. if ( FileName == nullptr ) throw gcnew ArgumentNullException( L"FileName" ); if ( SignedFileName == nullptr ) throw gcnew ArgumentNullException( L"SignedFileName" ); if ( Key == nullptr ) throw gcnew ArgumentNullException( L"Key" ); if ( ElementsToSign == nullptr ) throw gcnew ArgumentNullException( L"ElementsToSign" ); // 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 it's 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; // Loop through each passed element to sign // and create a reference. System::Collections::IEnumerator^ myEnum = ElementsToSign->GetEnumerator(); while ( myEnum->MoveNext() ) { String^ s = safe_cast<String^>(myEnum->Current); // Create a reference to be signed. Reference^ reference = gcnew Reference; reference->Uri = s; // 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( dynamic_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 ( dynamic_cast<XmlDeclaration^>(doc->FirstChild) ) { 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. static Boolean VerifyXmlFile( String^ Name ) { // Check the arguments. if ( Name == nullptr ) throw gcnew ArgumentNullException( L"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( L"Signature" ); // Load the signature node. signedXml->LoadXml( dynamic_cast<XmlElement^>(nodeList->Item( 0 )) ); // Check the signature and return the result. return signedXml->CheckSignature(); } int main() { // Generate a signing key. RSACryptoServiceProvider^ Key = gcnew RSACryptoServiceProvider; try { // Specify an element to sign. array<String^>^elements = {L"#tag1"}; // Sign an XML file and save the signature to a // new file. SignXmlFile( L"Test.xml", L"SignedExample.xml", Key, elements ); Console::WriteLine( L"XML file signed." ); // Verify the signature of the signed XML. Console::WriteLine( L"Verifying signature..." ); bool result = VerifyXmlFile( L"SignedExample.xml" ); // Display the results of the signature verification to // the console. if ( result ) { Console::WriteLine( L"The XML signature is valid." ); } else { Console::WriteLine( L"The XML signature is not valid." ); } } catch ( CryptographicException^ e ) { Console::WriteLine( e->Message ); } finally { // Clear resources associated with the // RSACryptoServiceProvider. Key->Clear(); } return 1; }

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
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。


SignedXml コンストラクタ (XmlDocument)
アセンブリ: System.Security (system.security.dll 内)



エンベロープ シグネチャを使用して XML ドキュメント全体について署名および検証を行うコードの例を次に示します。
' This example signs an XML file using an ' envelope signature. It then verifies the ' signed XML. ' Imports System Imports System.Security.Cryptography Imports System.Security.Cryptography.Xml Imports System.Text Imports System.Xml Module SignVerifyEnvelope Sub Main(ByVal args() As String) ' Generate a signing key. Dim Key As New RSACryptoServiceProvider() Try ' Sign an XML file and save the signature to a ' new file. SignXmlFile("Test.xml", "SignedExample.xml", Key) Console.WriteLine("XML file signed.") ' Verify the signature of the signed XML. Console.WriteLine("Verifying signature...") Dim result As Boolean = VerifyXmlFile("SignedExample.xml") ' Display the results of the signature verification to ' the console. If result Then Console.WriteLine("The XML signature is valid.") Else Console.WriteLine("The XML signature is not valid.") End If Catch e As CryptographicException Console.WriteLine(e.Message) Finally ' Clear resources associated with the ' RSACryptoServiceProvider. Key.Clear() End Try End Sub ' Sign an XML file and save the signature in a new file. Sub SignXmlFile(ByVal FileName As String, ByVal SignedFileName As String, ByVal Key As RSA) ' Check the arguments. If FileName Is Nothing Then Throw New ArgumentNullException("FileName") End If If SignedFileName Is Nothing Then Throw New ArgumentNullException("SignedFileName") End If If Key Is Nothing Then Throw New ArgumentNullException("Key") End If ' Create a new XML document. Dim doc As New XmlDocument() ' Format the document to ignore white spaces. doc.PreserveWhitespace = False ' Load the passed XML file using it's name. doc.Load(New XmlTextReader(FileName)) ' Create a SignedXml object. Dim signedXml As New SignedXml(doc) ' Add the key to the SignedXml document. signedXml.SigningKey = Key ' Get the signature object from the SignedXml object. Dim XMLSignature As Signature = signedXml.Signature ' Create a reference to be signed. Pass "" ' to specify that all of the current XML ' document should be signed. Dim reference As New Reference("") ' Add an enveloped transformation to the reference. Dim env As New XmlDsigEnvelopedSignatureTransform() reference.AddTransform(env) ' Add the Reference object to the Signature object. XMLSignature.SignedInfo.AddReference(reference) ' Add an RSAKeyValue KeyInfo (optional; helps recipient find key to validate). Dim keyInfo As New KeyInfo() keyInfo.AddClause(New RSAKeyValue(CType(Key, RSA))) ' Add the KeyInfo object to the Reference object. XMLSignature.KeyInfo = keyInfo ' Compute the signature. signedXml.ComputeSignature() ' Get the XML representation of the signature and save ' it to an XmlElement object. Dim xmlDigitalSignature As XmlElement = signedXml.GetXml() ' Append the element to the XML document. doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, True)) If TypeOf doc.FirstChild Is XmlDeclaration Then doc.RemoveChild(doc.FirstChild) End If ' Save the signed XML document to a file specified ' using the passed string. Dim xmltw As New XmlTextWriter(SignedFileName, New UTF8Encoding(False)) doc.WriteTo(xmltw) xmltw.Close() End Sub ' Verify the signature of an XML file and return the result. Function VerifyXmlFile(ByVal Name As String) As [Boolean] ' Check the arguments. If Name Is Nothing Then Throw New ArgumentNullException("Name") End If ' Create a new XML document. Dim xmlDocument As New 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. Dim signedXml As New SignedXml(xmlDocument) ' Find the "Signature" node and create a new ' XmlNodeList object. Dim nodeList As XmlNodeList = xmlDocument.GetElementsByTagName("Signature") ' Load the signature node. signedXml.LoadXml(CType(nodeList(0), XmlElement)) ' Check the signature and return the result. Return signedXml.CheckSignature() End Function End Module
// // This example signs an XML file using an // envelope signature. It then verifies the // signed XML. // using System; using System.Security.Cryptography; using System.Security.Cryptography.Xml; using System.Text; using System.Xml; public class SignVerifyEnvelope { public static void Main(String[] args) { // Generate a signing key. RSACryptoServiceProvider Key = new RSACryptoServiceProvider(); try { // Sign an XML file and save the signature to a // new file. SignXmlFile("Test.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); } finally { // Clear resources associated with the // RSACryptoServiceProvider. Key.Clear(); } } // Sign an XML file and save the signature in a new file. public static void SignXmlFile(string FileName, string SignedFileName, RSA Key) { // Check the arguments. if (FileName == null) throw new ArgumentNullException("FileName"); if (SignedFileName == null) throw new ArgumentNullException("SignedFileName"); if (Key == null) throw new ArgumentNullException("Key"); // Create a new XML document. XmlDocument doc = new XmlDocument(); // Format the document to ignore white spaces. doc.PreserveWhitespace = false; // Load the passed XML file using it's name. doc.Load(new XmlTextReader(FileName)); // Create a SignedXml object. SignedXml signedXml = new SignedXml(doc); // Add the key to the SignedXml document. signedXml.SigningKey = Key; // Get the signature object from the SignedXml object. Signature XMLSignature = signedXml.Signature; // Create a reference to be signed. Pass "" // to specify that all of the current XML // document should be signed. Reference reference = new Reference(""); // Add an enveloped transformation to the reference. XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform(); reference.AddTransform(env); // Add the Reference object to the Signature object. XMLSignature.SignedInfo.AddReference(reference); // Add an RSAKeyValue KeyInfo (optional; helps recipient find key to validate). KeyInfo keyInfo = new KeyInfo(); keyInfo.AddClause(new RSAKeyValue((RSA)Key)); // Add the KeyInfo object to the Reference object. XMLSignature.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 is XmlDeclaration) { doc.RemoveChild(doc.FirstChild); } // Save the signed XML document to a file specified // using the passed string. XmlTextWriter xmltw = new XmlTextWriter(SignedFileName, new UTF8Encoding(false)); doc.WriteTo(xmltw); xmltw.Close(); } // Verify the signature of an XML file and return the result. public static Boolean VerifyXmlFile(String Name) { // Check the arguments. if (Name == null) throw new ArgumentNullException("Name"); // Create a new XML document. XmlDocument xmlDocument = new 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 = new SignedXml(xmlDocument); // Find the "Signature" node and create a new // XmlNodeList object. XmlNodeList nodeList = xmlDocument.GetElementsByTagName("Signature"); // Load the signature node. signedXml.LoadXml((XmlElement)nodeList[0]); // Check the signature and return the result. return signedXml.CheckSignature(); } }
// // This example signs an XML file using an // envelope signature. It then verifies the // signed XML. // #using <System.Xml.dll> #using <System.Security.dll> #using <System.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. static void SignXmlFile( String^ FileName, String^ SignedFileName, RSA^ Key ) { // Check the arguments. if ( FileName == nullptr ) throw gcnew ArgumentNullException( L"FileName" ); if ( SignedFileName == nullptr ) throw gcnew ArgumentNullException( L"SignedFileName" ); if ( Key == nullptr ) throw gcnew ArgumentNullException( L"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 it's 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; // Get the signature object from the SignedXml object. Signature^ XMLSignature = signedXml->Signature; // Create a reference to be signed. Pass "" // to specify that all of the current XML // document should be signed. Reference^ reference = gcnew Reference( L"" ); // Add an enveloped transformation to the reference. XmlDsigEnvelopedSignatureTransform^ env = gcnew XmlDsigEnvelopedSignatureTransform; reference->AddTransform( env ); // Add the Reference object to the Signature object. XMLSignature->SignedInfo->AddReference( reference ); // Add an RSAKeyValue KeyInfo (optional; helps recipient find key to validate). KeyInfo^ keyInfo = gcnew KeyInfo; keyInfo->AddClause( gcnew RSAKeyValue( dynamic_cast<RSA^>(Key) ) ); // Add the KeyInfo object to the Reference object. XMLSignature->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 ( dynamic_cast<XmlDeclaration^>(doc->FirstChild) ) { 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. static Boolean VerifyXmlFile( String^ Name ) { // Check the arguments. if ( Name == nullptr ) throw gcnew ArgumentNullException( L"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( L"Signature" ); // Load the signature node. signedXml->LoadXml( dynamic_cast<XmlElement^>(nodeList->Item( 0 )) ); // Check the signature and return the result. return signedXml->CheckSignature(); } int main() { // Generate a signing key. RSACryptoServiceProvider^ Key = gcnew RSACryptoServiceProvider; try { // Sign an XML file and save the signature to a // new file. SignXmlFile( L"Test.xml", L"SignedExample.xml", Key ); Console::WriteLine( L"XML file signed." ); // Verify the signature of the signed XML. Console::WriteLine( L"Verifying signature..." ); bool result = VerifyXmlFile( L"SignedExample.xml" ); // Display the results of the signature verification to // the console. if ( result ) { Console::WriteLine( L"The XML signature is valid." ); } else { Console::WriteLine( L"The XML signature is not valid." ); } } catch ( CryptographicException^ e ) { Console::WriteLine( e->Message ); } finally { // Clear resources associated with the // RSACryptoServiceProvider. Key->Clear(); } return 1; }
URI (Uniform Resource Identifier) によるアドレス指定が可能なオブジェクトについて、デタッチ シグネチャを使用して署名および検証を行うコードの例を次に示します。
' This example signs a URL using an ' envelope signature. It then verifies the ' signed XML. ' Imports System Imports System.Security.Cryptography Imports System.Security.Cryptography.Xml Imports System.Text Imports System.Xml Module SignVerifyEnvelope Sub Main(ByVal args() As String) ' Generate a signing key. Dim Key As New RSACryptoServiceProvider() Try ' Sign the detached resource and save the signature in an XML file. SignDetachedResource("http://www.microsoft.com", "SignedExample.xml", Key) Console.WriteLine("XML file signed.") ' Verify the signature of the signed XML. Console.WriteLine("Verifying signature...") Dim result As Boolean = VerifyXmlFile("SignedExample.xml") ' Display the results of the signature verification to \ ' the console. If result Then Console.WriteLine("The XML signature is valid.") Else Console.WriteLine("The XML signature is not valid.") End If Catch e As CryptographicException Console.WriteLine(e.Message) Finally ' Clear resources associated with the ' RSACryptoServiceProvider. Key.Clear() End Try End Sub ' Sign an XML file and save the signature in a new file. Sub SignDetachedResource(ByVal URIString As String, ByVal XmlSigFileName As String, ByVal Key As RSA) ' Check the arguments. If URIString Is Nothing Then Throw New ArgumentNullException("URIString") End If If XmlSigFileName Is Nothing Then Throw New ArgumentNullException("XmlSigFileName") End If If Key Is Nothing Then Throw New ArgumentNullException("Key") End If ' Create a SignedXml object. Dim signedXml As New SignedXml() ' Assign the key to the SignedXml object. signedXml.SigningKey = Key ' Get the signature object from the SignedXml object. Dim XMLSignature As Signature = signedXml.Signature ' Create a reference to be signed. Dim reference As New Reference() ' Add the passed URI to the reference object. reference.Uri = URIString ' Add the Reference object to the Signature object. XMLSignature.SignedInfo.AddReference(reference) ' Add an RSAKeyValue KeyInfo (optional; helps recipient find key to validate). Dim keyInfo As New KeyInfo() keyInfo.AddClause(New RSAKeyValue(CType(Key, RSA))) ' Add the KeyInfo object to the Reference object. XMLSignature.KeyInfo = keyInfo ' Compute the signature. signedXml.ComputeSignature() ' Get the XML representation of the signature and save ' it to an XmlElement object. Dim xmlDigitalSignature As XmlElement = signedXml.GetXml() ' Save the signed XML document to a file specified ' using the passed string. Dim xmltw As New XmlTextWriter(XmlSigFileName, New UTF8Encoding(False)) xmlDigitalSignature.WriteTo(xmltw) xmltw.Close() End Sub ' Verify the signature of an XML file and return the result. Function VerifyXmlFile(ByVal Name As String) As [Boolean] ' Check the arguments. If Name Is Nothing Then Throw New ArgumentNullException("Name") End If ' Create a new XML document. Dim xmlDocument As New 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. Dim signedXml As New SignedXml(xmlDocument) ' Find the "Signature" node and create a new ' XmlNodeList object. Dim nodeList As XmlNodeList = xmlDocument.GetElementsByTagName("Signature") ' Load the signature node. signedXml.LoadXml(CType(nodeList(0), XmlElement)) ' Check the signature and return the result. Return signedXml.CheckSignature() End Function End Module
// // This example signs a URL using an // envelope signature. It then verifies the // signed XML. // using System; using System.Security.Cryptography; using System.Security.Cryptography.Xml; using System.Text; using System.Xml; public class SignVerifyEnvelope { public static void Main(String[] args) { // Generate a signing key. RSACryptoServiceProvider Key = new RSACryptoServiceProvider(); try { // Sign the detached resource and save the signature in an XML file. SignDetachedResource("http://www.microsoft.com", "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); } finally { // Clear resources associated with the // RSACryptoServiceProvider. Key.Clear(); } } // Sign an XML file and save the signature in a new file. public static void SignDetachedResource(string URIString, string XmlSigFileName, RSA Key) { // Check the arguments. if (URIString == null) throw new ArgumentNullException("URIString"); if (XmlSigFileName == null) throw new ArgumentNullException("XmlSigFileName"); if (Key == null) throw new ArgumentNullException("Key"); // Create a SignedXml object. SignedXml signedXml = new SignedXml(); // Assign the key to the SignedXml object. signedXml.SigningKey = Key; // Get the signature object from the SignedXml object. Signature XMLSignature = signedXml.Signature; // Create a reference to be signed. Reference reference = new Reference(); // Add the passed URI to the reference object. reference.Uri = URIString; // Add the Reference object to the Signature object. XMLSignature.SignedInfo.AddReference(reference); // Add an RSAKeyValue KeyInfo (optional; helps recipient find key to validate). KeyInfo keyInfo = new KeyInfo(); keyInfo.AddClause(new RSAKeyValue((RSA)Key)); // Add the KeyInfo object to the Reference object. XMLSignature.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 = new XmlTextWriter(XmlSigFileName, new UTF8Encoding(false)); xmlDigitalSignature.WriteTo(xmltw); xmltw.Close(); } // Verify the signature of an XML file and return the result. public static Boolean VerifyXmlFile(String Name) { // Check the arguments. if (Name == null) throw new ArgumentNullException("Name"); // Create a new XML document. XmlDocument xmlDocument = new 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 = new SignedXml(xmlDocument); // Find the "Signature" node and create a new // XmlNodeList object. XmlNodeList nodeList = xmlDocument.GetElementsByTagName("Signature"); // Load the signature node. signedXml.LoadXml((XmlElement)nodeList[0]); // Check the signature and return the result. return signedXml.CheckSignature(); } }
// // This example signs a URL using an // envelope signature. It then verifies the // signed XML. // #using <System.dll> #using <System.Xml.dll> #using <System.Security.dll> using namespace System; using namespace System::Security::Cryptography; using namespace System::Security::Cryptography::Xml; using namespace System::Text; using namespace System::Xml; namespace Sample { public ref class SignVerifyEnvelope { public: static void Work() { // Generate a signing key. RSACryptoServiceProvider^ key = gcnew RSACryptoServiceProvider(); try { // Sign the detached resource and save the // signature in an XML file. SignDetachedResource("http://www.microsoft.com" , "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."); } Console::ReadLine(); } catch (CryptographicException^ ex) { Console::WriteLine(ex->Message); } finally { // Clear resources associated with the // RSACryptoServiceProvider. key->Clear(); } } // Sign an XML file and save the signature in a new file. static void SignDetachedResource(String^ uri, String^ xmlFileName, RSA^ key) { // Check the arguments. if (uri->Length == 0) { throw gcnew ArgumentException("uri"); } if (xmlFileName->Length == 0) { throw gcnew ArgumentException("xmlFileName"); } if (key->KeySize == 0) { throw gcnew ArgumentException("key"); } // Create a SignedXml object. SignedXml^ signedXml = gcnew SignedXml(); // Assign the key to the SignedXml object. signedXml->SigningKey = key; // Get the signature object from the SignedXml object. Signature^ xmlSignature = signedXml->Signature; // Create a reference to be signed. Reference^ reference = gcnew Reference(); // Add the passed URI to the reference object. reference->Uri = uri; // Add the Reference object to the Signature object. xmlSignature->SignedInfo->AddReference(reference); // Add an RSAKeyValue KeyInfo (optional; helps recipient // find key to validate). KeyInfo^ keyInfo = gcnew KeyInfo(); keyInfo->AddClause( gcnew RSAKeyValue(key)); // Add the KeyInfo object to the Reference object. xmlSignature->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^ xmlTextWriter = gcnew XmlTextWriter( xmlFileName, gcnew UTF8Encoding(false)); xmlDigitalSignature->WriteTo(xmlTextWriter); xmlTextWriter->Close(); } // Verify the signature of an XML file and return the result. static Boolean VerifyXmlFile(String^ documentName) { // Check the arguments. if (documentName->Length == 0) { throw gcnew ArgumentException("documentName"); } // 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(documentName); // 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( (XmlElement^) nodeList->Item(0)); // Check the signature and return the result. return signedXml->CheckSignature(); } }; } int main() { Sample::SignVerifyEnvelope::Work(); }
エンベロープ シグネチャを使用して XML ドキュメントの単一の要素について署名および検証を行うコードの例を次に示します。
' This example signs an XML file using an ' envelope signature. It then verifies the ' signed XML. ' Imports System Imports System.Security.Cryptography Imports System.Security.Cryptography.Xml Imports System.Text Imports System.Xml Module SignVerifyEnvelope Sub Main(ByVal args() As String) ' Generate a signing key. Dim Key As New RSACryptoServiceProvider() Try ' Specify an element to sign. Dim elements As String() = New String() {"#tag1"} ' Sign an XML file and save the signature to a ' new file. SignXmlFile("Test.xml", "SignedExample.xml", Key, elements) Console.WriteLine("XML file signed.") ' Verify the signature of the signed XML. Console.WriteLine("Verifying signature...") Dim result As Boolean = VerifyXmlFile("SignedExample.xml") ' Display the results of the signature verification to \ ' the console. If result Then Console.WriteLine("The XML signature is valid.") Else Console.WriteLine("The XML signature is not valid.") End If Catch e As CryptographicException Console.WriteLine(e.Message) Finally ' Clear resources associated with the ' RSACryptoServiceProvider. Key.Clear() End Try End Sub ' Sign an XML file and save the signature in a new file. Sub SignXmlFile(ByVal FileName As String, ByVal SignedFileName As String, ByVal Key As RSA, ByVal ElementsToSign() As String) ' Check the arguments. If FileName Is Nothing Then Throw New ArgumentNullException("FileName") End If If SignedFileName Is Nothing Then Throw New ArgumentNullException("SignedFileName") End If If Key Is Nothing Then Throw New ArgumentNullException("Key") End If If ElementsToSign Is Nothing Then Throw New ArgumentNullException("ElementsToSign") End If ' Create a new XML document. Dim doc As New XmlDocument() ' Format the document to ignore white spaces. doc.PreserveWhitespace = False ' Load the passed XML file using it's name. doc.Load(New XmlTextReader(FileName)) ' Create a SignedXml object. Dim signedXml As New SignedXml(doc) ' Add the key to the SignedXml document. signedXml.SigningKey = Key ' Loop through each passed element to sign ' and create a reference. Dim s As String For Each s In ElementsToSign ' Create a reference to be signed. Dim reference As New Reference() reference.Uri = s ' Add an enveloped transformation to the reference. Dim env As New XmlDsigEnvelopedSignatureTransform() reference.AddTransform(env) ' Add the reference to the SignedXml object. signedXml.AddReference(reference) Next s ' Add an RSAKeyValue KeyInfo (optional; helps recipient find key to validate). Dim keyInfo As New KeyInfo() keyInfo.AddClause(New RSAKeyValue(CType(Key, RSA))) signedXml.KeyInfo = keyInfo ' Compute the signature. signedXml.ComputeSignature() ' Get the XML representation of the signature and save ' it to an XmlElement object. Dim xmlDigitalSignature As XmlElement = signedXml.GetXml() ' Append the element to the XML document. doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, True)) If TypeOf doc.FirstChild Is XmlDeclaration Then doc.RemoveChild(doc.FirstChild) End If ' Save the signed XML document to a file specified ' using the passed string. Dim xmltw As New XmlTextWriter(SignedFileName, New UTF8Encoding(False)) doc.WriteTo(xmltw) xmltw.Close() End Sub ' Verify the signature of an XML file and return the result. Function VerifyXmlFile(ByVal Name As String) As [Boolean] ' Check the arguments. If Name Is Nothing Then Throw New ArgumentNullException("Name") End If ' Create a new XML document. Dim xmlDocument As New 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. Dim signedXml As New SignedXml(xmlDocument) ' Find the "Signature" node and create a new ' XmlNodeList object. Dim nodeList As XmlNodeList = xmlDocument.GetElementsByTagName("Signature") ' Load the signature node. signedXml.LoadXml(CType(nodeList(0), XmlElement)) ' Check the signature and return the result. Return signedXml.CheckSignature() End Function End Module
// // This example signs an XML file using an // envelope signature. It then verifies the // signed XML. // using System; using System.Security.Cryptography; using System.Security.Cryptography.Xml; using System.Text; using System.Xml; public class SignVerifyEnvelope { public static void Main(String[] args) { // Generate a signing key. RSACryptoServiceProvider Key = new RSACryptoServiceProvider(); try { // Specify an element to sign. string[] elements = { "#tag1" }; // Sign an XML file and save the signature to a // new file. SignXmlFile("Test.xml", "SignedExample.xml", Key, elements); 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); } finally { // Clear resources associated with the // RSACryptoServiceProvider. Key.Clear(); } } // Sign an XML file and save the signature in a new file. public static void SignXmlFile(string FileName, string SignedFileName, RSA Key, string[] ElementsToSign) { // Check the arguments. if (FileName == null) throw new ArgumentNullException("FileName"); if (SignedFileName == null) throw new ArgumentNullException("SignedFileName"); if (Key == null) throw new ArgumentNullException("Key"); if (ElementsToSign == null) throw new ArgumentNullException("ElementsToSign"); // Create a new XML document. XmlDocument doc = new XmlDocument(); // Format the document to ignore white spaces. doc.PreserveWhitespace = false; // Load the passed XML file using it's name. doc.Load(new XmlTextReader(FileName)); // Create a SignedXml object. SignedXml signedXml = new SignedXml(doc); // Add the key to the SignedXml document. signedXml.SigningKey = Key; // Loop through each passed element to sign // and create a reference. foreach (string s in ElementsToSign) { // Create a reference to be signed. Reference reference = new Reference(); reference.Uri = s; // Add an enveloped transformation to the reference. XmlDsigEnvelopedSignatureTransform env = new 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 = new KeyInfo(); keyInfo.AddClause(new RSAKeyValue((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 is XmlDeclaration) { doc.RemoveChild(doc.FirstChild); } // Save the signed XML document to a file specified // using the passed string. XmlTextWriter xmltw = new XmlTextWriter(SignedFileName, new UTF8Encoding(false)); doc.WriteTo(xmltw); xmltw.Close(); } // Verify the signature of an XML file and return the result. public static Boolean VerifyXmlFile(String Name) { // Check the arguments. if (Name == null) throw new ArgumentNullException("Name"); // Create a new XML document. XmlDocument xmlDocument = new 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 = new SignedXml(xmlDocument); // Find the "Signature" node and create a new // XmlNodeList object. XmlNodeList nodeList = xmlDocument.GetElementsByTagName("Signature"); // Load the signature node. signedXml.LoadXml((XmlElement)nodeList[0]); // Check the signature and return the result. return signedXml.CheckSignature(); } }
// // This example signs an XML file using an // envelope signature. It then verifies the // signed XML. // #using <System.Xml.dll> #using <System.Security.dll> #using <System.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. static void SignXmlFile( String^ FileName, String^ SignedFileName, RSA^ Key, array<String^>^ElementsToSign ) { // Check the arguments. if ( FileName == nullptr ) throw gcnew ArgumentNullException( L"FileName" ); if ( SignedFileName == nullptr ) throw gcnew ArgumentNullException( L"SignedFileName" ); if ( Key == nullptr ) throw gcnew ArgumentNullException( L"Key" ); if ( ElementsToSign == nullptr ) throw gcnew ArgumentNullException( L"ElementsToSign" ); // 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 it's 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; // Loop through each passed element to sign // and create a reference. System::Collections::IEnumerator^ myEnum = ElementsToSign->GetEnumerator(); while ( myEnum->MoveNext() ) { String^ s = safe_cast<String^>(myEnum->Current); // Create a reference to be signed. Reference^ reference = gcnew Reference; reference->Uri = s; // 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( dynamic_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 ( dynamic_cast<XmlDeclaration^>(doc->FirstChild) ) { 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. static Boolean VerifyXmlFile( String^ Name ) { // Check the arguments. if ( Name == nullptr ) throw gcnew ArgumentNullException( L"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( L"Signature" ); // Load the signature node. signedXml->LoadXml( dynamic_cast<XmlElement^>(nodeList->Item( 0 )) ); // Check the signature and return the result. return signedXml->CheckSignature(); } int main() { // Generate a signing key. RSACryptoServiceProvider^ Key = gcnew RSACryptoServiceProvider; try { // Specify an element to sign. array<String^>^elements = {L"#tag1"}; // Sign an XML file and save the signature to a // new file. SignXmlFile( L"Test.xml", L"SignedExample.xml", Key, elements ); Console::WriteLine( L"XML file signed." ); // Verify the signature of the signed XML. Console::WriteLine( L"Verifying signature..." ); bool result = VerifyXmlFile( L"SignedExample.xml" ); // Display the results of the signature verification to // the console. if ( result ) { Console::WriteLine( L"The XML signature is valid." ); } else { Console::WriteLine( L"The XML signature is not valid." ); } } catch ( CryptographicException^ e ) { Console::WriteLine( e->Message ); } finally { // Clear resources associated with the // RSACryptoServiceProvider. Key->Clear(); } return 1; }

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
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。


SignedXml コンストラクタ (XmlElement)
アセンブリ: System.Security (system.security.dll 内)



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
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。


SignedXml コンストラクタ

名前 | 説明 |
---|---|
SignedXml () | SignedXml クラスの新しいインスタンスを初期化します。 |
SignedXml (XmlDocument) | 指定した XML ドキュメントから SignedXml クラスの新しいインスタンスを初期化します。 |
SignedXml (XmlElement) | 指定した XmlElement オブジェクトから SignedXml クラスの新しいインスタンスを初期化します。 |

SignedXml フィールド


名前 | 説明 | |
---|---|---|
![]() | m_signature | 現在の SignedXml オブジェクトの Signature オブジェクトを表します。 |
![]() | m_strSigningKeyName | SignedXml オブジェクトに署名するための、インストールされているキーの名前を表します。 |

SignedXml プロパティ

名前 | 説明 | |
---|---|---|
![]() | EncryptedXml | XML 暗号化処理規則を定義する EncryptedXml オブジェクトを取得または設定します。 |
![]() | KeyInfo | 現在の SignedXml オブジェクトの KeyInfo オブジェクトを取得または設定します。 |
![]() | Resolver | 現在の XmlResolver オブジェクトを設定します。 |
![]() | Signature | 現在の SignedXml オブジェクトの Signature オブジェクトを取得します。 |
![]() | SignatureLength | 現在の SignedXml オブジェクトの署名の長さを取得します。 |
![]() | SignatureMethod | 現在の SignedXml オブジェクトの署名メソッドを取得します。 |
![]() | SignatureValue | 現在の SignedXml オブジェクトの署名値を取得します。 |
![]() | SignedInfo | 現在の SignedXml オブジェクトの SignedInfo オブジェクトを取得します。 |
![]() | SigningKey | SignedXml オブジェクトに署名するために使用する非対称アルゴリズム キーを取得または設定します。 |
![]() | SigningKeyName | SignedXml オブジェクトに署名するための、インストールされているキーの名前を取得または設定します。 |

SignedXml メソッド

名前 | 説明 | |
---|---|---|
![]() | AddObject | 署名されるオブジェクトのリストに DataObject オブジェクトを追加します。 |
![]() | AddReference | Reference オブジェクトを、XML デジタル署名の作成に使用するダイジェスト メソッド、ダイジェスト値、および変換を記述する SignedXml オブジェクトに追加します。 |
![]() | CheckSignature | オーバーロードされます。 Signature プロパティが検証するかどうかを判断します。 |
![]() | CheckSignatureReturningKey | Signature プロパティが署名内の公開キーを使用して検証するかどうかを判断します。 |
![]() | ComputeSignature | オーバーロードされます。 XML デジタル署名を計算します。 |
![]() | Equals | オーバーロードされます。 2 つの Object インスタンスが等しいかどうかを判断します。 ( Object から継承されます。) |
![]() | GetHashCode | 特定の型のハッシュ関数として機能します。GetHashCode は、ハッシュ アルゴリズムや、ハッシュ テーブルのようなデータ構造での使用に適しています。 ( Object から継承されます。) |
![]() | GetIdElement | 指定した XmlDocument オブジェクトから、指定した ID の XmlElement オブジェクトを返します。 |
![]() | GetType | 現在のインスタンスの Type を取得します。 ( Object から継承されます。) |
![]() | GetXml | SignedXml オブジェクトの XML 表現を返します。 |
![]() | LoadXml | XML 要素から SignedXml の状態を読み込みます。 |
![]() | ReferenceEquals | 指定した複数の Object インスタンスが同一かどうかを判断します。 ( Object から継承されます。) |
![]() | ToString | 現在の Object を表す String を返します。 ( Object から継承されます。) |

名前 | 説明 | |
---|---|---|
![]() | Finalize | Object がガベージ コレクションにより収集される前に、その Object がリソースを解放し、その他のクリーンアップ操作を実行できるようにします。 ( Object から継承されます。) |
![]() | GetPublicKey | 署名の公開キーを返します。 |
![]() | MemberwiseClone | 現在の Object の簡易コピーを作成します。 ( Object から継承されます。) |

SignedXml メンバ
コア XML 署名オブジェクトにラッパーを提供し、XML 署名の作成を簡単にします。
SignedXml データ型で公開されるメンバを以下の表に示します。



名前 | 説明 | |
---|---|---|
![]() | m_signature | 現在の SignedXml オブジェクトの Signature オブジェクトを表します。 |
![]() | m_strSigningKeyName | SignedXml オブジェクトに署名するための、インストールされているキーの名前を表します。 |

名前 | 説明 | |
---|---|---|
![]() | EncryptedXml | XML 暗号化処理規則を定義する EncryptedXml オブジェクトを取得または設定します。 |
![]() | KeyInfo | 現在の SignedXml オブジェクトの KeyInfo オブジェクトを取得または設定します。 |
![]() | Resolver | 現在の XmlResolver オブジェクトを設定します。 |
![]() | Signature | 現在の SignedXml オブジェクトの Signature オブジェクトを取得します。 |
![]() | SignatureLength | 現在の SignedXml オブジェクトの署名の長さを取得します。 |
![]() | SignatureMethod | 現在の SignedXml オブジェクトの署名メソッドを取得します。 |
![]() | SignatureValue | 現在の SignedXml オブジェクトの署名値を取得します。 |
![]() | SignedInfo | 現在の SignedXml オブジェクトの SignedInfo オブジェクトを取得します。 |
![]() | SigningKey | SignedXml オブジェクトに署名するために使用する非対称アルゴリズム キーを取得または設定します。 |
![]() | SigningKeyName | SignedXml オブジェクトに署名するための、インストールされているキーの名前を取得または設定します。 |

名前 | 説明 | |
---|---|---|
![]() | AddObject | 署名されるオブジェクトのリストに DataObject オブジェクトを追加します。 |
![]() | AddReference | Reference オブジェクトを、XML デジタル署名の作成に使用するダイジェスト メソッド、ダイジェスト値、および変換を記述する SignedXml オブジェクトに追加します。 |
![]() | CheckSignature | オーバーロードされます。 Signature プロパティが検証するかどうかを判断します。 |
![]() | CheckSignatureReturningKey | Signature プロパティが署名内の公開キーを使用して検証するかどうかを判断します。 |
![]() | ComputeSignature | オーバーロードされます。 XML デジタル署名を計算します。 |
![]() | Equals | オーバーロードされます。 2 つの Object インスタンスが等しいかどうかを判断します。 (Object から継承されます。) |
![]() | GetHashCode | 特定の型のハッシュ関数として機能します。GetHashCode は、ハッシュ アルゴリズムや、ハッシュ テーブルのようなデータ構造での使用に適しています。 (Object から継承されます。) |
![]() | GetIdElement | 指定した XmlDocument オブジェクトから、指定した ID の XmlElement オブジェクトを返します。 |
![]() | GetType | 現在のインスタンスの Type を取得します。 (Object から継承されます。) |
![]() | GetXml | SignedXml オブジェクトの XML 表現を返します。 |
![]() | LoadXml | XML 要素から SignedXml の状態を読み込みます。 |
![]() | ReferenceEquals | 指定した複数の Object インスタンスが同一かどうかを判断します。 (Object から継承されます。) |
![]() | ToString | 現在の Object を表す String を返します。 (Object から継承されます。) |

名前 | 説明 | |
---|---|---|
![]() | Finalize | Object がガベージ コレクションにより収集される前に、その Object がリソースを解放し、その他のクリーンアップ操作を実行できるようにします。 (Object から継承されます。) |
![]() | GetPublicKey | 署名の公開キーを返します。 |
![]() | MemberwiseClone | 現在の Object の簡易コピーを作成します。 (Object から継承されます。) |

- SignedXmlのページへのリンク