SignedXml Classe
Definição
Importante
Algumas informações se referem a produtos de pré-lançamento que podem ser substancialmente modificados antes do lançamento. A Microsoft não oferece garantias, expressas ou implícitas, das informações aqui fornecidas.
Fornece um wrapper em um objeto de assinatura XML principal para facilitar a criação de assinaturas XML.
public ref class SignedXml
public class SignedXml
type SignedXml = class
Public Class SignedXml
- Herança
-
SignedXml
Exemplos
O exemplo de código a seguir mostra como assinar e verificar um documento XML inteiro usando uma assinatura enveloped.
//
// 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.
RSA Key = RSA.Create();
// 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 asymmetric
// 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.
'
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 RSA = RSA.Create()
' 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 asymmetric
' 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
O exemplo de código a seguir mostra como assinar e verificar um único elemento de um documento XML usando uma assinatura de codificação.
//
// 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.
RSA Key = RSA.Create();
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
// RSA instance.
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.
'
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 RSA = RSA.Create()
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
' RSA instance.
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
Comentários
Para obter mais informações sobre essa API, consulte comentários da API Complementar para SignedXml.
Construtores
| Nome | Description |
|---|---|
| SignedXml() |
Inicializa uma nova instância da classe SignedXml. |
| SignedXml(XmlDocument) |
Inicializa uma nova instância da classe do SignedXml documento XML especificado. |
| SignedXml(XmlElement) |
Inicializa uma nova instância da classe do SignedXml objeto especificado XmlElement . |
Campos
| Nome | Description |
|---|---|
| m_signature | |
| m_strSigningKeyName |
Representa o nome da chave instalada a ser usada para assinar o SignedXml objeto. |
| XmlDecryptionTransformUrl |
Representa o URI (Uniform Resource Identifier) para a transformação de descriptografia do modo XML. Esse campo é constante. |
| XmlDsigBase64TransformUrl |
Representa o URI (Uniform Resource Identifier) para a transformação base 64. Esse campo é constante. |
| XmlDsigC14NTransformUrl |
Representa o URI (Uniform Resource Identifier) para a transformação XML canônica. Esse campo é constante. |
| XmlDsigC14NWithCommentsTransformUrl |
Representa o URI (Uniform Resource Identifier) para a transformação XML canônica, com comentários. Esse campo é constante. |
| XmlDsigCanonicalizationUrl |
Representa o URI (Uniform Resource Identifier) para o algoritmo de canonicalização padrão para assinaturas digitais XML. Esse campo é constante. |
| XmlDsigCanonicalizationWithCommentsUrl |
Representa o URI (Uniform Resource Identifier) para o algoritmo de canonicalização padrão para assinaturas digitais XML e inclui comentários. Esse campo é constante. |
| XmlDsigDSAUrl |
Representa o URI (Uniform Resource Identifier) para o algoritmo padrão DSA para assinaturas digitais XML. Esse campo é constante. |
| XmlDsigEnvelopedSignatureTransformUrl |
Representa o URI (Uniform Resource Identifier) para a transformação de assinatura enveloped. Esse campo é constante. |
| XmlDsigExcC14NTransformUrl |
Representa o URI (Uniform Resource Identifier) para canonização exclusiva de XML. Esse campo é constante. |
| XmlDsigExcC14NWithCommentsTransformUrl |
Representa o URI (Uniform Resource Identifier) para canonização exclusiva de XML, com comentários. Esse campo é constante. |
| XmlDsigHMACSHA1Url |
Representa o URI (Uniform Resource Identifier) para o algoritmo padrão HMACSHA1 para assinaturas digitais XML. Esse campo é constante. |
| XmlDsigMinimalCanonicalizationUrl |
Representa o URI (Uniform Resource Identifier) para o algoritmo de canonicalização mínimo padrão para assinaturas digitais XML. Esse campo é constante. |
| XmlDsigNamespaceUrl |
Representa o URI (Uniform Resource Identifier) para o namespace padrão para assinaturas digitais XML. Esse campo é constante. |
| XmlDsigRSASHA1Url |
Representa o URI (Uniform Resource Identifier) para o método de assinatura padrão RSA para assinaturas digitais XML. Esse campo é constante. |
| XmlDsigRSASHA256Url |
Representa o URI (Uniform Resource Identifier) para a variação do RSA método de assinatura SHA-256 para assinaturas digitais XML. Esse campo é constante. |
| XmlDsigRSASHA384Url |
Representa o URI (Uniform Resource Identifier) para a variação do RSA método de assinatura SHA-384 para assinaturas digitais XML. Esse campo é constante. |
| XmlDsigRSASHA512Url |
Representa o URI (Uniform Resource Identifier) para a variação do RSA método de assinatura SHA-512 para assinaturas digitais XML. Esse campo é constante. |
| XmlDsigSHA1Url |
Representa o URI (Uniform Resource Identifier) para o método de resumo padrão SHA1 para assinaturas digitais XML. Esse campo é constante. |
| XmlDsigSHA256Url |
Representa o URI (Uniform Resource Identifier) para o método de resumo padrão SHA256 para assinaturas digitais XML. Esse campo é constante. |
| XmlDsigSHA384Url |
Representa o URI (Uniform Resource Identifier) para o método de resumo padrão SHA384 para assinaturas digitais XML. Esse campo é constante. |
| XmlDsigSHA512Url |
Representa o URI (Uniform Resource Identifier) para o método de resumo padrão SHA512 para assinaturas digitais XML. Esse campo é constante. |
| XmlDsigXPathTransformUrl |
Representa o URI (Uniform Resource Identifier) para a XPath (Linguagem de Caminho XML). Esse campo é constante. |
| XmlDsigXsltTransformUrl |
Representa o URI (Uniform Resource Identifier) para transformações XSLT. Esse campo é constante. |
| XmlLicenseTransformUrl |
Representa o URI (Uniform Resource Identifier) para o algoritmo de transformação de licença usado para normalizar licenças XrML para assinaturas. |
Propriedades
| Nome | Description |
|---|---|
| EncryptedXml |
Obtém ou define um EncryptedXml objeto que define as regras de processamento de criptografia XML. |
| KeyInfo |
Obtém ou define o KeyInfo objeto do objeto atual SignedXml . |
| Resolver |
Define o objeto atual XmlResolver . |
| SafeCanonicalizationMethods |
Obtém os nomes dos métodos cujos algoritmos de canonicalização são explicitamente permitidos. |
| Signature | |
| SignatureFormatValidator |
Obtém um delegado que será chamado para validar o formato (não a segurança criptográfica) de uma assinatura XML. |
| SignatureLength |
Obtém o comprimento da assinatura do objeto atual SignedXml . |
| SignatureMethod |
Obtém o método de assinatura do objeto atual SignedXml . |
| SignatureValue |
Obtém o valor de assinatura do objeto atual SignedXml . |
| SignedInfo |
Obtém o SignedInfo objeto do objeto atual SignedXml . |
| SigningKey |
Obtém ou define a chave de algoritmo assimétrica usada para assinar um SignedXml objeto. |
| SigningKeyName |
Obtém ou define o nome da chave instalada a ser usada para assinar o SignedXml objeto. |
Métodos
| Nome | Description |
|---|---|
| AddObject(DataObject) |
Adiciona um DataObject objeto à lista de objetos a serem assinados. |
| AddReference(Reference) |
Adiciona um Reference objeto ao SignedXml objeto que descreve um método digest, valor digest e transformação a ser usado para criar uma assinatura digital XML. |
| CheckSignature() |
Determina se a Signature propriedade verifica o uso da chave pública na assinatura. |
| CheckSignature(AsymmetricAlgorithm) |
Determina se a Signature propriedade verifica a chave especificada. |
| CheckSignature(KeyedHashAlgorithm) |
Determina se a Signature propriedade verifica o algoritmo mac (código de autenticação de mensagem) especificado. |
| CheckSignature(X509Certificate2, Boolean) |
Determina se a Signature propriedade verifica se o objeto especificado X509Certificate2 e, opcionalmente, se o certificado é válido. |
| CheckSignatureReturningKey(AsymmetricAlgorithm) |
Determina se a Signature propriedade verifica o uso da chave pública na assinatura. |
| ComputeSignature() |
Calcula uma assinatura digital XML. |
| ComputeSignature(KeyedHashAlgorithm) |
Calcula uma assinatura digital XML usando o algoritmo mac (código de autenticação de mensagem) especificado. |
| Equals(Object) |
Determina se o objeto especificado é igual ao objeto atual. (Herdado de Object) |
| GetHashCode() |
Serve como a função hash predefinida. (Herdado de Object) |
| GetIdElement(XmlDocument, String) |
Retorna o XmlElement objeto com a ID especificada do objeto especificado XmlDocument . |
| GetPublicKey() |
Retorna a chave pública de uma assinatura. |
| GetType() |
Obtém o Type da instância atual. (Herdado de Object) |
| GetXml() |
Retorna a representação XML de um SignedXml objeto. |
| LoadXml(XmlElement) |
Carrega um SignedXml estado de um elemento XML. |
| MemberwiseClone() |
Cria uma cópia superficial do Objectatual. (Herdado de Object) |
| ToString() |
Retorna uma cadeia de caracteres que representa o objeto atual. (Herdado de Object) |