// 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(); }
static void Main(string[] args) { if (args.Length != 4) { Console.WriteLine("Usage: cra.exe cert-file cert-password input-path output-path"); return; } String certFile = args[0]; String password = args[1]; String input = args[2]; String output = args[3]; X509Certificate2 cert = new X509Certificate2(certFile, password, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet); XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(input); var XmlToSign = new XmlDocument(); XmlToSign.LoadXml(xmlDoc.DocumentElement["Body"].OuterXml); SignedXml signedXml = new SignedXml(XmlToSign); signedXml.SigningKey = cert.PrivateKey; Reference reference = new Reference(); reference.Uri = ""; XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform(); reference.AddTransform(env); signedXml.AddReference(reference); signedXml.ComputeSignature(); XmlElement xmlDigitalSignature = signedXml.GetXml(); xmlDoc.DocumentElement["Body"].AppendChild(xmlDoc.ImportNode(xmlDigitalSignature, true)); xmlDoc.Save(output); }
public static XmlElement GetXmlSignature(this XmlDocument document, X509Certificate2 certificate) { if (document == null) { throw new ArgumentNullException(nameof(document)); } if (certificate == null) { throw new ArgumentNullException(nameof(certificate)); } if (certificate.HasPrivateKey == false) { throw new InvalidOperationException($"Certificate does not have private key. {certificate}"); } var key = certificate.GetRSAPrivateKey(); var signedXml = new SignedXml(document); signedXml.SigningKey = key; var XMLSignature = signedXml.Signature; // Create a reference to be signed. Pass "" to specify that all of the current XML document should be signed. var reference = new Reference(""); // Add an enveloped transformation to the reference. var 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). var 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. var xmlDigitalSignature = signedXml.GetXml(); return(xmlDigitalSignature); }
private void SignHeaderSmev() { Log(" подписание заголовка"); XmlDocument signNode = new XmlDocument(); signNode.InnerXml = Resources.SMEVHeader; // Создание подписчика XML-документа var signedXml = new GostSignedXml(file) { GetIdElementHandler = GetSmevIdElement }; // Установка ключа для создания подписи signedXml.SetSigningCertificate(certSP); // Ссылка на узел, который нужно подписать, с указанием алгоритма хэширования ГОСТ Р 34.11-94 (в соответствии с методическими рекомендациями СМЭВ) var dataReference = new Reference { Uri = "#body", DigestMethod = GostSignedXml.XmlDsigGost3411ObsoleteUrl }; // Метод преобразования, применяемый к данным перед их подписью (в соответствии с методическими рекомендациями СМЭВ) // dataReference.AddTransform(new XmlDsigEnvelopedSignatureTransform()); dataReference.AddTransform(new XmlDsigExcC14NTransform()); // Установка ссылки на узел signedXml.AddReference(dataReference); // Установка алгоритма нормализации узла SignedInfo (в соответствии с методическими рекомендациями СМЭВ) signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl; // Установка алгоритма подписи ГОСТ Р 34.10-2001 (в соответствии с методическими рекомендациями СМЭВ) signedXml.SignedInfo.SignatureMethod = GostSignedXml.XmlDsigGost3410ObsoleteUrl; // Вычисление подписи signedXml.ComputeSignature("ds"); // Получение XML-представления подписи var signatureXml = signedXml.GetXml("ds"); // Добавление подписи в исходный документ signNode.GetElementsByTagName("ds:SignedInfo")[0].ParentNode.RemoveChild(signNode.GetElementsByTagName("ds:SignedInfo")[0]); signNode.GetElementsByTagName("ds:SignatureValue")[0].InnerText = signatureXml.GetElementsByTagName("ds:SignatureValue")[0].InnerText; signNode.GetElementsByTagName("ds:Signature")[0].PrependChild(signNode.ImportNode(signatureXml.GetElementsByTagName("ds:SignedInfo")[0], true)); signNode.GetElementsByTagName("wsse:BinarySecurityToken")[0].InnerText = Convert.ToBase64String(certSP.RawData); file.DocumentElement.PrependChild(file.CreateElement(file.DocumentElement.Prefix, "Header", "http://schemas.xmlsoap.org/soap/envelope/")); file.GetElementsByTagName(file.DocumentElement.Prefix + ":Header")[0].PrependChild(file.ImportNode(signNode.GetElementsByTagName("wsse:Security")[0], true)); Log(VerifySmevRequestSignature(file) ? " подпись корректна" : " !подпись некорректна"); }
public void Sign() { var qualifyingProperties = GetQualifyingProperties(Certificate); var qualifyingPropertiesXml = ObjectToXml.Serialize(qualifyingProperties); var signedXml = new ExtendedSignedXml(Xml); signedXml.Signature.Id = qualifyingProperties.Target; signedXml.SigningKey = Certificate.GetRSAPrivateKey(); signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl; signedXml.SignedInfo.SignatureMethod = SignedXml.XmlDsigRSASHA256Url; var documentReference = new Reference { Id = qualifyingProperties.SignedProperties.SignedDataObjectProperties.DataObjectFormat.ObjectReference, Type = null, Uri = "" }; documentReference.AddTransform(new XmlDsigEnvelopedSignatureTransform()); documentReference.DigestMethod = SignedXml.XmlDsigSHA256Url; signedXml.AddReference(documentReference); var signedProperties = new Reference { Type = Namespaces.SignedProperties, Uri = "#" + qualifyingProperties.SignedProperties.Id }; signedProperties.AddTransform(new XmlDsigExcC14NTransform()); signedProperties.DigestMethod = SignedXml.XmlDsigSHA256Url; signedXml.AddReference(signedProperties); var dataObject = new DataObject { Data = qualifyingPropertiesXml.ChildNodes }; signedXml.AddObject(dataObject); var certificateKeyInfo = new KeyInfo(); certificateKeyInfo.AddClause(new KeyInfoX509Data(Certificate)); signedXml.KeyInfo = certificateKeyInfo; signedXml.ComputeSignature(); var signature = signedXml.GetXml(); Insert(signature, Xml.DocumentElement); }
public static void AppendSignatureToXMLDocument(this XmlDocument xmlDoc, String referenceURI, X509Certificate2 certificate) { var sig = new PrefixedSignedXML(xmlDoc) { SigningKey = certificate.PrivateKey }; var key = new RSACryptoServiceProvider(); // Add the key to the SignedXml xmlDocument. sig.SigningKey = key; // Create a reference to be signed. var reference = new Reference { Uri = "#" + referenceURI }; // Add an enveloped transformation to the reference. var env = new XmlDsigEnvelopedSignatureTransform(); reference.AddTransform(env); // Add the reference to the SignedXml object. sig.AddReference(reference); var path = Path.Combine(new DirectoryInfo(HttpContext.Current.Server.MapPath(@"~\")).Parent.FullName, "sign.crt"); var cert = X509Certificate2.CreateFromCertFile(path); // Add an RSAKeyValue KeyInfo (optional; helps recipient find key to validate). var keyInfo = new KeyInfo(); keyInfo.AddClause(new KeyInfoX509Data(cert)); sig.KeyInfo = keyInfo; // Compute the signature. sig.ComputeSignature(); var signature = sig.GetXml("ds"); var manager = new XmlNamespaceManager(xmlDoc.NameTable); manager.AddNamespace("ds", SignedXml.XmlDsigNamespaceUrl); manager.AddNamespace("saml", "urn:oasis:names:tc:SAML:2.0:assertion"); manager.AddNamespace("samlp", "urn:oasis:names:tc:SAML:2.0:protocol"); var node = xmlDoc.SelectSingleNode("/samlp:Response/saml:Assertion", manager); //var manager = new XmlNamespaceManager(xmlDoc.NameTable); //manager.AddNamespace("saml", SignedXml.XmlDsigNamespaceUrl); //var xmlResponse = xmlDoc.SelectSingleNode("saml:Assertion", manager); node.AppendChild(signature); }
//------------------------------------------------------------------------------------------- private string SignXML(string xml) { // Signing XML Documents: http://msdn.microsoft.com/en-us/library/ms229745.aspx var rsaKey = new RSACryptoServiceProvider(); string sales_licensekeys_privatekey = ConfigurationManager.AppSettings["sales_licensekeys_privatekey"]; if (!File.Exists(sales_licensekeys_privatekey)) { throw new Exception("The private signing key is missing"); } rsaKey.FromXmlString(System.IO.File.ReadAllText(sales_licensekeys_privatekey)); XmlDocument doc = new XmlDocument(); doc.PreserveWhitespace = true; doc.LoadXml(xml); SignedXml signedXml = new SignedXml(doc); signedXml.SigningKey = rsaKey; // Create a reference to be signed. Reference reference = new Reference(); reference.Uri = ""; // set to "" to sign the entire doc XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform(); reference.AddTransform(env); signedXml.AddReference(reference); signedXml.ComputeSignature(); XmlElement xmlDigitalSignature = signedXml.GetXml(); doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, true)); MemoryStream ms = new MemoryStream(); XmlTextWriter writer = new XmlTextWriter(ms, new UTF8Encoding(false)); writer = new XmlTextWriter(ms, new UTF8Encoding(false)); //writer.Formatting = Formatting.Indented; doc.WriteContentTo(writer); writer.Flush(); ms.Position = 0; StreamReader reader = new StreamReader(ms); return(reader.ReadToEnd()); }
public static void Sign(this XmlDocument doc, X509Certificate2 cert, string elementId, string elementName = null) { if (doc == null) { throw new ArgumentNullException(nameof(doc)); } var rsaKey = ((RSA)cert.PrivateKey); var signedXml = new SignedXml(doc) { SigningKey = rsaKey }; signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl; var keyInfo = new KeyInfo(); var keyInfoData = new KeyInfoX509Data(cert); keyInfo.AddClause(keyInfoData); signedXml.KeyInfo = keyInfo; var reference = new Reference("#" + elementId); reference.AddTransform(new XmlDsigEnvelopedSignatureTransform()); reference.AddTransform(new XmlDsigExcC14NTransform()); signedXml.AddReference(reference); signedXml.ComputeSignature(); var signatureElement = signedXml.GetXml(); var signatureParent = string.IsNullOrWhiteSpace(elementName) ? doc.DocumentElement : doc.GetElementsByTagName(elementName)[0]; signatureParent?.AppendChild(doc.ImportNode(signatureElement, true)); }
// Create a signature and add it to the specified document. private static void SignDocument(ref XmlDocument xmlDoc) { // Generate a signing key. RSACryptoServiceProvider Key = new RSACryptoServiceProvider(); // Create a SignedXml object. SignedXml signedXml = new SignedXml(xmlDoc); // 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. reference.AddTransform(new XmlDsigEnvelopedSignatureTransform()); // Add the reference to the SignedXml object. signedXml.AddReference(reference); try { // Create a new KeyInfo object. KeyInfo keyInfo = new KeyInfo(); // Load the X509 certificate. X509Certificate MSCert = X509Certificate.CreateFromCertFile(Certificate); // Load the certificate into a KeyInfoX509Data object // and add it to the KeyInfo object. keyInfo.AddClause(new KeyInfoX509Data(MSCert)); // Add the KeyInfo object to the SignedXml object. signedXml.KeyInfo = keyInfo; } catch (FileNotFoundException ex) { Console.WriteLine("Unable to locate the following file: " + Certificate); } // Compute the signature. signedXml.ComputeSignature(); // Add the signature branch to the original tree so it is enveloped. xmlDoc.DocumentElement.AppendChild(signedXml.GetXml()); }
private static void GenerateReference(string elementID, string inclusivePrefixList, SignedXmlWithId xSigned) { var reference = new Reference() { Uri = "#" + elementID }; XmlDsigExcC14NTransform env = new XmlDsigExcC14NTransform(); env.InclusiveNamespacesPrefixList = inclusivePrefixList; reference.AddTransform(env); xSigned.AddReference(reference); }
public static XmlElement GenerateSignature(XmlDocument licenseDocument, IPrivateCryptoKey privateKey) { using (var privateKeyProvider = new RsaPrivateKeyProvider()) { var reference = new Reference { Uri = string.Empty }; reference.AddTransform(new XmlDsigEnvelopedSignatureTransform()); reference.AddTransform(new XmlDsigExcC14NTransform()); reference.DigestMethod = "http://www.w3.org/2001/04/xmlenc#sha256"; var signedXml = new SignedXml(licenseDocument) { SigningKey = privateKeyProvider.Recreate(privateKey) }; signedXml.SignedInfo.SignatureMethod = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"; signedXml.AddReference(reference); signedXml.ComputeSignature(); return(signedXml.GetXml()); } }
public static void NenshkruajFajllin() { // krijimi dhe nenshkrimi duhet te futet ne Server // shiko se duhet me exportu public key te Rsa me e qit si file // e nuk mujta me gjet XmlDocument objXml = new XmlDocument(); RSACryptoServiceProvider objRsa = new RSACryptoServiceProvider(); // merr db objXml.Load("xmldb.xml"); SignedXml objSignedXml = new SignedXml(objXml);; Reference referenca = new Reference(); referenca.Uri = ""; XmlDsigEnvelopedSignatureTransform transform = new XmlDsigEnvelopedSignatureTransform(); referenca.AddTransform(transform); objSignedXml.AddReference(referenca); KeyInfo ki = new KeyInfo(); ki.AddClause(new RSAKeyValue(objRsa)); objSignedXml.KeyInfo = ki; //exportimi i qelsit string strXmlParametrat = objRsa.ToXmlString(true); // true eshte per celes privat dhe publik 2t StreamWriter sw = new StreamWriter("celesiPublik.xml"); sw.Write(strXmlParametrat); sw.Close(); objSignedXml.SigningKey = objRsa; objSignedXml.ComputeSignature(); XmlElement signatureNode = objSignedXml.GetXml(); XmlElement rootNode = objXml.DocumentElement; rootNode.AppendChild(signatureNode); // e nenshkruan xmldb dhe e run ne 1 fallj tjeter objXml.Save("xmldb_nenshkruar.xml"); }
/// <summary> /// Use an X509 certificate to append a computed signature to an XML serialized Response /// </summary> /// <param name="XMLSerializedSAMLResponse"></param> /// <param name="ReferenceURI">Assertion ID from SAML Response</param> /// <param name="SigningCert">X509 Certificate for signing</param> /// <remarks>Referenced this article: /// http://www.west-wind.com/weblog/posts/2008/Feb/23/Digitally-Signing-an-XML-Document-and-Verifying-the-Signature /// </remarks> public static void AppendSignatureToXMLDocument(ref XmlDocument XMLSerializedSAMLResponse, String ReferenceURI) { var signCertificate = SAMLConfiguration.Current.GetLocalIdentityProviderCertificate(); var signedXML = new PrefixedSignedXml(XMLSerializedSAMLResponse); signedXML.SigningKey = signCertificate.PrivateKey; signedXML.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl; var reference = new Reference(); reference.Uri = ""; reference.AddTransform(new XmlDsigEnvelopedSignatureTransform()); reference.AddTransform(new XmlDsigExcC14NTransform()); signedXML.AddReference(reference); signedXML.ComputeSignature("ds"); var signature = signedXML.GetXml("ds"); var xeResponse = XMLSerializedSAMLResponse.DocumentElement; xeResponse.AppendChild(signature); }
void CreateReference(Signature sig, XmlDocument doc, string id) { SecurityAlgorithmSuite suite = security.Element.DefaultAlgorithmSuite; if (id == String.Empty) { id = GenerateId(doc); } Reference r = new Reference("#" + id); r.AddTransform(CreateTransform(suite.DefaultCanonicalizationAlgorithm)); r.DigestMethod = suite.DefaultDigestAlgorithm; sig.SignedInfo.AddReference(r); }
/// <summary> /// Assina um elemento Xml pela tag de identificação. /// </summary> /// <param name="xml">Xml que dese ser assinado.</param> /// <param name="idReference">Conteudo da tag de referencia para assinatura.</param> /// <param name="certificate">Certificado usado para assinatura.</param> /// <returns>Elemento Xml contendo a assinatura.</returns> public static string GetSignature(XmlDocument xml, string idReference, X509Certificate2 certificate) { SignedXml signedXml = new SignedXml(xml); signedXml.Signature.Id = "Ass_" + idReference; signedXml.SigningKey = certificate.PrivateKey; idReference = !string.IsNullOrEmpty(idReference) ? "#" + idReference : ""; Reference reference = new Reference(idReference); reference.AddTransform(new XmlDsigEnvelopedSignatureTransform()); reference.AddTransform(new XmlDsigC14NTransform()); KeyInfo keyInfo = new KeyInfo(); keyInfo.AddClause(new KeyInfoX509Data(certificate)); signedXml.AddReference(reference); signedXml.KeyInfo = keyInfo; signedXml.ComputeSignature(); return(signedXml.GetXml().OuterXml); }
private void SetContentExternallyDetached(SignatureDocument sigDocument, string fileName) { _refContent = new Reference(); sigDocument.Document = new XmlDocument(); sigDocument.XadesSignature = new XadesSignedXml(sigDocument.Document); _refContent.Uri = new Uri(fileName).AbsoluteUri; _refContent.Id = "Reference-" + Guid.NewGuid().ToString(); if (_refContent.Uri.EndsWith(".xml") || _refContent.Uri.EndsWith(".XML")) { _mimeType = "text/xml"; _refContent.AddTransform(new XmlDsigC14NTransform()); } sigDocument.XadesSignature.AddReference(_refContent); }
public XmlElement GetDGWSSign(X509Certificate2 cert) { var refnames = new [] { "#IDCard" }; foreach (var s in refnames) { var reference = new Reference(); reference.Uri = s; reference.AddTransform(new XmlDsigEnvelopedSignatureTransform()); reference.AddTransform(new XmlDsigExcC14NTransform()); reference.DigestMethod = XmlDsigSHA1Url; AddReference(reference); } SigningKey = cert.PrivateKey; SignedInfo.CanonicalizationMethod = new XmlDsigExcC14NTransform().Algorithm; SignedInfo.SignatureMethod = XmlDsigRSASHA1Url; KeyInfo = new KeyInfo(); KeyInfo.AddClause(new KeyInfoX509Data(cert)); ComputeSignature(); return(GetXml()); }
// Sign an XML file and save the signature in a new file. public static void SignXmlFile(string FileName, string SignedFileName, KeyedHashAlgorithm 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); // 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(Key); // 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(); }
public static XadesSignedXml GetXadesSignedXml(X509Certificate2 certificate, XmlDocument originalDoc, string signatureid, string privateKeyPassword) { var secureString = new SecureString(); foreach (var ch in privateKeyPassword) { secureString.AppendChar(ch); } var provider = (Gost3410CryptoServiceProvider)certificate.PrivateKey; provider.SetContainerPassword(secureString); var signedXml = new XadesSignedXml(originalDoc) { SigningKey = provider }; signedXml.Signature.Id = signatureid; signedXml.SignatureValueId = String.Format("{0}-sigvalue", signatureid); var reference = new Reference { Uri = "#signed-data-container", DigestMethod = CPSignedXml.XmlDsigGost3411UrlObsolete, Id = String.Format("{0}-ref0", signatureid) }; reference.AddTransform(new XmlDsigEnvelopedSignatureTransform()); reference.AddTransform(new XmlDsigExcC14NTransform()); signedXml.AddReference(reference); signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigCanonicalizationUrl; signedXml.SignedInfo.SignatureMethod = CPSignedXml.XmlDsigGost3410UrlObsolete; return(signedXml); }
private static XmlDocument GetSignedMetaData(XmlDocument xmlDocument, X509Certificate2 certificate) { SignedXml signedXml = new SignedXml(xmlDocument); signedXml.SigningKey = certificate.PrivateKey; // Create a reference to be signed. Reference reference = new Reference(); reference.Uri = ""; // Add an enveloped transformation to the reference. XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform(true); reference.AddTransform(env); //canonicalize XmlDsigC14NTransform c14t = new XmlDsigC14NTransform(); reference.AddTransform(c14t); // 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(); xmlDocument.DocumentElement.AppendChild( xmlDocument.ImportNode(xmlDigitalSignature, true)); return(xmlDocument); }
public static void Sign(this XmlDocument xmlDocument, X509Certificate2 cert) { if (xmlDocument == null) { throw new ArgumentNullException("xmlDocument"); } if (cert == null) { throw new ArgumentNullException("cert"); } var signedXml = new SignedXml(xmlDocument); // The transform XmlDsigExcC14NTransform and canonicalization method XmlDsigExcC14NTransformUrl is important for partially signed XML files // see: http://msdn.microsoft.com/en-us/library/system.security.cryptography.xml.signedxml.xmldsigexcc14ntransformurl(v=vs.110).aspx // The reference URI has to be set correctly to avoid assertion injections // For both, the ID/Reference and the Transform/Canonicalization see as well: // https://www.oasis-open.org/committees/download.php/35711/sstc-saml-core-errata-2.0-wd-06-diff.pdf section 5.4.2 and 5.4.3 signedXml.SigningKey = (RSACryptoServiceProvider)cert.PrivateKey; signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl; var reference = new Reference { Uri = "#" + xmlDocument.DocumentElement.GetAttribute("ID") }; reference.AddTransform(new XmlDsigEnvelopedSignatureTransform()); reference.AddTransform(new XmlDsigExcC14NTransform()); signedXml.AddReference(reference); signedXml.ComputeSignature(); xmlDocument.DocumentElement.InsertAfter( xmlDocument.ImportNode(signedXml.GetXml(), true), xmlDocument.DocumentElement["Issuer", Saml2Namespaces.Saml2Name]); }
private static void AddSignatureNode(XmlDocument xmlDoc, XmlNamespaceManager ns, X509Certificate2 certificate) { XmlElement issuerNode = (XmlElement)xmlDoc.DocumentElement.SelectSingleNode("saml:Issuer", ns); SignedXml signedXml = new SignedXml(xmlDoc.DocumentElement); signedXml.SigningKey = certificate.PrivateKey; signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl; KeyInfo keyInfo = new KeyInfo(); keyInfo.AddClause(new KeyInfoX509Data(certificate)); signedXml.KeyInfo = keyInfo; string refId = xmlDoc.DocumentElement.GetAttribute("ID"); Reference reference = new Reference(); reference.Uri = "#" + refId; XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform(); reference.AddTransform(env); XmlDsigExcC14NTransform env2 = new XmlDsigExcC14NTransform(); env2.InclusiveNamespacesPrefixList = "#default code ds kind rw saml samlp typens"; reference.AddTransform(env2); signedXml.AddReference(reference); signedXml.ComputeSignature(); XmlElement xmlDigitalSignature = signedXml.GetXml(); xmlDoc.DocumentElement.InsertAfter(xmlDoc.ImportNode(xmlDigitalSignature, true), issuerNode); }
// 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 = ""; //.DigestMethod = CryptoPro.Sharpei.Xml.CPSignedXml.XmlDsigGost3411UrlObsolete; // 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(); }
/// <summary> /// Signs an XmlDocument with an xml signature using the signing certificate given as argument to the method. /// In case it is ever needed ... this link explains how to add namespace prefixes to the generated signature. http://stackoverflow.com/questions/12219232/xml-signature-ds-prefix /// </summary> /// <param name="xDoc">The XDocument to be signed</param> /// <param name="ids">The ids of the elements in the xmldocument that must be signed.</param> /// <param name="cert">The certificate used to sign the document</param> public static XDocument SignDocument(XDocument xDoc, IEnumerable <string> ids, X509Certificate2 cert) { // Convert to XmlDocument as SignedXml only understands this type. var doc = ToXmlDocument(xDoc); // Apply private key, canonicalization method and signature method var signedXml = new SignedXmlWithIdResolvement(doc); signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl; signedXml.SignedInfo.SignatureMethod = RsaPkcs1Sha256SignatureDescription.XmlDsigMoreRsaSha256Url; signedXml.SigningKey = cert.PrivateKey; // Make a reference for each element that must be signed. foreach (var id in ids) { var reference = new Reference("#" + id); reference.AddTransform(new XmlDsigExcC14NTransform()); reference.DigestMethod = RsaPkcs1Sha256SignatureDescription.XmlEncSha256Url; signedXml.AddReference(reference); } // Include a reference to the certificate var referenceElement = doc.CreateElement(SignatureCaseMessageTransformer.WssePrefix, "Reference", SignatureCaseMessageTransformer.Wsse10Namespace); referenceElement.SetAttribute("URI", "#sec-binsectoken"); // Attribute must be in the empty namespace. var securityTokenReferenceElement = doc.CreateElement(SignatureCaseMessageTransformer.WssePrefix, "SecurityTokenReference", SignatureCaseMessageTransformer.Wsse10Namespace); securityTokenReferenceElement.AppendChild(referenceElement); signedXml.KeyInfo.AddClause(new KeyInfoNode(securityTokenReferenceElement)); signedXml.ComputeSignature(); // Append the computed signature. The signature must be placed as the sibling of the BinarySecurityToken element. var nsManager = new XmlNamespaceManager(doc.NameTable); nsManager.AddNamespace(SignatureCaseMessageTransformer.S11Prefix, SignatureCaseMessageTransformer.S11Namespace); nsManager.AddNamespace(SignatureCaseMessageTransformer.WssePrefix, SignatureCaseMessageTransformer.Wsse10Namespace); var securityNode = doc.SelectSingleNode("/" + SignatureCaseMessageTransformer.S11Prefix + ":Envelope/" + SignatureCaseMessageTransformer.S11Prefix + ":Header/" + SignatureCaseMessageTransformer.WssePrefix + ":Security", nsManager); var binarySecurityTokenNode = doc.SelectSingleNode("/" + SignatureCaseMessageTransformer.S11Prefix + ":Envelope/" + SignatureCaseMessageTransformer.S11Prefix + ":Header/" + SignatureCaseMessageTransformer.WssePrefix + ":Security/" + SignatureCaseMessageTransformer.WssePrefix + ":BinarySecurityToken", nsManager); securityNode.InsertAfter(doc.ImportNode(signedXml.GetXml(), true), binarySecurityTokenNode); var signedDocument = ToXDocument(doc); return(signedDocument); }
public static XmlDocument SignXmlFileSmev2(XmlDocument doc, X509Certificate2 certificate) { XmlNode root = doc.SelectSingleNode("/*"); string rootPrefix = root.Prefix; //----------------------------------------------------------------------------------------------CREATE STRUCTURE XmlDocument tDoc = AddTemplate(doc, certificate); //----------------------------------------------------------------------------------------------ROOT PREFIX XmlElement bodyElement = tDoc.GetElementsByTagName(rootPrefix + ":Body")[0] as XmlElement; string referenceUri = bodyElement.GetAttribute("wsu:Id"); //----------------------------------------------------------------------------------------------SignedXML CREATE //нужен для корректной отработки wsu:reference Smev2SignedXml signedXml = new Smev2SignedXml(tDoc) { SigningKey = certificate.PrivateKey }; //----------------------------------------------------------------------------------------------REFERNCE Reference reference = new Reference { DigestMethod = CryptoPro.Sharpei.Xml.CPSignedXml.XmlDsigGost3411UrlObsolete, Uri = "#" + referenceUri }; XmlDsigExcC14NTransform c14 = new XmlDsigExcC14NTransform(); reference.AddTransform(c14); signedXml.AddReference(reference); //----------------------------------------------------------------------------------------------SIGNATURE SETUP signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl; #pragma warning disable 612 signedXml.SignedInfo.SignatureMethod = CryptoPro.Sharpei.Xml.CPSignedXml.XmlDsigGost3410UrlObsolete; #pragma warning disable 612 //----------------------------------------------------------------------------------------------KEYINFO KeyInfo keyInfo = new KeyInfo(); KeyInfoX509Data X509KeyInfo = new KeyInfoX509Data(certificate); keyInfo.AddClause(X509KeyInfo); signedXml.KeyInfo = keyInfo; //----------------------------------------------------------------------------------------------SIGN DOCUMENT signedXml.ComputeSignature(); //----------------------------------------------------------------------------------------------GET XML XmlElement xmlDigitalSignature = signedXml.GetXml(); //----------------------------------------------------------------------------------------------APPEND SIGNATURE TAGS tDoc.GetElementsByTagName("Signature")[0].PrependChild( tDoc.ImportNode(xmlDigitalSignature.GetElementsByTagName("SignatureValue")[0], true)); tDoc.GetElementsByTagName("Signature")[0].PrependChild( tDoc.ImportNode(xmlDigitalSignature.GetElementsByTagName("SignedInfo")[0], true)); ((XmlElement)tDoc.GetElementsByTagName("Signature")[0]).SetAttribute("xmlns", ds_); return(tDoc); }
public void XmlHelpers_IsSignedBy_ThrowsOnDualReferencesInSignature() { var xml = "<xml ID=\"myxml\" />"; var xmlDoc = XmlHelpers.XmlDocumentFromString(xml); var signedXml = new SignedXml(xmlDoc); signedXml.SigningKey = SignedXmlHelper.TestCert.PrivateKey; signedXml.SignedInfo.SignatureMethod = SignedXml.XmlDsigRSASHA1Url; signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl; var ref1 = new Reference { Uri = "#myxml" }; ref1.AddTransform(new XmlDsigEnvelopedSignatureTransform()); ref1.AddTransform(new XmlDsigExcC14NTransform()); signedXml.AddReference(ref1); var ref2 = new Reference { Uri = "#myxml" }; ref2.AddTransform(new XmlDsigEnvelopedSignatureTransform()); ref2.AddTransform(new XmlDsigExcC14NTransform()); signedXml.AddReference(ref2); signedXml.ComputeSignature(); xmlDoc.DocumentElement.AppendChild(xmlDoc.ImportNode(signedXml.GetXml(), true)); xmlDoc.DocumentElement.Invoking( x => x.IsSignedBy(SignedXmlHelper.TestCert)) .Should().Throw <InvalidSignatureException>() .And.Message.Should().Be("Multiple references for Xml signatures are not allowed."); }
private static XmlElement signedXml(XmlDocument xmlDoc, AsymmetricAlgorithm asym) { SignedXml signedXml = new SignedXml(xmlDoc); signedXml.SigningKey = asym; Reference reference = new Reference { Uri = "" }; reference.AddTransform(new XmlDsigEnvelopedSignatureTransform()); signedXml.AddReference(reference); signedXml.ComputeSignature(); return(signedXml.GetXml()); }
public static void SignSamlDocument(XmlDocument doc, string id, X509Certificate2 cert) { var signedXml = new SignedXml(doc); signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl; signedXml.SigningKey = cert.PrivateKey; signedXml.SignedInfo.SignatureMethod = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"; // Retrieve the value of the "ID" attribute on the root assertion element. var reference = new Reference("#" + id); reference.DigestMethod = "http://www.w3.org/2001/04/xmlenc#sha256"; reference.AddTransform(new XmlDsigEnvelopedSignatureTransform()); reference.AddTransform(new XmlDsigExcC14NTransform()); signedXml.AddReference(reference); // Include the public key of the certificate in the assertion. signedXml.KeyInfo = new KeyInfo(); signedXml.KeyInfo.AddClause(new KeyInfoX509Data(cert, X509IncludeOption.EndCertOnly)); signedXml.ComputeSignature(); // Append the computed signature. The signature must be placed as the sibling of the Issuer element. if (doc.DocumentElement != null) { var nodes = doc.DocumentElement.GetElementsByTagName("Issuer", Saml20Constants.Assertion); var parentNode = nodes[0].ParentNode; if (parentNode != null) { parentNode.InsertAfter(doc.ImportNode(signedXml.GetXml(), true), nodes[0]); } } }
void AddSignatureReference(SignedXml signedXml, XmlDocument doc, String partName) { DataObject dataObject = new DataObject(); XmlElement elPart = (XmlElement)doc.GetElementsByTagName(partName)[0]; dataObject.Data = doc.GetElementsByTagName(partName); elPart.SetAttribute("id", partName); // Create a reference to be signed. Reference reference = new Reference(); reference.Uri = "#" + partName; reference.AddTransform(new XmlDsigC14NTransform()); // Da det er xml vi signerer, ønsker vi Canonicalisation. signedXml.AddReference(reference); }
/// <summary> /// Carga el documento XML especificado y establece para firmar el elemento especificado en elementId /// </summary> /// <param name="xmlDocument"></param> /// <param name="elementId"></param> /// <param name="mimeType"></param> private void SetContentInternallyDetached(SignatureDocument sigDocument, XmlDocument xmlDocument, string elementId) { sigDocument.Document = xmlDocument; _refContent = new Reference(); _refContent.Uri = "#" + elementId; _refContent.Id = "Reference-" + Guid.NewGuid().ToString(); if (_dataFormat.MimeType == "text/xml") { XmlDsigC14NTransform transform = new XmlDsigC14NTransform(); _refContent.AddTransform(transform); } else { XmlDsigBase64Transform transform = new XmlDsigBase64Transform(); _refContent.AddTransform(transform); } sigDocument.XadesSignature = new XadesSignedXml(sigDocument.Document); sigDocument.XadesSignature.AddReference(_refContent); }
private static XmlElement GetXmlDigitalSignature(XmlDocument x, AsymmetricAlgorithm key) { var signedXml = new SignedXml(x) { SigningKey = key }; var reference = new Reference { Uri = "" }; reference.AddTransform(new XmlDsigEnvelopedSignatureTransform()); signedXml.AddReference(reference); signedXml.ComputeSignature(); return(signedXml.GetXml()); }
private static string CreateSignature(X509Certificate2 clientCert, XElement samlResponse) { string responseId = samlResponse.Attribute("ID").Value; XmlDocument doc = new XmlDocument(); XmlElement samlResponseXmlEl = doc.ReadNode(samlResponse.CreateReader()) as XmlElement; doc.AppendChild(samlResponseXmlEl); if (samlResponseXmlEl == null) { throw new NullReferenceException("samlResponseXmlEl was null"); } var signedXml = new SignedXml(doc); var signatureReference = new Reference("#" + responseId); signatureReference.AddTransform(new XmlDsigExcC14NTransform("#default samlp saml ds xs xsi")); signatureReference.AddTransform(new XmlDsigEnvelopedSignatureTransform()); signedXml.AddReference(signatureReference); signedXml.SigningKey = clientCert.PrivateKey; var certificateKeyInfo = new KeyInfo(); certificateKeyInfo.AddClause(new KeyInfoX509Data(clientCert)); signedXml.KeyInfo = certificateKeyInfo; signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl; signedXml.ComputeSignature(); string signatureXml = signedXml.GetXml().OuterXml; return(signatureXml); }
public static XmlDocument Assinar(XmlDocument docXML, string pUri, X509Certificate2 pCertificado) { try { // Load the certificate from the certificate store. X509Certificate2 cert = pCertificado; // 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 = docXML; // Create a SignedXml object. SignedXml signedXml = new SignedXml(doc); // Add the key to the SignedXml document. signedXml.SigningKey = cert.PrivateKey; // Create a reference to be signed. Reference reference = new Reference(); // pega o uri que deve ser assinada XmlAttributeCollection _Uri = doc.GetElementsByTagName(pUri).Item(0).Attributes; foreach (XmlAttribute _atributo in _Uri) { if (_atributo.Name == "Id") { reference.Uri = "#" + _atributo.InnerText; } } // Add an enveloped transformation to the reference. XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform(); reference.AddTransform(env); XmlDsigC14NTransform c14 = new XmlDsigC14NTransform(); reference.AddTransform(c14); // Add the reference to the SignedXml object. signedXml.AddReference(reference); // Create a new KeyInfo object. KeyInfo keyInfo = new KeyInfo(); // Load the certificate into a KeyInfoX509Data object // and add it to the KeyInfo object. keyInfo.AddClause(new KeyInfoX509Data(cert)); // Add the KeyInfo object to the SignedXml object. 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); } return doc; } catch (Exception ex) { throw new Exception("Erro ao efetuar assinatura digital, detalhes: " + ex.Message); } }
// Třída podepíše certifikátem dokument XML a přidá časové razítko // Pokud je již dokument podepsaný, přidá se další podpis public XmlDocument SignWithTimestamp(XmlDocument doc, X509Certificate2 cert, string tsURL, string tsUsername, string tsPassword) { // před podepisováním z dokumentu odstraníme komentáře (.NET s nimi má problémy pokud se kombinují s XPath transformacemi) XmlDocument strippedDoc = RemoveComments(doc); // definice mapování prefixů na jmenné prostory XmlNamespaceManager manager = new XmlNamespaceManager(strippedDoc.NameTable); manager.AddNamespace("dsig", "http://www.w3.org/2000/09/xmldsig#"); // zjištění kolik podpisů již v dokumentu je int signatures = strippedDoc.SelectNodes("//dsig:Signature", manager).Count; string signatureID = (signatures + 1).ToString(); // vytvoření elementu Object pro časové razítko XmlElement objectElement = doc.CreateElement("Object", "http://www.w3.org/2000/09/xmldsig#"); // spočítání otisku certifikátu SHA256 sha256 = new SHA256Managed(); string certHash = Convert.ToBase64String(sha256.ComputeHash(cert.GetRawCertData())); objectElement.InnerXml = @"<xades:QualifyingProperties xmlns:xades='http://uri.etsi.org/01903/v1.3.2#' Target='#Signature-" + signatureID + @"' xmlns='http://www.w3.org/2000/09/xmldsig#'> <xades:SignedProperties Id='Signature-" + signatureID + @"-SignedProperties'> <xades:SignedSignatureProperties> <xades:SigningTime>" + XmlConvert.ToString(DateTime.Now.ToUniversalTime(), XmlDateTimeSerializationMode.RoundtripKind) + @"</xades:SigningTime> <xades:SigningCertificate> <xades:Cert> <xades:CertDigest> <DigestMethod Algorithm='http://www.w3.org/2001/04/xmlenc#sha256'></DigestMethod> <DigestValue>" + certHash + @"</DigestValue> </xades:CertDigest> <xades:IssuerSerial> <X509IssuerName>" + cert.IssuerName + @"</X509IssuerName> <X509SerialNumber>" + cert.GetSerialNumberString() + @"</X509SerialNumber> </xades:IssuerSerial> </xades:Cert> </xades:SigningCertificate> </xades:SignedSignatureProperties> <xades:SignedDataObjectProperties> <xades:DataObjectFormat ObjectReference='#Signature-" + signatureID + @"-Document-Reference'> <xades:MimeType>application/xml</xades:MimeType> </xades:DataObjectFormat> </xades:SignedDataObjectProperties> </xades:SignedProperties> <xades:UnsignedProperties> <xades:UnsignedSignatureProperties> <xades:SignatureTimeStamp> <xades:EncapsulatedTimeStamp Encoding='http://uri.etsi.org/01903/v1.2.2#DER'></xades:EncapsulatedTimeStamp> </xades:SignatureTimeStamp> </xades:UnsignedSignatureProperties> </xades:UnsignedProperties> </xades:QualifyingProperties>"; // objekt sloužící pro vytvoření podpisu CustomIdSignedXml signedXml = new CustomIdSignedXml(strippedDoc, objectElement); // podepisovat budeme privátním klíčem z certifikátu signedXml.SigningKey = cert.PrivateKey; // podepisovat budeme pomocí RSA-SHA256 signedXml.SignedInfo.SignatureMethod = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"; // reference na podepisovaný dokument ("" znamená celý dokument) Reference reference = new Reference(); reference.Uri = ""; reference.Id = "Signature-" + signatureID + "-Document-Reference"; // pro výpočet otisku se bude používat SHA-256 reference.DigestMethod = "http://www.w3.org/2001/04/xmlenc#sha256"; // digitální podpis bude přímo součástí dokumentu XML (tzv. "enveloped signature") XmlDsigEnvelopedSignatureTransform envTransform = new XmlDsigEnvelopedSignatureTransform(); reference.AddTransform(envTransform); // navíc budeme používat XPath transoformaci, která dovoluje přidat několik podpisů najednou XmlDsigXPathTransform xpathTransform = new XmlDsigXPathTransform(); // příprava definice XPath transformace jako struktura XML signature XmlDocument transformBody = new XmlDocument(); // podoba XPath filtru se liší podle počtu podpisů if (signatures == 0) transformBody.LoadXml("<dsig:XPath xmlns:dsig='http://www.w3.org/2000/09/xmldsig#'>not(ancestor-or-self::dsig:Signature)</dsig:XPath>"); else transformBody.LoadXml("<dsig:XPath xmlns:dsig='http://www.w3.org/2000/09/xmldsig#'>not(ancestor-or-self::dsig:Signature) or not(ancestor-or-self::dsig:Signature/preceding-sibling::dsig:Signature[" + signatures + "])</dsig:XPath>"); // načtení definice XPath transformace do objektu xpathTransform.LoadInnerXml(transformBody.SelectNodes("/*[1]")); // přidání XPath transformace reference.AddTransform(xpathTransform); // přidání reference do podpisu signedXml.AddReference(reference); // reference na SignedProperties -- XAdES-BES vyžaduje podpis certifikátu Reference spReference = new Reference(); spReference.Uri = "#Signature-" + signatureID + "-SignedProperties"; // pro výpočet otisku se bude používat SHA-256 spReference.DigestMethod = "http://www.w3.org/2001/04/xmlenc#sha256"; // přidání reference do podpisu signedXml.AddReference(spReference); // přidání certifikátu do podpisu KeyInfo keyInfo = new KeyInfo(); keyInfo.AddClause(new KeyInfoX509Data(cert)); signedXml.KeyInfo = keyInfo; // přidání objektu s časovým razítkem do podpisu DataObject dataObj = new DataObject(); dataObj.LoadXml(objectElement); signedXml.AddObject(dataObj); // výpočet podpisu signedXml.ComputeSignature(); // získání XML reprezentace podpisu XmlElement xmlSignature = signedXml.GetXml(); // k podpisu přidáme identifikátor, tak jak doporučuje standard ISDOC xmlSignature.SetAttribute("Id", "Signature-" + signatureID); // XML dokument pro podepsaný výsledek XmlDocument result = new XmlDocument(); // bílé znaky musíme zachovat, jinak se špatně spočte hash result.PreserveWhitespace = true; // načtení původního dokumentu result.AppendChild(result.ImportNode(strippedDoc.DocumentElement, true)); // připojení podpisu na konec dokumentu XML result.DocumentElement.AppendChild(result.ImportNode(xmlSignature, true)); // Spočítání otisku digitálního podpisu byte[] digest; digest = sha256.ComputeHash(signedXml.SignatureValue); // generátor požadavků na časové razítko TimeStampRequestGenerator reqGen = new TimeStampRequestGenerator(); // vytvoření dat pro požadavek na timestamp server TimeStampRequest request = reqGen.Generate(TspAlgorithms.Sha256, digest); // získání surových dat pro poslání na timestamp server byte[] reqData = request.GetEncoded(); // inicializace požadavku na timestamp server HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(tsURL); httpReq.Method = "POST"; httpReq.ContentType = "application/timestamp-query"; httpReq.ContentLength = reqData.Length; httpReq.Credentials = new NetworkCredential(tsUsername, tsPassword); // odeslání požadavku na timestamp server Stream reqStream = httpReq.GetRequestStream(); reqStream.Write(reqData, 0, reqData.Length); reqStream.Close(); // přečtení odpovědi HttpWebResponse httpResp = (HttpWebResponse)httpReq.GetResponse(); Stream respStream = new BufferedStream(httpResp.GetResponseStream()); TimeStampResponse response = new TimeStampResponse(respStream); respStream.Close(); // Console.WriteLine("Status razítkování: " + response.Status); // Console.WriteLine("Čas razítka: " + response.TimeStampToken.TimeStampInfo.GenTime.ToLocalTime()); string timestamp = Convert.ToBase64String(response.GetEncoded()); // doplnění získaného časového razítka do dokumentu XmlNamespaceManager nsmng = new XmlNamespaceManager(result.NameTable); nsmng.AddNamespace("ds", "http://www.w3.org/2000/09/xmldsig#"); nsmng.AddNamespace("xades", "http://uri.etsi.org/01903/v1.3.2#"); XmlElement etsElement = (XmlElement)result.SelectSingleNode("//*[@Id = 'Signature-" + signatureID +"']/ds:Object/xades:QualifyingProperties/xades:UnsignedProperties/xades:UnsignedSignatureProperties/xades:SignatureTimeStamp/xades:EncapsulatedTimeStamp", nsmng); etsElement.InnerText = timestamp; return result; }
// Třída podepíše certifikátem dokument XML // Pokud je již dokument podepsaný, přidá se další podpis public XmlDocument Sign(XmlDocument doc, X509Certificate2 cert) { // před podepisováním z dokumentu odstraníme komentáře (.NET s nimi má problémy pokud se kombinují s XPath transformacemi) XmlDocument strippedDoc = RemoveComments(doc); // definice mapování prefixů na jmenné prostory XmlNamespaceManager manager = new XmlNamespaceManager(strippedDoc.NameTable); manager.AddNamespace("dsig", "http://www.w3.org/2000/09/xmldsig#"); // zjištění kolik podpisů již v dokumentu je int signatures = strippedDoc.SelectNodes("//dsig:Signature", manager).Count; // objekt sloužící pro vytvoření podpisu SignedXml signedXml = new SignedXml(strippedDoc); // podepisovat budeme privátním klíčem z certifikátu signedXml.SigningKey = cert.PrivateKey; // podepisovat budeme pomocí RSA-SHA256 signedXml.SignedInfo.SignatureMethod = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"; // reference na podepisovaný dokument ("" znamená celý dokument) Reference reference = new Reference(); reference.Uri = ""; // pro výpočet otisku se bude používat SHA-256 reference.DigestMethod = "http://www.w3.org/2001/04/xmlenc#sha256"; // digitální podpis bude přímo součástí dokumentu XML (tzv. "enveloped signature") XmlDsigEnvelopedSignatureTransform envTransform = new XmlDsigEnvelopedSignatureTransform(); reference.AddTransform(envTransform); // navíc budeme používat XPath transoformaci, která dovoluje přidat několik podpisů najednou XmlDsigXPathTransform xpathTransform = new XmlDsigXPathTransform(); // příprava definice XPath transformace jako struktura XML signature XmlDocument transformBody = new XmlDocument(); // podoba XPath filtru se liší podle počtu podpisů if (signatures == 0) transformBody.LoadXml("<dsig:XPath xmlns:dsig='http://www.w3.org/2000/09/xmldsig#'>not(ancestor-or-self::dsig:Signature)</dsig:XPath>"); else transformBody.LoadXml("<dsig:XPath xmlns:dsig='http://www.w3.org/2000/09/xmldsig#'>not(ancestor-or-self::dsig:Signature) or not(ancestor-or-self::dsig:Signature/preceding-sibling::dsig:Signature[" + signatures + "])</dsig:XPath>"); // načtení definice XPath transformace do objektu xpathTransform.LoadInnerXml(transformBody.SelectNodes("/*[1]")); // přidání XPath transformace reference.AddTransform(xpathTransform); // přidání reference do podpisu signedXml.AddReference(reference); // přidání certifikátu do podpisu KeyInfo keyInfo = new KeyInfo(); keyInfo.AddClause(new KeyInfoX509Data(cert)); signedXml.KeyInfo = keyInfo; // výpočet podpisu signedXml.ComputeSignature(); // získání XML reprezentace podpisu XmlElement xmlSignature = signedXml.GetXml(); // k podpisu přidáme identifikátor, tak jak doporučuje standard ISDOC xmlSignature.SetAttribute("Id", "Signature-" + (signatures + 1)); // XML dokument pro podepsaný výsledek XmlDocument result = new XmlDocument(); // bílé znaky musíme zachovat, jinak se špatně spočte hash result.PreserveWhitespace = true; // načtení původního dokumentu result.AppendChild(result.ImportNode(strippedDoc.DocumentElement, true)); // připojení podpisu na konec dokumentu XML result.DocumentElement.AppendChild(result.ImportNode(xmlSignature, true)); return result; }
// 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 doc, RSA key) { // Create a SignedXml object SignedXml signedXml = new SignedXml(doc); // Add the key to the SignedXml document signedXml.KeyInfo = new KeyInfo(); signedXml.KeyInfo.AddClause(new RSAKeyValue(key)); 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); // Set the KeyInfo to the SignedXml object // KeyInfo ki = new KeyInfo(); // ki.AddClause(new RSAKeyValue(key)); // signedXml.SigningKey = key; // signedXml.KeyInfo = ki; // 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)); doc.DocumentElement.PrependChild(signedXml.GetXml()); }
//------------------------------------------------------------------------------------------- private string SignXML(string xml) { // Signing XML Documents: http://msdn.microsoft.com/en-us/library/ms229745.aspx var rsaKey = new RSACryptoServiceProvider(); string sales_licensekeys_privatekey = ConfigurationManager.AppSettings["sales_licensekeys_privatekey"]; if (!File.Exists(sales_licensekeys_privatekey)) throw new Exception("The private signing key is missing"); rsaKey.FromXmlString(System.IO.File.ReadAllText(sales_licensekeys_privatekey)); XmlDocument doc = new XmlDocument(); doc.PreserveWhitespace = true; doc.LoadXml(xml); SignedXml signedXml = new SignedXml(doc); signedXml.SigningKey = rsaKey; // Create a reference to be signed. Reference reference = new Reference(); reference.Uri = ""; // set to "" to sign the entire doc XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform(); reference.AddTransform(env); signedXml.AddReference(reference); signedXml.ComputeSignature(); XmlElement xmlDigitalSignature = signedXml.GetXml(); doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, true)); MemoryStream ms = new MemoryStream(); XmlTextWriter writer = new XmlTextWriter(ms, new UTF8Encoding(false)); writer = new XmlTextWriter(ms, new UTF8Encoding(false)); //writer.Formatting = Formatting.Indented; doc.WriteContentTo(writer); writer.Flush(); ms.Position = 0; StreamReader reader = new StreamReader(ms); return reader.ReadToEnd(); }