public static bool VerifySignature(string xml) { if (xml == null) throw new ArgumentNullException("xml"); XmlDocument doc = new XmlDocument(); doc.PreserveWhitespace = true; doc.LoadXml(xml); // If there's no signature => return that we are "valid" XmlNode signatureNode = findSignatureElement(doc); if (signatureNode == null) return true; SignedXml signedXml = new SignedXml(doc); signedXml.LoadXml((XmlElement)signatureNode); //var x509Certificates = signedXml.KeyInfo.OfType<KeyInfoX509Data>(); //var certificate = x509Certificates.SelectMany(cert => cert.Certificates.Cast<X509Certificate2>()).FirstOrDefault(); //if (certificate == null) throw new InvalidOperationException("Signature does not contain a X509 certificate public key to verify the signature"); //return signedXml.CheckSignature(certificate, true); return signedXml.CheckSignature(); }
// 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 bool IsValid() { bool status = false; XmlNamespaceManager manager = new XmlNamespaceManager(xmlDoc.NameTable); manager.AddNamespace("ds", SignedXml.XmlDsigNamespaceUrl); XmlNodeList nodeList = xmlDoc.SelectNodes("//ds:Signature", manager); SignedXml signedXml = new SignedXml(xmlDoc); signedXml.LoadXml((XmlElement)nodeList[0]); return signedXml.CheckSignature(certificate.cert, true); }
// Verify the signature of an XML file against an asymmetric // algorithm and return the result. public static Boolean VerifyXml(XmlDocument Doc, RSA Key) { // Check arguments. if (Doc == null) throw new ArgumentException("Doc"); if (Key == null) throw new ArgumentException("Key"); // Create a new SignedXml object and pass it // the XML document class. SignedXml signedXml = new SignedXml(Doc); // Find the "Signature" node and create a new // XmlNodeList object. XmlNodeList nodeList = Doc.GetElementsByTagName("Signature"); // Throw an exception if no signature was found. if (nodeList.Count <= 0) { throw new CryptographicException("Verification failed: No Signature was found in the document."); } // This example only supports one signature for // the entire XML document. Throw an exception // if more than one signature was found. if (nodeList.Count >= 2) { throw new CryptographicException("Verification failed: More that one signature was found for the document."); } // Load the first <signature> node. signedXml.LoadXml((XmlElement)nodeList[0]); // Check the signature and return the result. return signedXml.CheckSignature(Key); }
/// <summary> /// Obtém a assinatura de um objeto serializável /// </summary> /// <typeparam name="T"></typeparam> /// <param name="objeto"></param> /// <param name="id"></param> /// <param name="certificadoDigital">Informe o certificado digital</param> /// <param name="manterDadosEmCache">Validador para manter o certificado em cache</param> /// <param name="signatureMethod"></param> /// <param name="digestMethod"></param> /// <param name="cfgServicoRemoverAcentos"></param> /// <returns>Retorna um objeto do tipo Classes.Assinatura.Signature, contendo a assinatura do objeto passado como parâmetro</returns> public static Signature ObterAssinatura <T>(T objeto, string id, X509Certificate2 certificadoDigital, bool manterDadosEmCache = false, string signatureMethod = "http://www.w3.org/2000/09/xmldsig#rsa-sha1", string digestMethod = "http://www.w3.org/2000/09/xmldsig#sha1", bool cfgServicoRemoverAcentos = false) where T : class { var objetoLocal = objeto; if (id == null) { throw new Exception("Não é possível assinar um objeto evento sem sua respectiva Id!"); } try { var documento = new XmlDocument { PreserveWhitespace = true }; documento.LoadXml(cfgServicoRemoverAcentos ? FuncoesXml.ClasseParaXmlString(objetoLocal).RemoverAcentos() : FuncoesXml.ClasseParaXmlString(objetoLocal)); var docXml = new SignedXml(documento) { SigningKey = certificadoDigital.PrivateKey }; docXml.SignedInfo.SignatureMethod = signatureMethod; var reference = new Reference { Uri = "#" + id, DigestMethod = digestMethod }; // adicionando EnvelopedSignatureTransform a referencia var envelopedSigntature = new XmlDsigEnvelopedSignatureTransform(); reference.AddTransform(envelopedSigntature); var c14Transform = new XmlDsigC14NTransform(); reference.AddTransform(c14Transform); docXml.AddReference(reference); // carrega o certificado em KeyInfoX509Data para adicionar a KeyInfo var keyInfo = new KeyInfo(); keyInfo.AddClause(new KeyInfoX509Data(certificadoDigital)); docXml.KeyInfo = keyInfo; docXml.ComputeSignature(); //// recuperando a representação do XML assinado var xmlDigitalSignature = docXml.GetXml(); var assinatura = FuncoesXml.XmlStringParaClasse <Signature>(xmlDigitalSignature.OuterXml); return(assinatura); } finally { //Marcos Gerene 04/08/2018 - o objeto certificadoDigital nunca será nulo, porque se ele for nulo nem as configs para criar ele teria. //Se não mantém os dados do certificado em cache libera o certificado, chamando o método reset. //if (!manterDadosEmCache & certificadoDigital == null) // certificadoDigital.Reset(); } }
// 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 Key) { // Check arguments. if (xmlDoc == null) { throw new ArgumentException("xmlDoc"); } if (Key == null) { throw new ArgumentException("Key"); } // 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. 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. xmlDoc.DocumentElement.AppendChild(xmlDoc.ImportNode(xmlDigitalSignature, true)); }
// Sign an XML file and save the signature in a new file. public static void SignXmlFile(string FileName, string SignedFileName, RSA Key, string XSLString) { // 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; // 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); // Create an XmlDsigXPathTransform object using // the helper method 'CreateXPathTransform' defined // later in this sample. XmlDsigXsltTransform XsltTransform = CreateXsltTransform(XSLString); // Add the transform to the reference. reference.AddTransform(XsltTransform); // 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)); // 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 a XML file (enveloping signature) using a digital certificate /// </summary> /// <param name="xml">The XML data to sign represented as byte array</param> /// <param name="certFile">The certificate file to use for signing</param> /// <param name="certPassword">The certificate password</param> /// <param name="signWithSha256">Sign the document using SHA-256</param> /// <returns>The signed data represented as byte array</returns> private static byte[] SignEnvelopingXml(byte[] xml, string certFile, string certPassword, bool signWithSha256) { if (xml == null || xml.Length == 0) { // invalid XML array throw new Exception("Nothing to sign!"); } // load certificate X509Certificate2 certificate = LoadSigningCertificate(certFile, certPassword, signWithSha256); if (!certificate.HasPrivateKey) { // invalid certificate throw new Exception("Specified certificate not suitable for signing!"); } using (MemoryStream stream = new MemoryStream(xml)) { // go to the beginning of the stream stream.Flush(); stream.Position = 0; // create new XmlDocument from stream XmlDocument doc = new XmlDocument() { PreserveWhitespace = true }; doc.Load(stream); // craete transform (for canonicalization method & reference) XmlDsigExcC14NTransform transform = new XmlDsigExcC14NTransform(); // create new SignedXml from XmlDocument SignedXml signed = GenerateSignedXml(doc, certificate, signWithSha256); signed.SignedInfo.CanonicalizationMethod = transform.Algorithm; // get nodes (use XPath to include FATCA declaration) XmlNodeList nodes = doc.DocumentElement.SelectNodes("/*"); // define data object DataObject dataObject = new DataObject() { Data = nodes, Id = "FATCA" }; // add the data we are signing as a sub-element (object) of the signature element signed.AddObject(dataObject); // create reference Reference reference = new Reference(string.Format("#{0}", dataObject.Id)); reference.AddTransform(transform); if (signWithSha256) { // SHA-256 digest reference.DigestMethod = RSAPKCS1SHA256SignatureDescription.ReferenceDigestMethod; } // add reference to document signed.AddReference(reference); // include KeyInfo object & compute signature signed.KeyInfo = CreateKeyInfoFromCertificate(certificate); signed.ComputeSignature(); // get signature XmlElement xmlDigitalSignature = signed.GetXml(); // XML declaration string xmlDeclaration = string.Empty; if (doc.FirstChild is XmlDeclaration) { // include declaration xmlDeclaration = doc.FirstChild.OuterXml; } // return signature as byte array return(Encoding.UTF8.GetBytes(string.Concat(xmlDeclaration, xmlDigitalSignature.OuterXml))); } }
public SamlBodyResponse ProcessSamlResponse(SamlBodyResponse samlBodyRes) { var result = new SamlBodyResponse() { Success = true, AuthToken = string.Empty }; if (string.IsNullOrEmpty(samlBodyRes.SAMLResponse)) { return(AddResponseError(samlBodyRes, "Recebido pedido de autenticação inválido (SAMLResponse vazio)")); } #region XmlLoad byte[] reqDataB64 = Convert.FromBase64String(samlBodyRes.SAMLResponse); string reqData = Encoding.UTF8.GetString(reqDataB64); XmlDocument xml = new XmlDocument { PreserveWhitespace = true }; try { xml.LoadXml(reqData); } catch (XmlException ex) { return(AddResponseError(samlBodyRes, "Excepção ao carregar xml: " + ex.ToString())); } #endregion #region Xml signature validation string certificateB64 = xml.GetElementsByTagName("X509Certificate", "http://www.w3.org/2000/09/xmldsig#").Item(0).InnerText; X509Certificate2 certificate = new X509Certificate2(Convert.FromBase64String(certificateB64)); var chain = new X509Chain(); chain.ChainPolicy.RevocationFlag = X509RevocationFlag.ExcludeRoot; chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; chain.ChainPolicy.VerificationFlags = X509VerificationFlags.NoFlag; // sets the timeout for retrieving the certificate validation chain.ChainPolicy.UrlRetrievalTimeout = new TimeSpan(0, 1, 0); if (!chain.Build(certificate)) { return(AddResponseError(samlBodyRes, "Assinatura tem certificado inválido")); } if (!xml.PreserveWhitespace) { return(AddResponseError(samlBodyRes, "SAMLRequest não preserva espaços em branco")); } SignedXml signedXmlForValidation = new SignedXml(xml); XmlNodeList nodeList = xml.GetElementsByTagName("Signature", "http://www.w3.org/2000/09/xmldsig#"); if (nodeList.Count == 0) { return(AddResponseError(samlBodyRes, "SAMLRequest não está assinado.")); } signedXmlForValidation.LoadXml((XmlElement)nodeList[0]); if (!signedXmlForValidation.CheckSignature()) { return(AddResponseError(samlBodyRes, "Formato de mensagem desconhecido: " + xml.DocumentElement.LocalName)); } #endregion #region Schema validation if (EnableResponseSchemaValidation) { var validRes = ValidateSchema(xml, samlBodyRes); if (!validRes.Success) { return(validRes); } } #endregion #region Process saml response var reader = new XmlTextReader(new StringReader(xml.OuterXml)); //detectar tipo recebido: switch (xml.DocumentElement.LocalName.ToUpper()) { case "RESPONSE": return(ProcessResponse(samlBodyRes, xml, reader)); case "LOGOUTRESPONSE": return(ProcessLogoutResponse(samlBodyRes, xml, reader)); default: // tipo de resposta desconhecido ou não processável... return(AddResponseError(samlBodyRes, "Formato de mensagem desconhecido: " + xml.DocumentElement.LocalName)); } #endregion }
public static bool eval_a(string A_0, int A_1) { if (true) { } switch (0) { case 0: { IL_16: A_1 = 2; A_0 += eval_bw.eval_a(0); XmlDocument xmlDocument = new XmlDocument(); string text = ""; bool result; try { while (true) { xmlDocument.Load(A_0); SignedXml signedXml = new SignedXml(xmlDocument); XmlNode xmlNode = xmlDocument.GetElementsByTagName(eval_bw.a(), "http://www.w3.org/2000/09/xmldsig#")[0]; signedXml.LoadXml((XmlElement)xmlNode); int num = 7; while (true) { string text2; XmlNode xmlNode2; int num2; TimeSpan timeSpan; switch (num) { case 0: text2 = eval_bw.eval_a(A_1); xmlNode2 = xmlDocument.GetElementsByTagName(text2)[0]; num = 9; continue; case 1: goto IL_162; case 2: goto IL_167; case 3: if (num2 > 0) { num = 4; continue; } goto IL_1E6; case 4: result = true; num = 1; continue; case 5: if (A_1 == 0) { num = 2; continue; } goto IL_1E6; case 6: if (timeSpan.Hours > 22) { num = 10; continue; } goto IL_E4; case 7: if (signedXml.CheckSignature(global::eval_s.bc)) { num = 0; continue; } goto IL_1E6; case 8: goto IL_E4; case 9: if (A_1 != 2) { num = 11; continue; } goto IL_167; case 10: num2++; num = 8; continue; case 11: num = 5; continue; case 12: goto IL_1F2; } break; IL_E4: num = 3; continue; IL_167: text = text2 + " " + xmlNode2.InnerText; DateTime d = DateTime.Parse(text); DateTime now = DateTime.Now; timeSpan = d - now; num2 = timeSpan.Days; num = 6; continue; IL_1E6: num = 12; } } IL_162: return result; IL_1F2: goto IL_35; } catch { goto IL_35; } return result; IL_35: MessageBox.Show(A_0 + " " + text); File.Delete(A_0); return false; } } goto IL_16; }
// See: https://msdn.microsoft.com/en-us/library/ms148731(v=vs.110).aspx // See also: https://docs.microsoft.com/en-us/dotnet/standard/security/how-to-verify-the-digital-signatures-of-xml-documents // The code differs from the MSDN sample as it checks certificates against the root store instead. private bool IsSigned(string path, out X509Certificate2 signingCertificate) { signingCertificate = null; var xmlDoc = new XmlDocument() { PreserveWhitespace = true }; xmlDoc.Load(path); XmlNodeList signatureNodes = xmlDoc.GetElementsByTagName("Signature", SignedXml.XmlDsigNamespaceUrl); Log.WriteMessage(LogVerbosity.Diagnostic, SignCheckResources.XmlSignatureNodes, signatureNodes.Count); if (signatureNodes.Count == 0) { return(false); } var signedXml = new SignedXml(xmlDoc); signedXml.LoadXml((XmlElement)signatureNodes[0]); if (signedXml.Signature.KeyInfo.OfType <KeyInfoX509Data>().Count() == 0) { return(false); } ArrayList certificates = signedXml.Signature.KeyInfo.OfType <KeyInfoX509Data>().First().Certificates; foreach (X509Certificate2 certificate in certificates) { if (signedXml.CheckSignature(certificate, verifySignatureOnly: true)) { using (var rootStore = new X509Store(StoreName.Root)) { rootStore.Open(OpenFlags.IncludeArchived | OpenFlags.OpenExistingOnly | OpenFlags.ReadOnly); using (var chain = new X509Chain(useMachineContext: true)) { chain.Build(certificate); int numberOfChainElements = chain.ChainElements.Count; X509ChainElement rootChainElement = null; X500DistinguishedName subjectDistinguishedName = certificate.SubjectName; // Locate the last element in the the chain as that should be the root, otherwise use the certificate we have // and try to match that against a root certificate. if (numberOfChainElements > 0) { rootChainElement = chain.ChainElements[numberOfChainElements - 1]; subjectDistinguishedName = rootChainElement.Certificate.SubjectName; } X509Certificate2Collection rootCertificates = rootStore.Certificates; X509Certificate2Collection matchingRootCertificates = rootCertificates.Find(X509FindType.FindBySubjectDistinguishedName, subjectDistinguishedName.Name, validOnly: true); if (matchingRootCertificates.Count > 0) { signingCertificate = matchingRootCertificates[0]; } return(true); } } } } return(false); }
static bool ValidateXml(XmlDocument receipt, X509Certificate2 certificate) { // Create the signed XML object. SignedXml sxml = new SignedXml(receipt); // Get the XML Signature node and load it into the signed XML object. XmlNode dsig = receipt.GetElementsByTagName("Signature", SignedXml.XmlDsigNamespaceUrl)[0]; if (dsig == null) { // If signature is not found return false System.Console.WriteLine("Signature not found."); return false; } sxml.LoadXml((XmlElement)dsig); // Check the signature bool isValid = sxml.CheckSignature(certificate, true); FieldInfo field = sxml.GetType().GetField("m_signature", BindingFlags.NonPublic | BindingFlags.Instance); var sig = (Signature)field.GetValue(sxml); var _ref = (Reference)sig.SignedInfo.References[0]; //var pre = Type.GetType("System.Security.Cryptography.Xml.Utils").GetMethod("PreProcessDocumentInput"); //pre.Invoke(null, new[] { }); var enveloped = (XmlDsigEnvelopedSignatureTransform)_ref.TransformChain[0]; enveloped.LoadInput(receipt); var outputstream = enveloped.GetOutput(); var securityUrl = receipt.BaseURI; var resolver = new XmlSecureResolver(new XmlUrlResolver(), securityUrl); //TransformToOctetStream(Stream input, XmlResolver resolver, string baseUri) MethodInfo trans = _ref.TransformChain.GetType().GetMethods(BindingFlags.NonPublic | BindingFlags.Instance)[2]; var stream = trans.Invoke(_ref.TransformChain, new object[] {receipt, resolver, securityUrl}); var canontype = sig.GetType().Assembly.GetType("System.Security.Cryptography.Xml.CanonicalXml"); var foo = Activator.CreateInstance(canontype, BindingFlags.NonPublic | BindingFlags.Instance, null, new object[] {receipt, resolver}, null); MethodInfo method = _ref.GetType().GetMethod("CalculateHashValue", BindingFlags.NonPublic | BindingFlags.Instance); FieldInfo refs = sig.GetType().GetField("m_referencedItems", BindingFlags.NonPublic | BindingFlags.Instance); var refs1 = refs.GetValue(sig); var res = method.Invoke(_ref, new [] {receipt, refs1}); var str = Convert.ToBase64String((byte[])res); return isValid; }
/// <summary> /// Signs the specified xml document with the certificate found in /// the local machine matching the provided friendly name and /// referring to the specified target reference ID. /// </summary> /// <param name="certFriendlyName"> /// Friendly Name of the X509Certificate to be retrieved /// from the LocalMachine keystore and used to sign the xml document. /// Be sure to have appropriate permissions set on the keystore. /// </param> /// <param name="xmlDoc"> /// XML document to be signed. /// </param> /// <param name="targetReferenceId"> /// Reference element that will be specified as signed. /// </param> /// <param name="includePublicKey"> /// Flag to determine whether to include the public key in the /// signed xml. /// </param> public void SignXml(string certFriendlyName, IXPathNavigable xmlDoc, string targetReferenceId, bool includePublicKey) { if (string.IsNullOrEmpty(certFriendlyName)) { throw new Saml2Exception(Resources.SignedXmlInvalidCertFriendlyName); } if (xmlDoc == null) { throw new Saml2Exception(Resources.SignedXmlInvalidXml); } if (string.IsNullOrEmpty(targetReferenceId)) { throw new Saml2Exception(Resources.SignedXmlInvalidTargetRefId); } X509Certificate2 cert = _certificateFactory.GetCertificateByFriendlyName(certFriendlyName); if (cert == null) { throw new Saml2Exception(Resources.SignedXmlCertNotFound); } var xml = (XmlDocument)xmlDoc; var signedXml = new SignedXml(xml); signedXml.SigningKey = cert.PrivateKey; if (includePublicKey) { var keyInfo = new KeyInfo(); keyInfo.AddClause(new KeyInfoX509Data(cert)); signedXml.KeyInfo = keyInfo; } var reference = new Reference(); reference.Uri = "#" + targetReferenceId; var envelopSigTransform = new XmlDsigEnvelopedSignatureTransform(); reference.AddTransform(envelopSigTransform); signedXml.AddReference(reference); signedXml.ComputeSignature(); XmlElement xmlSignature = signedXml.GetXml(); var nsMgr = new XmlNamespaceManager(xml.NameTable); nsMgr.AddNamespace("ds", SignedXml.XmlDsigNamespaceUrl); nsMgr.AddNamespace("saml", Saml2Constants.NamespaceSamlAssertion); nsMgr.AddNamespace("samlp", Saml2Constants.NamespaceSamlProtocol); XmlNode issuerNode = xml.DocumentElement.SelectSingleNode("saml:Issuer", nsMgr); if (issuerNode != null) { xml.DocumentElement.InsertAfter(xmlSignature, issuerNode); } else { // Insert as a child to the target reference id XmlNode targetNode = xml.DocumentElement.SelectSingleNode("//*[@ID='" + targetReferenceId + "']", nsMgr); targetNode.PrependChild(xmlSignature); } }
public static void SaveCard(InformationCard card, X509Certificate2 cert, string filename) { MemoryStream stream = new MemoryStream(); XmlWriter writer = XmlWriter.Create(stream); writer.WriteStartElement("InformationCard", "http://schemas.xmlsoap.org/ws/2005/05/identity"); writer.WriteAttributeString("lang", "http://www.w3.org/XML/1998/namespace", "en-US"); writer.WriteStartElement("InformationCardReference", "http://schemas.xmlsoap.org/ws/2005/05/identity"); writer.WriteElementString("CardId", "http://schemas.xmlsoap.org/ws/2005/05/identity", card.CardReference.CardID); writer.WriteElementString("CardVersion", "http://schemas.xmlsoap.org/ws/2005/05/identity", card.CardReference.CardVersion.ToString()); writer.WriteEndElement(); if (card.CardName != null && card.CardName.Length > 0) { writer.WriteStartElement("CardName", "http://schemas.xmlsoap.org/ws/2005/05/identity"); writer.WriteString(card.CardName); writer.WriteEndElement(); } if (card.CardImage != null && card.CardImage.ImageName.Length > 0) { writer.WriteStartElement("CardImage", "http://schemas.xmlsoap.org/ws/2005/05/identity"); if (card.CardImage != null && card.CardImage.ImageMimeType != null && card.CardImage.ImageMimeType.Length > 0) { writer.WriteAttributeString("MimeType", card.CardImage.ImageMimeType); } FileInfo cardImage = new FileInfo(card.CardImage.ImageName); if (cardImage.Exists) { byte[] cardImageBytes = new byte[cardImage.Length]; using (FileStream imageFS = cardImage.OpenRead()) { imageFS.Read(cardImageBytes, 0, cardImageBytes.Length); } string imageBase64 = Convert.ToBase64String(cardImageBytes); writer.WriteString(imageBase64); writer.WriteEndElement(); } } writer.WriteStartElement("Issuer", "http://schemas.xmlsoap.org/ws/2005/05/identity"); writer.WriteString(card.Issuer); writer.WriteEndElement(); //writer.WriteStartElement("IssuerName", "http://schemas.xmlsoap.org/ws/2005/05/identity"); //writer.WriteString(card.IssuerName); //writer.WriteEndElement(); writer.WriteStartElement("TimeIssued", "http://schemas.xmlsoap.org/ws/2005/05/identity"); writer.WriteString(XmlConvert.ToString(card.TimeIssued, XmlDateTimeSerializationMode.Utc)); writer.WriteEndElement(); writer.WriteStartElement("TimeExpires", "http://schemas.xmlsoap.org/ws/2005/05/identity"); writer.WriteString(XmlConvert.ToString(card.TimeExpires, XmlDateTimeSerializationMode.Utc)); writer.WriteEndElement(); writer.WriteStartElement("TokenServiceList", "http://schemas.xmlsoap.org/ws/2005/05/identity"); foreach (TokenService ts in card.TokenServiceList) { EndpointAddressBuilder endpointBuilder = new EndpointAddressBuilder(); endpointBuilder.Uri = new Uri(ts.EndpointReference.Address); endpointBuilder.Identity = new X509CertificateEndpointIdentity(RetrieveCertificate(ts.EndpointReference.Identity)); if (null != ts.EndpointReference.Mex) { MetadataReference mexReference = new MetadataReference(); mexReference.Address = new EndpointAddress(ts.EndpointReference.Mex); mexReference.AddressVersion = AddressingVersion.WSAddressing10; MetadataSection mexSection = new MetadataSection(); mexSection.Metadata = mexReference; MetadataSet mexSet = new MetadataSet(); mexSet.MetadataSections.Add(mexSection); MemoryStream mexMemoryStream = new MemoryStream(); XmlTextWriter mexWriter = new XmlTextWriter(mexMemoryStream, System.Text.Encoding.UTF8); mexSet.WriteTo(mexWriter); mexWriter.Flush(); mexMemoryStream.Seek(0, SeekOrigin.Begin); XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(mexMemoryStream, XmlDictionaryReaderQuotas.Max); endpointBuilder.SetMetadataReader(reader); writer.WriteStartElement("TokenService", "http://schemas.xmlsoap.org/ws/2005/05/identity"); EndpointAddress endpoint = endpointBuilder.ToEndpointAddress(); endpoint.WriteTo(AddressingVersion.WSAddressing10, writer); writer.WriteStartElement("UserCredential", "http://schemas.xmlsoap.org/ws/2005/05/identity"); if (ts.UserCredential.DisplayCredentialHint != null && ts.UserCredential.DisplayCredentialHint.Length > 0) { writer.WriteStartElement("DisplayCredentialHint", "http://schemas.xmlsoap.org/ws/2005/05/identity"); writer.WriteString(ts.UserCredential.DisplayCredentialHint); writer.WriteEndElement(); } switch (ts.UserCredential.UserCredentialType) { case CredentialType.UsernameAndPassword: writer.WriteStartElement("UsernamePasswordCredential", "http://schemas.xmlsoap.org/ws/2005/05/identity"); if (!string.IsNullOrEmpty(ts.UserCredential.Value)) { writer.WriteStartElement("Username", "http://schemas.xmlsoap.org/ws/2005/05/identity"); writer.WriteString(ts.UserCredential.Value); writer.WriteEndElement(); } writer.WriteEndElement(); break; case CredentialType.Kerberos: writer.WriteStartElement("KerberosV5Credential", "http://schemas.xmlsoap.org/ws/2005/05/identity"); writer.WriteEndElement(); break; case CredentialType.SmartCard: writer.WriteStartElement("X509V3Credential", "http://schemas.xmlsoap.org/ws/2005/05/identity"); writer.WriteStartElement("X509Data", "http://www.w3.org/2000/09/xmldsig#"); if (!string.IsNullOrEmpty(ts.UserCredential.Value)) { writer.WriteStartElement("KeyIdentifier", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"); writer.WriteAttributeString("ValueType", null, "http://docs.oasis-open.org/wss/2004/xx/oasis-2004xx-wss-soap-message-security-1.1#ThumbprintSHA1"); writer.WriteString(RetrieveCertificate(ts.UserCredential.Value).Thumbprint); writer.WriteEndElement(); } else { throw new InvalidDataException("No thumbprint was specified"); } writer.WriteEndElement(); writer.WriteEndElement(); break; default: break; } writer.WriteEndElement(); writer.WriteEndElement(); } } writer.WriteEndElement(); //end of tokenservice list // // tokentypes // writer.WriteStartElement("SupportedTokenTypeList", "http://schemas.xmlsoap.org/ws/2005/05/identity"); foreach (TokenType tokenType in card.AcceptedTokenTypes) { writer.WriteElementString("TokenType", "http://schemas.xmlsoap.org/ws/2005/02/trust", tokenType.Uri); } writer.WriteEndElement(); // // claims // writer.WriteStartElement("SupportedClaimTypeList", "http://schemas.xmlsoap.org/ws/2005/05/identity"); foreach (CardClaim claim in card.SupportedClaimTypeList) { writer.WriteStartElement("SupportedClaimType", "http://schemas.xmlsoap.org/ws/2005/05/identity"); writer.WriteAttributeString("Uri", claim.Uri); if (!String.IsNullOrEmpty(claim.DisplayTag)) { writer.WriteElementString("DisplayTag", "http://schemas.xmlsoap.org/ws/2005/05/identity", claim.DisplayTag); } if (!String.IsNullOrEmpty(claim.Description)) { writer.WriteElementString("Description", "http://schemas.xmlsoap.org/ws/2005/05/identity", claim.Description); } writer.WriteEndElement(); } writer.WriteEndElement(); if (card.RequireRPIdentification) { writer.WriteElementString("RequireAppliesTo", "http://schemas.xmlsoap.org/ws/2005/05/identity", card.RequireRPIdentification.ToString()); } if (!String.IsNullOrEmpty(card.PrivacyNotice)) { writer.WriteStartElement("PrivacyNotice", "http://schemas.xmlsoap.org/ws/2005/05/identity"); writer.WriteString(card.PrivacyNotice); writer.WriteEndElement(); } writer.WriteEndElement(); writer.Close(); stream.Position = 0; XmlDocument doc = new XmlDocument(); doc.PreserveWhitespace = false; doc.Load(stream); SignedXml signed = new SignedXml(); signed.SigningKey = cert.PrivateKey; signed.Signature.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl; Reference reference = new Reference(); reference.Uri = "#_Object_InfoCard"; reference.AddTransform( new XmlDsigExcC14NTransform()); signed.AddReference(reference); KeyInfo info = new KeyInfo(); KeyInfoX509Data certData = new KeyInfoX509Data(cert, X509IncludeOption.WholeChain); info.AddClause(certData); signed.KeyInfo = info; DataObject cardData = new DataObject("_Object_InfoCard", null, null, doc.DocumentElement); signed.AddObject(cardData); signed.ComputeSignature(); XmlElement e = signed.GetXml(); XmlTextWriter fileWriter = new XmlTextWriter(filename, Encoding.UTF8); e.WriteTo(fileWriter); //doc.WriteTo(fileWriter); //Added fileWriter.Flush(); fileWriter.Close(); }
// Sign an XML file and save the signature in a new file. public static void SignXmlFile(XmlDocument doc, string signedFileName, RSA key) { // Check the arguments. if (doc == null) { throw new ArgumentNullException("doc"); } if (signedFileName == null) { throw new ArgumentNullException("signedFileName"); } if (key == null) { throw new ArgumentNullException("key"); } // Format the document to ignore white spaces. doc.PreserveWhitespace = false; // Create a SignedXml object. SignedXml signedXml = new SignedXml(doc) { // Add the key to the SignedXml document. SigningKey = key }; // Create a reference to be signed. Reference reference = new Reference { Uri = string.Empty }; // 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(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. if (doc.DocumentElement != null) { 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 string RetornarXmlFirmado(string xmlString, string rutaCertificado, string claveCertificado, out string hash) //{ // hash = null; // XmlDocument documentXml = new XmlDocument(); // documentXml.PreserveWhitespace = true; // documentXml.LoadXml(xmlString); // var nodoExtension = documentXml.GetElementsByTagName("ExtensionContent", "urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2").Item(0); // if (nodoExtension == null) // { // throw new InvalidOperationException("No se pudo encontrar el nodo ExtensionContent en el XML"); // } // nodoExtension.RemoveAll(); // SignedXml firmado = new SignedXml(documentXml); // var xmlSignature = firmado.Signature; // byte[] certificadoByte = File.ReadAllBytes(rutaCertificado); // X509Certificate2 certificado = new X509Certificate2(); // //certificado.Import(certificadoByte, claveCertificado, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable); // certificado.Import(certificadoByte, claveCertificado, X509KeyStorageFlags.Exportable); // firmado.SigningKey = certificado.GetRSAPrivateKey(); // //firmado.SigningKey = (RSA)certificado.PrivateKey; // //firmado.SigningKey = certificado.PrivateKey; // //digest info agregada en la seccion firma // var env = new XmlDsigEnvelopedSignatureTransform(); // Reference reference = new Reference(); // reference.AddTransform(env); // reference.Uri = ""; // firmado.AddReference(reference); // firmado.SignedInfo.SignatureMethod = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"; // reference.DigestMethod = "http://www.w3.org/2001/04/xmlenc#sha256"; // var keyInfoData = new KeyInfoX509Data(certificado); // keyInfoData.AddSubjectName(certificado.Subject); // // info para la llave publica // KeyInfo keyInfo = new KeyInfo(); // keyInfo.AddClause(keyInfoData); // //keyInfo.sub // xmlSignature.KeyInfo = keyInfo; // xmlSignature.Id = "signatureKG"; // firmado.ComputeSignature(); // // Recuperamos el valor Hash de la firma para este documento. // if (reference.DigestValue != null) // { // hash = Convert.ToBase64String(reference.DigestValue); // } // XmlNode xmlNodeFirmado = firmado.GetXml(); // xmlNodeFirmado.Prefix = "ds"; // //XmlNode xmlNodeContent = documentXml.CreateElement("ext", "ExtensionContent", "urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2"); // //xmlNodeContent.AppendChild(xmlNodeFirmado); // //XmlNode xmlNode = documentXml.CreateElement("ext", "UBLExtension", "urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2"); // //xmlNode.AppendChild(xmlNodeContent); // nodoExtension.AppendChild(xmlNodeFirmado); // var settings = new XmlWriterSettings() // { // Encoding = Encoding.UTF8, // Indent = true, // IndentChars = "\t", // NewLineChars = Environment.NewLine // }; // string resultado = String.Empty; // using (var memDoc = new MemoryStream()) // { // using (var writer = XmlWriter.Create(memDoc, settings)) // { // //XDocument xDocument = XDocument.Parse(documentXml.OuterXml); // //xDocument.WriteTo(writer); // documentXml.WriteTo(writer); // } // //resultado = Encoding.Unicode.GetString(memDoc.ToArray()); // //resultado = Encoding.GetEncoding("ISO-8859-1").GetString(memDoc.ToArray()); // //resultado = Convert.ToBase64String(memDoc.ToArray()); // resultado = Encoding.UTF8.GetString(memDoc.ToArray()); // } // return resultado; //} public static string RetornarXmlFirmado(string prefijoComprobanteBusqueda, string tnsString, string xmlString, string rutaCertificado, string claveCertificado, out string hash) { hash = null; XmlDocument xmlDocument = new XmlDocument(); xmlDocument.PreserveWhitespace = true; xmlDocument.LoadXml(xmlString); X509Certificate2 certificado = new X509Certificate2(rutaCertificado, claveCertificado); XmlNamespaceManager nsMgr = new XmlNamespaceManager(xmlDocument.NameTable); nsMgr.AddNamespace("tns", tnsString); nsMgr.AddNamespace("ext", "urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2"); XmlElement elem = xmlDocument.CreateElement("ext:ExtensionContent", "urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2"); xmlDocument.SelectSingleNode($"{prefijoComprobanteBusqueda}/ext:UBLExtensions/ext:UBLExtension", nsMgr).AppendChild(elem); SignedXml signedXml = new SignedXml(xmlDocument); signedXml.SigningKey = certificado.GetRSAPrivateKey(); System.Security.Cryptography.Xml.KeyInfo KeyInfo = new System.Security.Cryptography.Xml.KeyInfo(); System.Security.Cryptography.Xml.Reference Reference = new System.Security.Cryptography.Xml.Reference(); Reference.Uri = ""; Reference.AddTransform(new XmlDsigEnvelopedSignatureTransform()); signedXml.AddReference(Reference); X509Chain X509Chain = new X509Chain(); X509Chain.Build(certificado); X509ChainElement local_element = X509Chain.ChainElements[0]; KeyInfoX509Data x509Data = new KeyInfoX509Data(local_element.Certificate); string subjectName = local_element.Certificate.Subject; x509Data.AddSubjectName(subjectName); KeyInfo.AddClause(x509Data); signedXml.Signature.Id = "signatureKG"; signedXml.KeyInfo = KeyInfo; signedXml.ComputeSignature(); XmlElement signature = signedXml.GetXml(); XmlNode dg = signature.GetElementsByTagName("DigestValue", "http://www.w3.org/2000/09/xmldsig#")[0]; XmlNode sg = signature.GetElementsByTagName("SignatureValue", "http://www.w3.org/2000/09/xmldsig#")[0]; hash = dg.InnerText; //SignatureValue = sg.InnerText; signature.Prefix = "ds"; //SetPrefix("ds", signature); elem.AppendChild(signature); MemoryStream msXMLFirmado = new MemoryStream(); xmlDocument.Save(msXMLFirmado); //msXMLFirmado.Position = 1; return(Encoding.UTF8.GetString(msXMLFirmado.ToArray()).Substring(1)); }
/// <summary> /// Assinar digitalmente o XML /// </summary> /// <param name="conteudoXML">XML a ser assinado</param> /// <param name="tagAssinatura">Nome da tag a ser assinada</param> /// <param name="tagAtributoId">Nome da tag que possui o ID para referencia na URI da assinatura</param> /// <param name="x509Cert">Certificado digital a ser utilizado na assinatura</param> /// <param name="algorithmType">Tipo de algorítimo a ser utilizado na assinatura</param> /// <param name="definirURI">Define o Reference.URI na assinatura</param> /// <param name="pinCertificado">PIN do certificado digital, quando do tipo A3</param> /// <param name="idAttributeName">Nome do atributo que tem o ID para assinatura. Se nada for passado o sistema vai tentar buscar o nome Id ou id, se não encontrar, não vai criar a URI Reference na assinatura com ID.</param> public void Assinar(XmlDocument conteudoXML, string tagAssinatura, string tagAtributoId, X509Certificate2 x509Cert, AlgorithmType algorithmType = AlgorithmType.Sha1, bool definirURI = true, string pinCertificado = "", string idAttributeName = "") { try { if (x509Cert == null) { throw new ExceptionCertificadoDigital(); } if (conteudoXML.GetElementsByTagName(tagAssinatura).Count == 0) { throw new Exception("A tag de assinatura " + tagAssinatura.Trim() + " não existe no XML. (Código do Erro: 5)"); } else if (conteudoXML.GetElementsByTagName(tagAtributoId).Count == 0) { throw new Exception("A tag de assinatura " + tagAtributoId.Trim() + " não existe no XML. (Código do Erro: 4)"); } else { XmlNodeList lists = conteudoXML.GetElementsByTagName(tagAssinatura); foreach (XmlNode nodes in lists) { foreach (XmlNode childNodes in nodes.ChildNodes) { if (!childNodes.Name.Equals(tagAtributoId)) { continue; } // Create a reference to be signed Reference reference = new Reference { Uri = "" }; // pega o uri que deve ser assinada XmlElement childElemen = (XmlElement)childNodes; if (definirURI) { if (string.IsNullOrEmpty(idAttributeName)) { if (childElemen.GetAttributeNode("Id") != null) { idAttributeName = "Id"; } else if (childElemen.GetAttributeNode("id") != null) { idAttributeName = "id"; } } else { reference.Uri = "#" + childElemen.GetAttributeNode(idAttributeName).Value; } } SignedXml signedXml = new SignedXml(conteudoXML); if (!string.IsNullOrWhiteSpace(pinCertificado)) { x509Cert.SetPinPrivateKey(pinCertificado); } reference.AddTransform(new XmlDsigEnvelopedSignatureTransform()); reference.AddTransform(new XmlDsigC14NTransform()); switch (algorithmType) { case AlgorithmType.Sha256: signedXml.SignedInfo.SignatureMethod = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"; signedXml.SigningKey = x509Cert.GetRSAPrivateKey(); signedXml.SignedInfo.SignatureMethod = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"; reference.DigestMethod = "http://www.w3.org/2001/04/xmlenc#sha256"; break; default: signedXml.SigningKey = x509Cert.PrivateKey; signedXml.SignedInfo.SignatureMethod = "http://www.w3.org/2000/09/xmldsig#rsa-sha1"; reference.DigestMethod = "http://www.w3.org/2000/09/xmldsig#sha1"; break; } signedXml.AddReference(reference); KeyInfo keyInfo = new KeyInfo(); keyInfo.AddClause(new KeyInfoX509Data(x509Cert)); signedXml.KeyInfo = keyInfo; signedXml.ComputeSignature(); XmlElement xmlDigitalSignature = signedXml.GetXml(); nodes.AppendChild(conteudoXML.ImportNode(xmlDigitalSignature, true)); } } } } catch (CryptographicException ex) { if (x509Cert.IsA3()) { throw new Exception("O certificado deverá ser reiniciado.\r\n Retire o certificado.\r\nAguarde o LED terminar de piscar.\r\n Recoloque o certificado e informe o PIN novamente.\r\n" + ex.ToString()); } else { throw; } } catch { throw; } }
static void Symmetric (string filename, byte[] key) { string shortName = Path.GetFileName (filename); XmlDocument doc = new XmlDocument (); doc.PreserveWhitespace = true; XmlTextReader xtr = new XmlTextReader (GetReader (filename)); XmlValidatingReader xvr = new XmlValidatingReader (xtr); xtr.Normalization = true; doc.Load (xvr); try { XmlNodeList nodeList = doc.GetElementsByTagName ("Signature", SignedXml.XmlDsigNamespaceUrl); XmlElement signature = (XmlElement) nodeList [0]; SignedXml s = new SignedXml (); s.LoadXml (signature); HMACSHA1 mac = new HMACSHA1 (key); if (s.CheckSignature (mac)) { Console.WriteLine ("valid {0}", shortName); valid++; } else { Console.WriteLine ("INVALID {0}", shortName); invalid++; } } catch (Exception ex) { Console.WriteLine ("EXCEPTION " + shortName + " " + ex); error++; } }
internal static LicenseInfo Verify(string signedXml, Action <string, string> messageReporterFunc, Action <string, string> errorDisplayFunc, Action <string, string> noLicenseFoundReporterFunc, DateTime nullDate, string publicKey) { LicenseInfo licenseInfo; SignedXml signedXml1 = new SignedXml(); using (RSACryptoServiceProvider rSACryptoServiceProvider = new RSACryptoServiceProvider()) { rSACryptoServiceProvider.FromXmlString(publicKey); if (!string.IsNullOrEmpty(signedXml)) { XmlDocument xmlDocument = new XmlDocument() { PreserveWhitespace = true }; xmlDocument.LoadXml(signedXml); XmlNodeList elementsByTagName = xmlDocument.GetElementsByTagName("Signature"); signedXml1.LoadXml((XmlElement)elementsByTagName[0]); if (signedXml1.CheckSignature(rSACryptoServiceProvider)) { LicenseInfo licenseInfo1 = LicenseInfo.CreateLicenseInfo(xmlDocument.SelectSingleNode(".//LLBLGenProLicense")); switch (licenseInfo1.TypeOfLicense) { case LicenseType.Trial: case LicenseType.Beta: { if (!licenseInfo1.Expires) { if (errorDisplayFunc != null) { errorDisplayFunc("The license file is invalid", "Invalid license file"); } licenseInfo1 = null; goto case LicenseType.Lite; } else { if (!(licenseInfo1.LicenseCreationDateTimeUTC > DateTime.UtcNow) && !(licenseInfo1.ExpirationDateUTC < DateTime.UtcNow.ToUniversalDate()) && !(nullDate > DateTime.UtcNow)) { goto case LicenseType.Lite; } if (messageReporterFunc != null) { LicenseType typeOfLicense = licenseInfo1.TypeOfLicense; messageReporterFunc(string.Format("The {0} period has ended as your license has expired.", typeOfLicense.ToString().ToLowerInvariant()), "License expired"); } licenseInfo1 = null; goto case LicenseType.Lite; } } case LicenseType.Normal: { DateTime linkerTimeUTC = typeof(Project).Assembly.GetLinkerTimeUTC(); if (linkerTimeUTC <= licenseInfo1.SubscriptionEndDateUTC) { goto case LicenseType.Lite; } if (messageReporterFunc != null) { string str = linkerTimeUTC.ToString("dd-MMM-yyyy"); DateTime subscriptionEndDateUTC = licenseInfo1.SubscriptionEndDateUTC; messageReporterFunc(string.Format("Sorry, but this build isn't allowed to be used with your license as it was released after your subscription expired (Build is from {0}, your subscription expired on {1}). Please renew your subscription to use this build and newer builds, or go to the LLBLGen Pro website and download a build released before {1}.", str, subscriptionEndDateUTC.ToString("dd-MMM-yyyy")), "Build is incompatible with expired subscription"); } licenseInfo1 = null; goto case LicenseType.Lite; } case LicenseType.Lite: { licenseInfo = licenseInfo1; break; } default: { goto case LicenseType.Lite; } } } else { if (errorDisplayFunc != null) { errorDisplayFunc("The license file signature is invalid", "Invalid license file"); } licenseInfo = null; } } else { if (noLicenseFoundReporterFunc != null) { noLicenseFoundReporterFunc("No license files found. Please install your LLBLGen Pro license file in the application's folder and restart the application. If you downloaded the trial version, be sure to request a trial license. You can request one on the LLBLGen Pro website or by clicking the 'Request Trial License' button below.", "No license file found"); } licenseInfo = null; } } return(licenseInfo); }
/// <summary> /// Validate script XML signature /// </summary> /// <param name="signedXml">Signed XML</param> /// <returns>true if signature is valid</returns> public virtual bool VerifyXmlSignature(SignedXml signedXml) { bool valid = false; foreach (var k in signedXml.KeyInfo) { var kv = k as RSAKeyValue; if (kv != null) { var rsa = new RSACryptoServiceProvider(); var key = Assembly.GetExecutingAssembly().GetName().GetPublicKey(); if (key == null || key.Length < 12) { return(false); } // here is a trick: the public key in assembly file has a 12-byte header at the beginning. // We strip it - and the remaining bytes can be now imported by RSACryptoServiceProvider class var tmpKey = new byte[key.Length - 12]; Array.Copy(key, 12, tmpKey, 0, tmpKey.Length); rsa.ImportCspBlob(tmpKey); valid = signedXml.CheckSignature(rsa); if (!valid) { break; } continue; } var ki = k as KeyInfoX509Data; if (ki != null) { if (ki.Certificates == null) { valid = false; } else { foreach (X509Certificate2 cert in ki.Certificates) { // Verify that certificate is trusted for code signing X509ChainPolicy pol = new X509ChainPolicy(); pol.RevocationMode = X509RevocationMode.NoCheck; pol.VerificationFlags = X509VerificationFlags.IgnoreEndRevocationUnknown | X509VerificationFlags.IgnoreCertificateAuthorityRevocationUnknown | X509VerificationFlags.IgnoreRootRevocationUnknown; pol.ApplicationPolicy.Add(new Oid("1.3.6.1.5.5.7.3.3")); X509Chain chain = new X509Chain(true); chain.ChainPolicy = pol; if (chain.Build(cert)) { valid = signedXml.CheckSignature(cert, true); } if (!valid) { break; } } } if (!valid) { break; } continue; } } return(valid); }
// authenticate and map supporting tokens to proper SupportingTokenSpecification list. void ProcessSupportingTokens(SignedXml sxml) { List <SupportingTokenInfo> tokens = new List <SupportingTokenInfo> (); // First, categorize those tokens in the Security // header: // - Endorsing signing // - Signed signed // - SignedEncrypted signed encrypted // - SignedEndorsing signing signed foreach (object obj in wss_header.Contents) { SecurityToken token = obj as SecurityToken; if (token == null) { continue; } bool signed = false, endorsing = false, encrypted = false; // signed foreach (Reference r in sxml.SignedInfo.References) { if (r.Uri.Substring(1) == token.Id) { signed = true; break; } } // FIXME: how to get 'encrypted' state? // FIXME: endorsing SecurityTokenAttachmentMode mode = signed ? encrypted ? SecurityTokenAttachmentMode.SignedEncrypted : endorsing ? SecurityTokenAttachmentMode.SignedEndorsing : SecurityTokenAttachmentMode.Signed : SecurityTokenAttachmentMode.Endorsing; tokens.Add(new SupportingTokenInfo(token, mode, false)); } // then, // 1. validate every mandatory supporting token // parameters (Endpoint-, Operation-). To do that, // iterate all tokens in the header against every // parameter in the mandatory list. // 2. validate every token that is not validated. // To do that, iterate all supporting token parameters // and check if any of them can validate it. SupportingTokenParameters supp; string action = GetAction(); if (action == null) { throw new ArgumentException("SOAP action could not be retrieved from the message to decrypt."); } ValidateTokensByParameters(security.Element.EndpointSupportingTokenParameters, tokens, false); if (security.Element.OperationSupportingTokenParameters.TryGetValue(action, out supp)) { ValidateTokensByParameters(supp, tokens, false); } ValidateTokensByParameters(security.Element.OptionalEndpointSupportingTokenParameters, tokens, true); if (security.Element.OptionalOperationSupportingTokenParameters.TryGetValue(action, out supp)) { ValidateTokensByParameters(supp, tokens, true); } }
// 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 using ceritificate file. //X509Certificate2 certificate; //using (FileStream fs = // File.Open(CERT_FILE, FileMode.Open)) //using (BinaryReader br = new BinaryReader(fs)) //{ // certificate = // new X509Certificate2( // br.ReadBytes((int)br.BaseStream.Length), "demo"); //} //signedXml.SigningKey = certificate.PrivateKey; // Add the key to the SignedXml document using pre-shared key. signedXml.SigningKey = Key; signedXml.SignedInfo.SignatureMethod = SIGNATURE_ALG; // Create a reference to be signed. Reference reference = new Reference(); reference.Uri = ""; // Add an enveloped transformation to the reference. reference.AddTransform(new XmlDsigEnvelopedSignatureTransform()); reference.AddTransform(new XmlDsigExcC14NTransform()); reference.DigestMethod = SIGNATURE_DIG; // If you are using certificate, use code below, // and pass the certificate as parameter. //KeyInfo keyInfo = new KeyInfo(); //KeyInfoX509Data keyInfoData = new KeyInfoX509Data(certificate); //keyInfo.AddClause(keyInfoData); //signedXml.KeyInfo = keyInfo; // 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)); // 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(); }
// dump methods under construction ;-) static void DumpSignedXml (SignedXml s) { Console.WriteLine ("*** SignedXml ***"); Console.WriteLine (s.SigningKeyName); Console.WriteLine (s.SigningKey); if (s.Signature != null) DumpSignature (s.Signature); if (s.SignedInfo != null) DumpSignedInfo (s.SignedInfo); Console.WriteLine (s.SignatureMethod); Console.WriteLine (s.SignatureLength); Console.WriteLine (s.SignatureValue); if (s.KeyInfo != null) DumpKeyInfo (s.KeyInfo); }
static int Main(string[] args) { // Verify that an XML document path is provided. if (args.Length != 1 || !File.Exists(args[0])) { Console.Error.WriteLine("Error: You must provide the path to an XML " + "document to sign."); return(1); } // Load the license request file. XmlDocument xmldoc = new XmlDocument(); xmldoc.Load(args[0]); // Get the key pair from the key store. CspParameters parms = new CspParameters(1); // PROV_RSA_FULL parms.Flags = CspProviderFlags.UseMachineKeyStore; // Use Machine store parms.KeyContainerName = "CodeProject"; // "CodeProject" container parms.KeyNumber = 2; // AT_SIGNATURE RSACryptoServiceProvider csp = new RSACryptoServiceProvider(parms); // Creating the XML signing object. SignedXml sxml = new SignedXml(xmldoc); sxml.SigningKey = csp; // Set the canonicalization method for the document. sxml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigCanonicalizationUrl; // No comments. // Create an empty reference (not enveloped) for the XPath // transformation. Reference r = new Reference(""); // Create the XPath transform and add it to the reference list. r.AddTransform(new XmlDsigEnvelopedSignatureTransform(false)); // Add the reference to the SignedXml object. sxml.AddReference(r); // Compute the signature. sxml.ComputeSignature(); // Get the signature XML and add it to the document element. XmlElement sig = sxml.GetXml(); xmldoc.DocumentElement.AppendChild(sig); // Write-out formatted signed XML to console (allow for redirection). XmlTextWriter writer = new XmlTextWriter(Console.Out); writer.Formatting = Formatting.Indented; try { xmldoc.WriteTo(writer); } finally { writer.Flush(); writer.Close(); } return(0); }
// 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) { //var cspParams = new CspParameters { KeyContainerName = "XML_DSIG_RSA_KEY" }; //var key = new RSACryptoServiceProvider(cspParams); //var blob = key..ExportCspBlob(true); //var cert = new X509Certificate2(blob); //File.WriteAllBytes("Hello.cer", cert.Export(X509ContentType.Cert)); var cert = new X509Certificate2("certificate.pfx"); var privateKey = cert.PrivateKey as RSACryptoServiceProvider; // 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 = privateKey; // 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); var keyInfo = new KeyInfo(); keyInfo.AddClause(new RSAKeyValue(cert.PublicKey.Key as RSACryptoServiceProvider)); 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(); }
/// <summary> /// Assinar o documento XML digitalmente /// </summary> /// <param name="FilePath"></param> /// <param name="pUri"></param> /// <param name="oX509Certificate2"></param> /// <returns>XML assinado</returns> public string AssinarDocumentoXML(string FilePath, string pUri, X509Certificate2 oX509Certificate2) { var XML = File.ReadAllText(FilePath); try { var oX509Cert = new X509Certificate2(); var oX509Store = new X509Store("MY", StoreLocation.CurrentUser); oX509Store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly); var collection = oX509Store.Certificates; var collection1 = collection.Find(X509FindType.FindBySubjectDistinguishedName, oX509Certificate2.Subject.ToString(), false); if (collection1.Count == 0) { throw new Exception("Framework: Problemas no certificado digital."); } else { oX509Cert = collection1[0]; string x = oX509Cert.GetKeyAlgorithm().ToString(); // Create a new XML document. var oXML = new XmlDocument(); // Format the document to ignore white spaces. oXML.PreserveWhitespace = false; // Load the passed XML file using it’s name. try { oXML.LoadXml(XML); // cheching the elemento will be sign int qtdeRefUri = oXML.GetElementsByTagName(pUri).Count; if (qtdeRefUri == 0) { throw new Exception("Framework: A tag de assinatura " + pUri.Trim() + " não existe"); } else { if (qtdeRefUri > 1) { throw new Exception("Framework: A tag de assinatura " + pUri.Trim() + " não é unica"); } else { try { // Create a SignedXml object. SignedXml signedXml = new SignedXml(oXML); // Add the key to the SignedXml document signedXml.SigningKey = oX509Cert.PrivateKey; // Create a reference to be signed Reference reference = new Reference(); XmlAttributeCollection _Uri = oXML.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(oX509Cert)); // Add the KeyInfo object to the SignedXml object. signedXml.KeyInfo = keyInfo; signedXml.ComputeSignature(); // Get the XML representation of the signature and save // it to an XmlElement object. XmlElement xmlDigitalSignature = signedXml.GetXml(); // save element on XML oXML.DocumentElement.AppendChild(oXML.ImportNode(xmlDigitalSignature, true)); XmlDocument XMLDoc = new XmlDocument(); XMLDoc.PreserveWhitespace = false; XMLDoc = oXML; // XML document already signed XML = XMLDoc.OuterXml; oXML = null; signedXml = null; env = null; c14 = null; } catch (Exception oError) { throw new Exception("Framework: Erro ao assinar o documento XML." + oError.Message); } } } } catch (Exception oError) { throw new Exception("Framework: XML mal formatado." + oError.Message); } } } catch (Exception oError) { throw new Exception("Framework: Problema ao acessar o certificado digital." + oError.Message); } return(XML); }
public static bool VerifyPackageSignature(String xml) { XmlDocument xmlDocument = new XmlDocument(); xmlDocument.PreserveWhitespace = true; xmlDocument.Load(new XmlTextReader(xml)); XmlElement signatureElement = (XmlElement)xmlDocument.GetElementsByTagName("Signature")[0]; XmlElement signedInfo = (XmlElement)signatureElement.GetElementsByTagName("SignedInfo")[0]; byte[] signedInfoByteRange = CalculateC14nByteRange(signedInfo, xmlDocument); XmlNodeList references = signatureElement.GetElementsByTagName("Reference"); foreach (XmlElement reference in references) { String uri = reference.GetAttribute("URI"); if (String.IsNullOrEmpty(uri)) // main reference { signatureElement.ParentNode.RemoveChild(signatureElement); XmlNodeList transforms = signatureElement.GetElementsByTagName("Transform"); if (transforms.Count > 1) // second transform is Xpath Filter 2.0 { XmlElement xpathFilterTransform = (XmlElement)transforms[1]; XmlNamespaceManager namespaceManager = new XmlNamespaceManager(new NameTable()); namespaceManager.AddNamespace("xdp", "http://ns.adobe.com/xdp/"); XmlNodeList nodelist = xmlDocument.SelectNodes(xpathFilterTransform.InnerText, namespaceManager); if (!VerifyElement((XmlElement)nodelist[0], xmlDocument, reference)) { return(false); } //for correct work with SignedXml class xpathFilterTransform.ParentNode.RemoveChild(xpathFilterTransform); } else { if (!VerifyElement(null, xmlDocument, reference)) { return(false); } } // revert xmlDocument.DocumentElement.AppendChild(signatureElement); } else // SignedProperties reference { XmlElement signedProperties = (XmlElement)signatureElement.GetElementsByTagName("xades:SignedProperties")[0]; if (!VerifyElement(signedProperties, xmlDocument, reference)) { return(false); } } } SignedXml signedXml = new SignedXml(xmlDocument); signedXml.LoadXml(signatureElement); IEnumerator keyInfoClauses = signedXml.KeyInfo.GetEnumerator(); keyInfoClauses.MoveNext(); KeyInfoClause keyInfo = (KeyInfoClause)keyInfoClauses.Current; bool result = false; if (keyInfo is RSAKeyValue) { result = ((RSACryptoServiceProvider)((RSAKeyValue)keyInfo).Key).VerifyData(signedInfoByteRange, "SHA1", signedXml.SignatureValue); } else if (keyInfo is KeyInfoX509Data) { AsymmetricAlgorithm rsa = ((X509Certificate2)(((KeyInfoX509Data)keyInfo).Certificates[0])).PublicKey.Key; result = ((RSACryptoServiceProvider)rsa).VerifyData(signedInfoByteRange, "SHA1", signedXml.SignatureValue); } return(result); }
//tutorial - https://www.asptricks.net/2015/09/sign-xmldocument-with-x509certificate2.html internal static XmlDocument GetSignedXMLDocument(XmlDocument xmlDocument, X509Certificate2 certificate, long procedureSerial = -1, string reason = "") { //Before signing, should check if current document sign is valid or not, if current document is invalid, then new sign should not be added - not implemented yet, but should be if (CheckIfDocumentPreviouslySigned(xmlDocument)) { bool?isLastSignVerified = VerifyLastSign(xmlDocument); if (isLastSignVerified == false) { MessageBox.Show("The file was TEMPERED after last sign !!"); return(null); //Last Sign Not Verified } } //Then sign the xml try { //MessageBox.Show(certificate.Subject); SignedXml signedXml = new SignedXml(xmlDocument); signedXml.SigningKey = certificate.PrivateKey; // Create a reference to be signed Reference reference = new Reference(); ///////////////////// reference.Uri = ""; //"#" + procedureSerial; //reference.Type = reason; //reference.Id = DateTime.UtcNow.Ticks.ToString(); Tsa tsa = new Tsa(); string signedTsaString = tsa.GetSignedHashFromTsa(xmlDocument); DateTime?tsaTime = Tsa.GetTsaTimeFromSignedHash(signedTsaString); //reference.Id = Base64EncodedCurrentTime(tsaTime); reference.Id = signedTsaString; //bool status = Tsa.ValidateTimestamp(xmlDocument, reference.Id); //reference.TransformChain = ; ///////////////////// // Add an enveloped transformation to the reference. XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform(true); reference.AddTransform(env); // Add the reference to the SignedXml object. signedXml.AddReference(reference); //canonicalize XmlDsigC14NTransform c14t = new XmlDsigC14NTransform(); reference.AddTransform(c14t); KeyInfo keyInfo = new KeyInfo(); KeyInfoX509Data keyInfoData = new KeyInfoX509Data(certificate); KeyInfoName kin = new KeyInfoName(); //kin.Value = "Public key of certificate"; kin.Value = certificate.FriendlyName; RSA rsa = (RSA)certificate.PublicKey.Key; RSAKeyValue rkv = new RSAKeyValue(rsa); keyInfo.AddClause(rkv); keyInfo.AddClause(kin); keyInfo.AddClause(keyInfoData); signedXml.KeyInfo = keyInfo; //////////////////////////////////////////Add Other Data as we need//// // Add the data object to the signature. //CreateMetaDataObject("Name", GetNetworkTime()); signedXml.AddObject(CreateMetaDataObject(procedureSerial, reason)); /////////////////////////////////////////////////////////////////////// // 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) ); ///////////////////// } catch (Exception exception) { MessageBox.Show("Internal System Error during sign"); throw exception; } return(xmlDocument); }
public int AssinarNFE(string xml, string cnpj, string tagName) { try { xml = alteraCaracter(xml, 1); xmlAssinado = String.Empty; if (xCert == null) { xCert = selectCert(cnpj); } if (xCert != null) { xml = xml.Replace("\r\n", ""); string tagNameID = ""; if (tagName == "NFe") { tagNameID = "infNFe"; } else if (tagName == "inutNFe") { tagNameID = "infInut"; } else { tagNameID = "infEvento"; } XmlDocument docRequest = new XmlDocument(); docRequest.PreserveWhitespace = false; string docXML = String.Empty; if (xml.StartsWith("<")) { docXML = xml.ToString(); } else { docXML = File.ReadAllText(xml); } docRequest.LoadXml(remove_non_ascii(removeAcentuacao(docXML.ToString()))); XmlNodeList ListInfNFe = docRequest.GetElementsByTagName(tagNameID); foreach (XmlElement infNFe in ListInfNFe) { string id = infNFe.Attributes.GetNamedItem("Id").InnerText; signedXml = new SignedXml(infNFe); signedXml.SigningKey = xCert.PrivateKey; Reference reference = new Reference("#" + id); reference.AddTransform(new XmlDsigEnvelopedSignatureTransform()); reference.AddTransform(new XmlDsigC14NTransform()); signedXml.AddReference(reference); KeyInfo keyInfo = new KeyInfo(); keyInfo.AddClause(new KeyInfoX509Data(xCert)); signedXml.KeyInfo = keyInfo; signedXml.ComputeSignature(); XmlElement xmlSignature = docRequest.CreateElement("Signature", "http://www.w3.org/2000/09/xmldsig#"); XmlElement xmlSignedInfo = signedXml.SignedInfo.GetXml(); XmlElement xmlKeyInfo = signedXml.KeyInfo.GetXml(); XmlElement xmlSignatureValue = docRequest.CreateElement("SignatureValue", xmlSignature.NamespaceURI); string signBase64 = Convert.ToBase64String(signedXml.Signature.SignatureValue, Base64FormattingOptions.InsertLineBreaks); XmlText text = docRequest.CreateTextNode(signBase64); xmlSignatureValue.AppendChild(text); xmlSignature.AppendChild(docRequest.ImportNode(xmlSignedInfo, true)); xmlSignature.AppendChild(xmlSignatureValue); xmlSignature.AppendChild(docRequest.ImportNode(xmlKeyInfo, true)); var evento = docRequest.GetElementsByTagName(tagName); evento[0].AppendChild(xmlSignature); } xmlAssinado = docRequest.OuterXml; docRequest.Save(pathApp + "\\NF-e_assinada.xml"); return(0); } else { errorBroken = "Nenhum Certificado Digital selecionado"; return(999); } } catch (XmlException e1) { errorBrokenDetalhado = e1.StackTrace; errorBroken = e1.Message; return(999); } catch (CryptographicException e2) { errorBrokenDetalhado = e2.StackTrace; errorBroken = e2.Message; return(999); } catch (Exception e3) { errorBrokenDetalhado = e3.StackTrace; errorBroken = e3.Message; return(999); } }
public void SetSignatureAfterDecryption(int index, SignedXml signedXml, byte[] decryptedBuffer) { SetElementAfterDecryption(index, ReceiveSecurityHeaderElementCategory.Signature, signedXml, ReceiveSecurityHeaderBindingModes.Unknown, signedXml.SignedInfo.Id, decryptedBuffer, null); }
public string Sign(string xml, string nodeToSign, string certificateSerialNumber, string certificatePassword = null) { try { _log.Debug(""); _log.Debug("NOVA ASSINATURA"); _log.Debug(new string('-', 150)); _log.Debug(""); _log.Debug($"O conteúdo do XML é NULO ou Vazio? {string.IsNullOrEmpty(xml)}"); _log.Debug(""); _log.Debug($"nodeToSign: {nodeToSign}"); _log.Debug($"certificateSerialNumber: {certificateSerialNumber}"); _log.Debug($"certificatePassword: {certificatePassword}"); _log.Debug(""); _log.Debug($"XML Recebido:{Environment.NewLine}{Environment.NewLine}{xml}"); _log.Debug(""); if (string.IsNullOrEmpty(xml)) { throw new Exception("Conteúdo de XML inválido"); } xml = xml.NormalizeXml(); if (string.IsNullOrEmpty(xml)) { throw new Exception("O conteúdo do XML não foi informado"); } var doc = new XmlDocument(); try { doc.LoadXml(xml); } catch (Exception e) { _log.Error(e, "Erro ao carregar o Documento XML"); throw; } _log.Debug("Documento XML criado"); var nodes = doc.GetElementsByTagName(nodeToSign); if (nodes.Count == 0) { throw new Exception("Conteúdo de XML inválido"); } _log.Debug($"Tag {nodeToSign} encontrada"); var certificate = new CertificateRepository().GetBySerialNumber(certificateSerialNumber); if (certificate == null) { throw new Exception("Não foi possível encontrar o certificado"); } _log.Debug($"Certificado obtido: {certificate.Subject}"); foreach (XmlElement node in nodes) { _log.Debug("Adicionar tipo de criptografia a engine"); CryptoConfig.AddAlgorithm(typeof(RSAPKCS1SHA256SignatureDescription), "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"); _log.Debug("RSAPKCS1SHA256SignatureDescription adicionada"); var keyInfo = new KeyInfo(); keyInfo.AddClause(new KeyInfoX509Data(certificate)); _log.Debug("KeyInfo criado e cláusula adicionada"); var Key = (RSACryptoServiceProvider)certificate.PrivateKey; _log.Debug("key obtida"); var signedXml = new SignedXml(node) { SigningKey = Key, KeyInfo = keyInfo }; _log.Debug("SignedXML criado"); using (var rsa = ReadCard(Key, certificatePassword)) { signedXml.SigningKey = rsa; signedXml.SignedInfo.CanonicalizationMethod = "http://www.w3.org/TR/2001/REC-xml-c14n-20010315"; signedXml.SignedInfo.SignatureMethod = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"; _log.Debug("SignedXML preparado"); // O atributo id no eSocial é impresso com o "I" maiúsculo. // Já no Reinf é com "i" minúsculo. // no eSocial não deve ter valor no atributo URI da tag reference. // Já no Reinf deve conter o valor do "id" //var id = node.Attributes.GetNamedItem("Id")?.InnerText; var id = node.Attributes.GetNamedItem("id")?.InnerText; // assim não encontra o id quando for do eSocial, mas encontrará do Reinf _log.Debug($"ID #{id}"); var reference = new Reference($"#{id}"); reference.AddTransform(new XmlDsigEnvelopedSignatureTransform()); reference.AddTransform(new XmlDsigC14NTransform(false)); reference.DigestMethod = "http://www.w3.org/2001/04/xmlenc#sha256"; if (string.IsNullOrEmpty(id?.Trim())) { reference.Uri = ""; } _log.Debug("Referências criadas"); signedXml.AddReference(reference); _log.Debug("Referências adicionadas"); _log.Debug("A criar assinatura"); signedXml.ComputeSignature(); _log.Debug("Assinatura criada"); var signature = signedXml.GetXml(); _log.Debug("A adicionar a assinatura no documento"); var parentNode = node.ParentNode; if (parentNode == null) { throw new Exception("Não foi possível encontrar o Nó do eSocial"); } parentNode.AppendChild(signature); } _log.Debug("Assinatura adicionada"); } _log.Debug("Atualizando XML de saída"); var sb = new StringBuilder(); using (var writer = XmlWriter.Create(sb, new XmlWriterSettings { Indent = false })) doc.WriteTo(writer); _log.Debug($"XML Assinado:{Environment.NewLine}{Environment.NewLine}{doc.OuterXml}{Environment.NewLine}"); var signatureCount = doc.GetElementsByTagName("Signature").Count; _log.Debug($"Quantidade de assinaturas geradas: {signatureCount}"); return(doc.OuterXml); } catch (Exception e) { _log.Debug("Erro"); _log.Error(e, ""); throw; } }
public void AppendSignature(SignedXml signedXml) { AppendElement(ReceiveSecurityHeaderElementCategory.Signature, signedXml, ReceiveSecurityHeaderBindingModes.Unknown, signedXml.Signature.Id, null); }
// 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(); }
/// <summary> /// Signs an XML Document for a Saml Response /// </summary> internal static XmlElement SignXMLDoc(XmlDocument doc, X509Certificate2 certificate, string referenceUri) { if (doc == null) { throw new ArgumentNullException("The doc parameter can't be null"); } if (certificate == null) { throw new ArgumentNullException("The cert2 parameter can't be null"); } if (string.IsNullOrWhiteSpace(referenceUri)) { throw new ArgumentNullException("The referenceUri parameter can't be null or empty"); } AsymmetricAlgorithm privateKey; try { privateKey = certificate.PrivateKey; } catch (Exception ex) { throw new FieldAccessException("Unable to find private key in the X509Certificate", ex); } #if NET461 var key = new RSACryptoServiceProvider(new CspParameters(24)) { PersistKeyInCsp = false }; key.FromXmlString(privateKey.ToXmlString(true)); SignedXml signedXml = new SignedXml(doc) { SigningKey = key }; #else SignedXml signedXml = new SignedXml(doc) { SigningKey = privateKey // key }; #endif signedXml.SignedInfo.SignatureMethod = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"; signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl; Reference reference = new Reference { DigestMethod = "http://www.w3.org/2001/04/xmlenc#sha256" }; reference.AddTransform(new XmlDsigEnvelopedSignatureTransform()); reference.AddTransform(new XmlDsigExcC14NTransform()); reference.Uri = "#" + referenceUri; signedXml.AddReference(reference); KeyInfo keyInfo = new KeyInfo(); keyInfo.AddClause(new KeyInfoX509Data(certificate)); signedXml.KeyInfo = keyInfo; signedXml.ComputeSignature(); XmlElement signature = signedXml.GetXml(); return(signature); }
// Třída ověří všechny podpisy v dokumentu public bool Verify(XmlDocument doc) { // definice mapování prefixů na jmenné prostory XmlNamespaceManager manager = new XmlNamespaceManager(doc.NameTable); manager.AddNamespace("dsig", "http://www.w3.org/2000/09/xmldsig#"); // příznak validnosti podpisu bool validates = false; // vybereme všechny podpisy v dokumentu XmlNodeList signatures = doc.SelectNodes("/*/dsig:Signature", manager); // pokud by v dokumentu nebylani jeden podpis, nemůže být podpis validní if (signatures.Count > 0) validates = true; // postupné ověření všech nalezených podpisů for (int i = 0; i < signatures.Count; i++) { // načtení XML reprezentace podpisu XmlElement signatureElement = (XmlElement)signatures.Item(i); // načtení dokumentu do objektu pro práci s podpisy SignedXml signedDoc = new SignedXml(doc); // nastavení elementu, ve kterém se má kontrolovat podpis signedDoc.LoadXml(signatureElement); // kontrola podpisu if (!signedDoc.CheckSignature()) validates = false; } return validates; }
/// <summary>Checks the signature.</summary> /// <param name="signedRootElement">The signed root element.</param> /// <param name="idpKeys">A list containing one ore more assymetric keys of a algorithm.</param> private static void CheckSignature(XmlElement signedRootElement, IEnumerable <AsymmetricAlgorithm> idpKeys) { var xmlDocument = new XmlDocument { PreserveWhitespace = true }; xmlDocument.LoadXml(signedRootElement.OuterXml); var signature = xmlDocument.DocumentElement["Signature", SignedXml.XmlDsigNamespaceUrl]; if (signature == null) { throw new Saml2ResponseFailedValidationException("The SAML Response is not signed and contains unsigned Assertions. Response cannot be trusted."); } var signedXml = new SignedXml(xmlDocument); signedXml.LoadXml(signature); var signedRootElementId = "#" + signedRootElement.GetAttribute("ID"); if (signedXml.SignedInfo.References.Count == 0) { throw new Saml2ResponseFailedValidationException("No reference found in Xml signature, it doesn't validate the Xml data."); } if (signedXml.SignedInfo.References.Count != 1) { throw new Saml2ResponseFailedValidationException("Multiple references for Xml signatures are not allowed."); } var reference = signedXml.SignedInfo.References.Cast <Reference>().Single(); if (reference.Uri != signedRootElementId) { throw new Saml2ResponseFailedValidationException("Incorrect reference on Xml signature. The reference must be to the root element of the element containing the signature."); } foreach (Transform transform in reference.TransformChain) { if (!allowedTransforms.Contains(transform.Algorithm)) { throw new Saml2ResponseFailedValidationException( "Transform \"" + transform.Algorithm + "\" found in Xml signature is not allowed in SAML."); } } try { if (!idpKeys.Any(signedXml.CheckSignature)) { throw new Saml2ResponseFailedValidationException("Signature validation failed on SAML response or contained assertion."); } } catch (CryptographicException) { if (signedXml.SignatureMethod == Options.RsaSha256Namespace && CryptoConfig.CreateFromName(signedXml.SignatureMethod) == null) { throw new Saml2ResponseFailedValidationException("SHA256 signatures require the algorithm to be registered at the process level. Call Kentor.AuthServices.Configuration.Options.GlobalEnableSha256XmlSignatures() on startup to register."); } else { throw; } } }
// 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; }
/// <summary> /// Signs an XML element referenced by ID and places the signature element under the document root element. /// Pass an empty string as the element to sign the entire document. /// </summary> internal static XmlElement SignXmlElement(XmlDocument document, string elementToSignId, X509Certificate2 signer) { if (document == null) { throw new ArgumentNullException(nameof(document)); } if (elementToSignId == null) { throw new ArgumentNullException(nameof(elementToSignId)); } if (signer == null) { throw new ArgumentNullException(nameof(signer)); } using (var signingKey = signer.GetRSAPrivateKey()) { var signedXml = new SignedXml(document) { SigningKey = signingKey }; // Add each content key assignment rule element as a reference to sign. var whatToSign = new Reference { // A nice strong algorithm without known weaknesses that are easily exploitable. DigestMethod = Constants.Sha512Algorithm }; if (elementToSignId == "") { // Sign the document. whatToSign.Uri = ""; // This is needed because the signature is within the signed data. whatToSign.AddTransform(new XmlDsigEnvelopedSignatureTransform()); } else { // Sign one specific element. whatToSign.Uri = "#" + elementToSignId; } signedXml.AddReference(whatToSign); // A nice strong algorithm without known weaknesses that are easily exploitable. // The below URI is also contained in "SignedXml.XmlDsigRSASHA512Url", but it doesn't // have public visibility in the .NET Core version of the library. signedXml.SignedInfo.SignatureMethod = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha512"; // Canonical XML 1.0 (omit comments); I suppose it works fine, no deep thoughts about this. signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigCanonicalizationUrl; // Signer certificate must be delivered with the signature. signedXml.KeyInfo.AddClause(new KeyInfoX509Data(signer)); // Ready to sign! Let's go! signedXml.ComputeSignature(); // Now stick the Signature element it generated back into the document and we are done. var signature = signedXml.GetXml(); return((XmlElement)document.DocumentElement.AppendChild(document.ImportNode(signature, true))); } }
static void Main(string[] args) { try { // arrange var xml = File.ReadAllText("test.xml", Encoding.UTF8); var pdf = File.ReadAllBytes("test.pdf"); var cert = Program.Certificate; if (cert == null) { Console.WriteLine("No certificate selected."); Environment.Exit(0); } var dokument = new Dokument(); dokument.Opis.Data.Czas.Wartosc = DateTime.Now.ToString("o"); dokument.Dane.Data.Czas.Wartosc = DateTime.Now.ToString("yyyy-MM-dd"); dokument.Dane.Adresaci.Podmiot.Osoba = new Osoba(); dokument.Dane.Adresaci.Podmiot.Osoba.Nazwisko = "Kowalski"; dokument.Dane.Adresaci.Podmiot.Osoba.Imie = "Jan"; dokument.Dane.Nadawcy.Podmiot.Instytucja = new Instytucja(); dokument.Dane.Nadawcy.Podmiot.Instytucja.NazwaInstytucji = "Urząd miasta Widliszki Wielkie"; dokument.Dane.Nadawcy.Podmiot.Instytucja.Adres.Miejscowosc = "Widliszki Wielkie"; dokument.Dane.Nadawcy.Podmiot.Instytucja.Adres.Ulica = "Kwiatowa"; dokument.Dane.Nadawcy.Podmiot.Instytucja.Adres.Budynek = "1-8"; dokument.Dane.Nadawcy.Podmiot.Instytucja.Adres.Poczta = "11-110"; dokument.Tresc.MiejscowoscDokumentu = "Widliszki Wielkie"; dokument.Tresc.Tytul = "Zawiadomienie w sprawie 1234/2019"; dokument.Tresc.RodzajWnioskuRozszerzony.JakisInny = "inne pismo"; dokument.Tresc.RodzajWnioskuRozszerzony.Rodzaj = "zawiadomienie"; dokument.Tresc.Informacje = new Informacja[] { new Informacja() { Wartosc = "Ala ma kota" }, new Informacja() { Wartosc = "Basia ma wózek widłowy" } }; dokument.Tresc.Zalaczniki = new Zalacznik[] { new Zalacznik() { Format = "application/octet-stream", NazwaPliku = "test.pdf", DaneZalacznika = new DaneZalacznika() { Zawartosc = pdf } } }; // act var namespaces = new XmlSerializerNamespaces(); //namespaces.Add("", ePUAP.Client.Constants.Namespaces.WNIO_PODPISANYDOKUMENT); namespaces.Add("wnio", ePUAP.Client.Constants.Namespaces.CRD_WNIO); namespaces.Add("meta", ePUAP.Client.Constants.Namespaces.CRD_META); namespaces.Add("str", ePUAP.Client.Constants.Namespaces.CRD_STR); namespaces.Add("adr", ePUAP.Client.Constants.Namespaces.CRD_ADR); namespaces.Add("oso", ePUAP.Client.Constants.Namespaces.CRD_OSO); namespaces.Add("inst", ePUAP.Client.Constants.Namespaces.CRD_INST); // wnio:Dokument var document = dokument.ToXmlDocument(namespaces); var pi = document.CreateProcessingInstruction( "xml-stylesheet", "type=\"text/xsl\" href=\"http://crd.gov.pl/wzor/2013/12/12/1410/styl.xsl\""); document.InsertAfter(pi, document.FirstChild); //var document = new XmlDocument(); //document.LoadXml(xml); var signed = new XAdESBESSigner().Sign(document, cert); var signedName = string.Format("test.{0}.xml", DateTime.Now.Ticks); if (signed != null) { // save signed document without BOM File.WriteAllText(signedName, document.OuterXml, new UTF8Encoding(false)); } Console.WriteLine("signed."); // verification var signedXml = new SignedXml(document); var messageSignatureNode = document.GetElementsByTagName("Signature")[0]; signedXml.LoadXml((XmlElement)messageSignatureNode); // check the signature and return the result. var verification = signedXml.CheckSignature(cert, true); Console.WriteLine("Verification: {0}", verification); // transformation using (var xmlReader = new StreamReader(signedName, new UTF8Encoding(false))) { var xPathDoc = new XPathDocument(xmlReader); var xslTrans = new XslCompiledTransform(); xslTrans.Load("http://crd.gov.pl/wzor/2013/12/12/1410/styl.xsl"); using (var writer = new XmlTextWriter(string.Format("result.{0}.html", DateTime.Now.Ticks), null)) { xslTrans.Transform(xPathDoc, null, writer); writer.Flush(); } } } catch (Exception ex) { while (ex != null) { Console.WriteLine(ex.Message); ex = ex.InnerException; } } Console.ReadLine(); }
// <Snippet2> // Sign an XML file and save the signature in a new file. public static void SignXmlFile(string FileName, string SignedFileName, string SubjectName) { if (null == FileName) { throw new ArgumentNullException("FileName"); } if (null == SignedFileName) { throw new ArgumentNullException("SignedFileName"); } if (null == SubjectName) { throw new ArgumentNullException("SubjectName"); } // Load the certificate from the certificate store. X509Certificate2 cert = GetCertificateBySubject(SubjectName); // 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 = cert.PrivateKey; // 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); // Create a new KeyInfo object. KeyInfo keyInfo = new KeyInfo(); // Load the certificate into a KeyInfoX509Data object // and add it to the KeyInfo object. // Create an X509IssuerSerial object and add it to the // KeyInfoX509Data object. KeyInfoX509Data kdata = new KeyInfoX509Data(cert); X509IssuerSerial xserial; xserial.IssuerName = cert.IssuerName.ToString(); xserial.SerialNumber = cert.SerialNumber; kdata.AddIssuerSerial(xserial.IssuerName, xserial.SerialNumber); keyInfo.AddClause(kdata); // 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); } // Save the signed XML document to a file specified // using the passed string. using (XmlTextWriter xmltw = new XmlTextWriter(SignedFileName, new UTF8Encoding(false))) { doc.WriteTo(xmltw); xmltw.Close(); } }
static void Asymmetric (string filename) { string shortName = Path.GetFileName (filename); XmlDocument doc = new XmlDocument (); XmlTextReader xtr = new XmlTextReader (GetReader (filename)); XmlValidatingReader xvr = new XmlValidatingReader (xtr); xtr.Normalization = true; doc.PreserveWhitespace = true; doc.Load (xvr); try { SignedXml s = null; if (filename.IndexOf ("enveloped") >= 0) s = new SignedXml (doc); else if (filename.IndexOf ("signature-big") >= 0) s = new SignedXml (doc); else s = new SignedXml (); XmlNodeList nodeList = doc.GetElementsByTagName ("Signature", "http://www.w3.org/2000/09/xmldsig#"); s.LoadXml ((XmlElement) nodeList [0]); #if false // wanna dump? Console.WriteLine ("\n\nFilename : " + fi.Name); DumpSignedXml (s); #endif // MS doesn't extract the public key out of the certificates // http://www.dotnet247.com/247reference/a.aspx?u=http://www.kbalertz.com/Feedback_320602.aspx Mono.Security.X509.X509Certificate mx = null; foreach (KeyInfoClause kic in s.KeyInfo) { if (kic is KeyInfoX509Data) { KeyInfoX509Data kix = (kic as KeyInfoX509Data); if ((kix.Certificates != null) && (kix.Certificates.Count > 0)) { System.Security.Cryptography.X509Certificates.X509Certificate x509 = (System.Security.Cryptography.X509Certificates.X509Certificate) kix.Certificates [0]; byte[] data = x509.GetRawCertData (); mx = new Mono.Security.X509.X509Certificate (data); } } } // special cases // 1- Merlin's certificate resolution (manual) // 2- Phaos (because Fx doesn't support RetrievalMethod switch (shortName) { case "signature-keyname.xml": mx = LoadCertificate (GetPath (filename, "lugh.crt")); break; case "signature-retrievalmethod-rawx509crt.xml": mx = LoadCertificate (GetPath (filename, "balor.crt")); break; case "signature-x509-is.xml": mx = LoadCertificate (GetPath (filename, "macha.crt")); break; case "signature-x509-ski.xml": mx = LoadCertificate (GetPath (filename, "nemain.crt")); break; case "signature-x509-sn.xml": mx = LoadCertificate (GetPath (filename, "badb.crt")); break; // Phaos case "signature-big.xml": case "signature-rsa-manifest-x509-data-issuer-serial.xml": case "signature-rsa-manifest-x509-data-ski.xml": case "signature-rsa-manifest-x509-data-subject-name.xml": case "signature-rsa-detached-xslt-transform-retrieval-method.xml": mx = LoadCertificate (GetPath (filename, "rsa-cert.der")); break; case "signature-rsa-detached-xslt-transform-bad-retrieval-method.xml": mx = LoadCertificate (GetPath (filename, "dsa-ca-cert.der")); break; default: break; } bool result = false; if (mx != null) { if (mx.RSA != null) { result = s.CheckSignature (mx.RSA); } else if (mx.DSA != null) { result = s.CheckSignature (mx.DSA); } } else { // use a key existing in the document result = s.CheckSignature (); } if (result) { Console.WriteLine ("valid " + shortName); valid++; } else { Console.WriteLine ("INVALID {0}", shortName); invalid++; } } catch (Exception ex) { Console.WriteLine ("EXCEPTION " + shortName + " " + ex); error++; } }
public static string Sign(string xml, X509Certificate2 certificate) { if (xml == null) throw new ArgumentNullException("xml"); if (certificate == null) throw new ArgumentNullException("certificate"); if (!certificate.HasPrivateKey) throw new ArgumentException("certificate", "Certificate should have a private key"); XmlDocument doc = new XmlDocument(); doc.PreserveWhitespace = true; doc.LoadXml(xml); SignedXml signedXml = new SignedXml(doc); signedXml.SigningKey = certificate.PrivateKey; // Attach certificate KeyInfo KeyInfoX509Data keyInfoData = new KeyInfoX509Data(certificate); KeyInfo keyInfo = new KeyInfo(); keyInfo.AddClause(keyInfoData); signedXml.KeyInfo = keyInfo; // Attach transforms var reference = new Reference(""); reference.AddTransform(new XmlDsigEnvelopedSignatureTransform(includeComments: false)); reference.AddTransform(new XmlDsigExcC14NTransform(includeComments: false)); signedXml.AddReference(reference); // Compute signature signedXml.ComputeSignature(); var signatureElement = signedXml.GetXml(); // Add signature to bundle doc.DocumentElement.AppendChild(doc.ImportNode(signatureElement, true)); return doc.OuterXml; }
public static SignatureType GeraAssinatura(XmlDocument doc, string pUri, X509Certificate2 cert) { try { var signature = doc.GetElementsByTagName("Signature"); if (signature.Count == 1) { signature.Item(0).ParentNode.RemoveChild(signature.Item(0)); } else if (signature.Count > 1) { throw new InvalidOperationException("Não é possível assinar um documento com mais de uma assinatura existente."); } // Create a SignedXml object. var signedXml = new SignedXml(doc) { SigningKey = cert.PrivateKey }; // Create a reference to be signed. var reference = new Reference(); // pega o uri que deve ser assinada var 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. var env = new XmlDsigEnvelopedSignatureTransform(); reference.AddTransform(env); var c14 = new XmlDsigC14NTransform(); reference.AddTransform(c14); // Add the reference to the SignedXml object. signedXml.AddReference(reference); // Create a new KeyInfo object. var 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(); var xml = signedXml.GetXml(); using (var sw = new StringWriter()) using (var xw = new XmlTextWriter(sw)) { xml.WriteTo(xw); xw.Close(); var sigXml = sw.ToString(); return(SignatureType.Deserialize(sigXml)); } } catch (Exception ex) { throw new Exception("Erro ao efetuar assinatura digital, detalhes: " + ex.Message); } }
// Verify the signature of an XML file against an asymetric // 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); }
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); } }