Example of XML signature

XML

X509Store xstore = new X509Store(StoreName.My, StoreLocation.CurrentUser);
xstore.Open(OpenFlags.MaxAllowed);
X509Certificate2Collection col = xstore.Certificates.Find(X509FindType.FindByThumbprint, "fb8e88e3814a489d56cb367abd60f61a85251a52", false);

XmlDocument doc = new XmlDocument();

// Load the passed XML file using its name.
doc.LoadXml("");

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

// Add the key to the SignedXml document. 
signedXml.SigningKey = col[0].GetRSAPrivateKey();

// 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);
}

Notice the GetRSAPrivateKey() function which replaces the direct PrivateKey property. PrivateKey is now deprecated and returns the CSP provider, while the new function (starting from .NET 4.6.2) returns the CNG or the CSP according to what is actually underndeath. Unfortunately there is no flag to force the property to do the same, so the old code has to be rewritten if you intend to use CNG.

Post a Comment

Previous Post Next Post