Skatteförvaltningens exempelkodsprogram (SignXmlNew)
Skatteförvaltningens exempelkodsprogram (SignXmlNew) – för att signera ett XML-meddelande för gränssnittet för certifikatförnyelse.
using System;
using System.IO;
using System.Security.Cryptography;
using System.Security.Cryptography.Xml;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Xml;
namespace SignXmlNew
{
class Program
{
static void Main(string[] args)
{
try
{
// Check command line parameters and, if necessary, throw an exception with usage instructions
if (args.Length != 3 ) throw new ArgumentException("Usage: xmlFile certPfxFile certPassword");
string xmlFile = args[0];
var certPfxFile = args[1];
var password = args[2];
XmlDocument doc = new XmlDocument();
doc.PreserveWhitespace = true;
doc.Load(xmlFile);
X509Certificate2 cert = new X509Certificate2(certPfxFile, password);
SignDocumentRsaSha256(doc, cert);
// Write the destination file that includes the Signature element
string destination = Path.GetFileNameWithoutExtension(xmlFile) + "_signed" + Path.GetExtension(xmlFile);
doc.Save(destination);
Console.WriteLine("OK, created: " + destination);
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex);
return;
}
}
///
/// Signs the given XmlDocument using RSA-SHA256 and the provided X509 certificate.
///
///The XmlDocument to be signed.
///The X509Certificate2, containing the private key for signing.
private static void SignDocumentRsaSha256(XmlDocument xmlDoc, X509Certificate2 cert)
{
var rsaKey = cert.GetRSAPrivateKey();
SignedXml signedXml = new SignedXml(xmlDoc);
signedXml.SignedInfo.CanonicalizationMethod = "http://www.w3.org/2001/10/xml-exc-c14n#";
signedXml.SigningKey = rsaKey;
Reference reference = new Reference();
reference.Uri = "";
XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();
reference.AddTransform(env);
signedXml.AddReference(reference);
var keyInfo = new KeyInfo();
keyInfo.AddClause(new KeyInfoX509Data(cert));
signedXml.KeyInfo = keyInfo;
signedXml.ComputeSignature();
XmlElement xmlDigitalSignature = signedXml.GetXml();
xmlDoc.DocumentElement.AppendChild(xmlDoc.ImportNode(xmlDigitalSignature, true));
}
}
}