Nota
L'accesso a questa pagina richiede l'autorizzazione. È possibile provare ad accedere o modificare le directory.
L'accesso a questa pagina richiede l'autorizzazione. È possibile provare a modificare le directory.
È possibile utilizzare le classi nello System.Security.Cryptography.Xml spazio dei nomi per firmare un documento XML o parte di un documento XML con una firma digitale. Le firme digitali XML (XMLDSIG) consentono di verificare che i dati non siano stati modificati dopo la firma. Per altre informazioni sullo standard XMLDSIG, vedere la raccomandazione W3C (World Wide Web Consortium) sulla sintassi e l'elaborazione delle firme XML.
Annotazioni
Il codice in questo articolo si applica a Windows.
Nell'esempio di codice di questa procedura viene illustrato come firmare digitalmente un intero documento XML e allegare la firma al documento in un <Signature> elemento . Nell'esempio viene creata una chiave di firma RSA, la chiave viene aggiunta a un contenitore di chiavi protette e quindi viene usata la chiave per firmare digitalmente un documento XML. È quindi possibile recuperare la chiave per verificare la firma digitale XML oppure per firmare un altro documento XML.
Per informazioni su come verificare una firma digitale XML creata utilizzando questa procedura, vedere Procedura: Verificare le firme digitali dei documenti XML.
Per firmare digitalmente un documento XML
Creare un CspParameters oggetto e specificare il nome del contenitore di chiavi.
CspParameters cspParams = new() { KeyContainerName = "XML_DSIG_RSA_KEY" };Dim cspParams As New CspParameters With { .KeyContainerName = "XML_DSIG_RSA_KEY" }Generare una chiave asimmetrica usando la RSACryptoServiceProvider classe . La chiave viene salvata automaticamente nel contenitore di chiavi quando si passa l'oggetto CspParameters al costruttore della RSACryptoServiceProvider classe . Questa chiave verrà utilizzata per firmare il documento XML.
RSACryptoServiceProvider rsaKey = new(cspParams);Dim rsaKey As New RSACryptoServiceProvider(cspParams)Creare un XmlDocument oggetto caricando un file XML dal disco. L'oggetto XmlDocument contiene l'elemento XML da crittografare.
XmlDocument xmlDoc = new() { // Load an XML file into the XmlDocument object. PreserveWhitespace = true }; xmlDoc.Load("test.xml");' Load an XML file into the XmlDocument object. Dim xmlDoc As New XmlDocument With { .PreserveWhitespace = True } xmlDoc.Load("test.xml")Creare un nuovo SignedXml oggetto e passarvi l'oggetto XmlDocument .
SignedXml signedXml = new(xmlDoc) {Dim signedXml As New SignedXml(xmlDoc)Aggiungere la chiave RSA di firma all'oggetto SignedXml .
SigningKey = rsaKey };signedXml.SigningKey = rsaKeyCreare un Reference oggetto che descrive cosa firmare. Per firmare l'intero documento, impostare la Uri proprietà su
"".// Create a reference to be signed. Reference reference = new() { Uri = "" };' Create a reference to be signed. Dim reference As New Reference() reference.Uri = ""Aggiungere un XmlDsigEnvelopedSignatureTransform oggetto all'oggetto Reference . Una trasformazione consente al verificatore di rappresentare i dati XML nello stesso modo usato dal firmatario. I dati XML possono essere rappresentati in modi diversi, pertanto questo passaggio è fondamentale per la verifica.
XmlDsigEnvelopedSignatureTransform env = new(); reference.AddTransform(env);Dim env As New XmlDsigEnvelopedSignatureTransform() reference.AddTransform(env)Aggiungere l'oggetto Reference all'oggetto SignedXml .
signedXml.AddReference(reference);signedXml.AddReference(reference)Calcolare la firma chiamando il ComputeSignature metodo .
signedXml.ComputeSignature();signedXml.ComputeSignature()Recuperare la rappresentazione XML della firma (un <
Signature> elemento) e salvarla in un nuovo XmlElement oggetto .XmlElement xmlDigitalSignature = signedXml.GetXml();Dim xmlDigitalSignature As XmlElement = signedXml.GetXml()Aggiungere l'elemento all'oggetto XmlDocument .
xmlDoc.DocumentElement?.AppendChild(xmlDoc.ImportNode(xmlDigitalSignature, true));xmlDoc.DocumentElement.AppendChild(xmlDoc.ImportNode(xmlDigitalSignature, True))Salvare il documento.
xmlDoc.Save("test.xml");xmlDoc.Save("test.xml")
Esempio
In questo esempio si presuppone che esista un file denominato test.xml nella stessa directory del programma compilato. È possibile inserire il codice XML seguente in un file denominato test.xml e usarlo con questo esempio.
<root>
<creditcard>
<number>19834209</number>
<expiry>02/02/2002</expiry>
</creditcard>
</root>
using System;
using System.Runtime.Versioning;
using System.Security.Cryptography;
using System.Security.Cryptography.Xml;
using System.Xml;
[SupportedOSPlatform("Windows")]
public class SignXML
{
public static void Main(String[] args)
{
try
{
// Create a new CspParameters object to specify
// a key container.
CspParameters cspParams = new()
{
KeyContainerName = "XML_DSIG_RSA_KEY"
};
// Create a new RSA signing key and save it in the container.
RSACryptoServiceProvider rsaKey = new(cspParams);
// Create a new XML document.
XmlDocument xmlDoc = new()
{
// Load an XML file into the XmlDocument object.
PreserveWhitespace = true
};
xmlDoc.Load("test.xml");
// Sign the XML document.
SignXml(xmlDoc, rsaKey);
Console.WriteLine("XML file signed.");
// Save the document.
xmlDoc.Save("test.xml");
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
// Sign an XML file.
// This document cannot be verified unless the verifying
// code has the key with which it was signed.
public static void SignXml(XmlDocument xmlDoc, RSA rsaKey)
{
// Check arguments.
if (xmlDoc == null)
throw new ArgumentException(null, nameof(xmlDoc));
if (rsaKey == null)
throw new ArgumentException(null, nameof(rsaKey));
// Create a SignedXml object.
SignedXml signedXml = new(xmlDoc)
{
// Add the key to the SignedXml document.
SigningKey = rsaKey
};
// Create a reference to be signed.
Reference reference = new()
{
Uri = ""
};
// Add an enveloped transformation to the reference.
XmlDsigEnvelopedSignatureTransform env = new();
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.
xmlDoc.DocumentElement?.AppendChild(xmlDoc.ImportNode(xmlDigitalSignature, true));
}
}
Imports System.Security.Cryptography
Imports System.Security.Cryptography.Xml
Imports System.Xml
Module SignXML
Sub Main(ByVal args() As String)
Try
' Create a new CspParameters object to specify
' a key container.
Dim cspParams As New CspParameters With {
.KeyContainerName = "XML_DSIG_RSA_KEY"
}
' Create a new RSA signing key and save it in the container.
Dim rsaKey As New RSACryptoServiceProvider(cspParams)
' Create a new XML document.
' Load an XML file into the XmlDocument object.
Dim xmlDoc As New XmlDocument With {
.PreserveWhitespace = True
}
xmlDoc.Load("test.xml")
' Sign the XML document.
SignXml(xmlDoc, rsaKey)
Console.WriteLine("XML file signed.")
' Save the document.
xmlDoc.Save("test.xml")
Catch e As Exception
Console.WriteLine(e.Message)
End Try
End Sub
' Sign an XML file.
' This document cannot be verified unless the verifying
' code has the key with which it was signed.
Sub SignXml(ByVal xmlDoc As XmlDocument, ByVal rsaKey As RSA)
' Check arguments.
If xmlDoc Is Nothing Then
Throw New ArgumentException(
"The XML doc cannot be nothing.", NameOf(xmlDoc))
End If
If rsaKey Is Nothing Then
Throw New ArgumentException(
"The RSA key cannot be nothing.", NameOf(rsaKey))
End If
' Create a SignedXml object.
Dim signedXml As New SignedXml(xmlDoc)
' Add the key to the SignedXml document.
signedXml.SigningKey = rsaKey
' 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.
xmlDoc.DocumentElement.AppendChild(xmlDoc.ImportNode(xmlDigitalSignature, True))
End Sub
End Module
Compilazione del codice
In un progetto destinato a .NET Framework includere un riferimento a
System.Security.dll.In un progetto destinato a .NET Core o .NET 5 installare il pacchetto NuGet System.Security.Cryptography.Xml.
Includere gli spazi dei nomi seguenti: System.Xml, System.Security.Cryptographye System.Security.Cryptography.Xml.
Sicurezza .NET
Non archiviare o trasferire mai la chiave privata di una coppia di chiavi asimmetriche in testo non crittografato. Per altre informazioni sulle chiavi crittografiche simmetriche e asimmetriche, vedere Generazione di chiavi per crittografia e decrittografia.
Non incorporare mai una chiave privata direttamente nel codice sorgente. I tasti incorporati possono essere facilmente letti da un assembly usando il Ildasm.exe (Disassembler IL) o aprendo l'assembly in un editor di testo, ad esempio Blocco note.