// Sign an XML file and save the signature in a new file. This method does not // save the public key within the XML file. This file cannot be verified unless // the verifying code has the key with which it was signed. public static void SignXmlFile(string FileName, string SignedFileName, RSA Key) { // Create a new XML document. XmlDocument doc = new XmlDocument(); // Load the passed XML file using its name. doc.Load(new XmlTextReader(FileName)); // Create a SignedXml object. SignedXml signedXml = new SignedXml(doc); // Add the key to the SignedXml document. signedXml.SigningKey = Key; // Create a reference to be signed. Reference reference = new Reference(); reference.Uri = ""; // Add an enveloped transformation to the reference. XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform(); reference.AddTransform(env); // Add the reference to the SignedXml object. signedXml.AddReference(reference); // Compute the signature. signedXml.ComputeSignature(); // Get the XML representation of the signature and save // it to an XmlElement object. XmlElement xmlDigitalSignature = signedXml.GetXml(); // Append the element to the XML document. doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, true)); if (doc.FirstChild is XmlDeclaration) { doc.RemoveChild(doc.FirstChild); } // Save the signed XML document to a file specified // using the passed string. XmlTextWriter xmltw = new XmlTextWriter(SignedFileName, new UTF8Encoding(false)); doc.WriteTo(xmltw); xmltw.Close(); }
static void Main(string[] args) { if (args.Length != 4) { Console.WriteLine("Usage: cra.exe cert-file cert-password input-path output-path"); return; } String certFile = args[0]; String password = args[1]; String input = args[2]; String output = args[3]; X509Certificate2 cert = new X509Certificate2(certFile, password, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet); XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(input); var XmlToSign = new XmlDocument(); XmlToSign.LoadXml(xmlDoc.DocumentElement["Body"].OuterXml); SignedXml signedXml = new SignedXml(XmlToSign); signedXml.SigningKey = cert.PrivateKey; Reference reference = new Reference(); reference.Uri = ""; XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform(); reference.AddTransform(env); signedXml.AddReference(reference); signedXml.ComputeSignature(); XmlElement xmlDigitalSignature = signedXml.GetXml(); xmlDoc.DocumentElement["Body"].AppendChild(xmlDoc.ImportNode(xmlDigitalSignature, true)); xmlDoc.Save(output); }
public static 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; }
// 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()); }
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); } }
//------------------------------------------------------------------------------------------- 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(); }
// 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. 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); } // 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(); } }
// 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; }
static void Main(string[] args) { Console.WriteLine("Hello World!"); var stopWatch = Stopwatch.StartNew(); var certificateFinder = new CertificateFinder(); var certInfo = certificateFinder.GetCertInfo(); Console.WriteLine($"GetCertInfo ticks: {stopWatch.ElapsedTicks}"); var xmlDocs = CreateTwoXmlDocs(); SecureString pinCode = new SecureString(); pinCode.AppendChar('6'); pinCode.AppendChar('8'); pinCode.AppendChar('6'); pinCode.AppendChar('1'); using (var key = certificateFinder.GetKey(certInfo, pinCode)) { Console.WriteLine($"GetKey ticks: {stopWatch.ElapsedTicks}"); foreach (var xmlDoc in xmlDocs) { var signedXml = new SignedXml(xmlDoc) { SigningKey = key }; var keyInfo = new KeyInfo(); keyInfo.AddClause(new KeyInfoX509Data(certInfo.SelectedCertificate.Certificate, X509IncludeOption.EndCertOnly)); signedXml.KeyInfo = keyInfo; // Create a reference to be signed. var reference = new Reference(); reference.Uri = string.Empty; // Add an enveloped transformation to the reference. var env = new XmlDsigEnvelopedSignatureTransform(); reference.AddTransform(env); // Add the reference to the SignedXml object. signedXml.AddReference(reference); // Compute the signature. signedXml.ComputeSignature(); Console.WriteLine($"ComputeSignature ticks: {stopWatch.ElapsedTicks}"); var signature = signedXml.GetXml(); var certificateSerialNumber = certInfo.SelectedCertificate.Certificate.SerialNumber; xmlDoc.DocumentElement.AppendChild(signature); //perSigningCallback?.Invoke(); } } Console.WriteLine("\nDone! Press any key to exit"); Console.ReadKey(); }
private Resultado AssinarXML(ref XmlDocument _xml, string _cnpj) { Resultado _resultado = new Resultado(); if (_xml == null) { _resultado.Sucesso = false; _resultado.Mensagens = new Base.ResultadoMensagem[] { new Base.ResultadoMensagem() { Texto = "Arquivo XML não pode estar vazio." } }; } if (string.IsNullOrEmpty(_cnpj)) { _resultado.Sucesso = false; _resultado.Mensagens = new Base.ResultadoMensagem[] { new Base.ResultadoMensagem() { Texto = "CNPJ para recuperar certificado não pode ser nulo" } }; } Resultado <X509Certificate2> _resultadoCert = Lib.Library.recuperarCertificadoEnvio(Guid, _cnpj); if (_resultadoCert.Sucesso) { X509Certificate2 _cert = _resultadoCert.Retorno; CryptoConfig.AddAlgorithm(typeof(RSAPKCS1SHA256SignatureDescription), "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"); string _exportedKeyMaterial = _cert.PrivateKey.ToXmlString(true); RSACryptoServiceProvider _key = new RSACryptoServiceProvider(new CspParameters(24)) { PersistKeyInCsp = false }; _key.FromXmlString(_exportedKeyMaterial); KeyInfo _keyInfo = new KeyInfo(); _keyInfo.AddClause(new KeyInfoX509Data(_cert)); var _xmlElements = _xml.GetElementsByTagName("eventos").Cast <XmlElement>().FirstOrDefault() .GetElementsByTagName("eSocial").Cast <XmlElement>().ToList(); foreach (XmlElement _xmlEle in _xmlElements) { string _id = _xmlEle.FirstChild.Attributes["Id"].Value; XmlDocument _newXML = new XmlDocument(); _newXML.LoadXml(_xmlEle.OuterXml); SignedXml _assinador = new SignedXml(_newXML) { SigningKey = _key }; _assinador.SignedInfo.SignatureMethod = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"; Reference _reference = new Reference(""); _reference.AddTransform(new XmlDsigEnvelopedSignatureTransform()); _reference.AddTransform(new XmlDsigC14NTransform()); _reference.Uri = ""; _reference.DigestMethod = "http://www.w3.org/2001/04/xmlenc#sha256"; _assinador.AddReference(_reference); _assinador.KeyInfo = _keyInfo; _assinador.ComputeSignature(); _xmlEle.AppendChild(_xml.ImportNode(_assinador.GetXml(), true)); } } else { _resultado.Sucesso = false; _resultado.Mensagens = new Base.ResultadoMensagem[] { new Base.ResultadoMensagem() { Texto = _resultadoCert.Mensagem } }; } return(_resultado); }
public static string FirmarDocumentoXML(string pathXmlDocument, string RutaCertificadoDigital, string PasswordCertificado) { XmlDocument documentXml = new XmlDocument(); documentXml.PreserveWhitespace = true; documentXml.Load(pathXmlDocument); var nodoExtension = documentXml.GetElementsByTagName("ExtensionContent", EspacioNombres.CommonExtensionComponents).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; var cert = RSAHelper.GetX509Certificate(RutaCertificadoDigital, PasswordCertificado); firmado.SigningKey = (RSA)cert.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/2000/09/xmldsig#rsa-sha1"; reference.DigestMethod = "http://www.w3.org/2000/09/xmldsig#sha1"; // info para la llave publica KeyInfo keyInfo = new KeyInfo(); keyInfo.AddClause(new KeyInfoX509Data(cert)); xmlSignature.KeyInfo = keyInfo; xmlSignature.Id = "SignatureErickOrlando"; firmado.ComputeSignature(); // Recuperamos el valor Hash de la firma para este documento. if (reference.DigestValue != null) { ModuloDoc moduloFactura = new ModuloDoc(); moduloFactura.DigestValue = Convert.ToBase64String(reference.DigestValue); } nodoExtension.AppendChild(firmado.GetXml()); var settings = new XmlWriterSettings() { Encoding = Encoding.GetEncoding("ISO-8859-1") }; string resultado = String.Empty; using (var memDoc = new MemoryStream()) { using (var writer = XmlWriter.Create(memDoc, settings)) { documentXml.WriteTo(writer); } resultado = Convert.ToBase64String(memDoc.ToArray()); } return(resultado); }
public int Assinar(string XMLString, string RefUri, X509Certificate2 X509Cert) /* * Entradas: * XMLString: string XML a ser assinada * RefUri : Referência da URI a ser assinada (Ex. infNFe * X509Cert : certificado digital a ser utilizado na assinatura digital * * Retornos: * Assinar : 0 - Assinatura realizada com sucesso * 1 - Erro: Problema ao acessar o certificado digital - %exceção% * 2 - Problemas no certificado digital * 3 - XML mal formado + exceção * 4 - A tag de assinatura %RefUri% inexiste * 5 - A tag de assinatura %RefUri% não é unica * 6 - Erro Ao assinar o documento - ID deve ser string %RefUri(Atributo)% * 7 - Erro: Ao assinar o documento - %exceção% * * XMLStringAssinado : string XML assinada * * XMLDocAssinado : XMLDocument do XML assinado */ { int resultado = 0; msgResultado = "Assinatura realizada com sucesso"; try { // certificado para ser utilizado na assinatura // string _xnome = ""; if (X509Cert != null) { // certificado ok ///_X509Cert = collection1[0]; string x; x = X509Cert.GetKeyAlgorithm().ToString(); // Create a new XML document. XmlDocument doc = new XmlDocument(); // Format the document to ignore white spaces. doc.PreserveWhitespace = true; // Load the passed XML file using it's name. try { doc.LoadXml(XMLString); // Verifica se a tag a ser assinada existe é única int qtdeRefUri = doc.GetElementsByTagName(RefUri).Count; if (qtdeRefUri == 0) { // a URI indicada não existe resultado = 4; msgResultado = "A tag de assinatura " + RefUri.Trim() + " inexiste"; } // Exsiste mais de uma tag a ser assinada else { if (qtdeRefUri > 1) { // existe mais de uma URI indicada resultado = 5; msgResultado = "A tag de assinatura " + RefUri.Trim() + " não é unica"; } //else if (_listaNum.IndexOf(doc.GetElementsByTagName(RefUri).Item(0).Attributes.ToString().Substring(1,1))>0) //{ // resultado = 6; // msgResultado = "Erro: Ao assinar o documento - ID deve ser string (" + doc.GetElementsByTagName(RefUri).Item(0).Attributes + ")"; //} else { try { // Create a SignedXml object. SignedXml signedXml = new SignedXml(doc); // Add the key to the SignedXml document signedXml.SigningKey = X509Cert.PrivateKey; // Create a reference to be signed signedXml.SignedInfo.SignatureMethod = SignedXml.XmlDsigRSASHA1Url; Reference reference = new Reference(); // pega o uri que deve ser assinada XmlAttributeCollection _Uri = doc.GetElementsByTagName(RefUri).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); reference.DigestMethod = SignedXml.XmlDsigSHA1Url; // 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(X509Cert)); // 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(); // Append the element to the XML document. doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, true)); XMLDoc = new XmlDocument(); XMLDoc.PreserveWhitespace = true; XMLDoc = doc; XMLDoc.Save("/storage/emulated/0/certificados/xml.xml"); } catch (Exception caught) { resultado = 7; msgResultado = "Erro: Ao assinar o documento - " + caught.Message; } } } } catch (Exception caught) { resultado = 3; msgResultado = "Erro: XML mal formado - " + caught.Message; } } } catch (Exception caught) { resultado = 1; msgResultado = "Erro: Problema ao acessar o certificado digital" + caught.Message; } return(resultado); }
private void Assinar(ref XmlDocument conteudoXML, string tagAssinatura, string tagAtributoId, X509Certificate2 x509Cert, Empresa empresa, EnumAlgorithmType algorithmType = EnumAlgorithmType.Sha1, string idAttributeName = "", bool definirURI = true, string pinCertificado = "") { try { //if (x509Cert == null) // throw new ExceptionCertificadoDigital(ErroPadrao.CertificadoNaoEncontrado); 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); XmlNode listRPS = null; /// Esta condição foi feita especificamente para prefeitura de Governador Valadares pois o AtribudoID e o Elemento assinado devem possuir o mesmo nome. /// Talvez tenha que ser reavaliado. #region Governador Valadares if (tagAssinatura.Equals(tagAtributoId) && empresa.UnidadeFederativaCodigo == 3127701) { foreach (XmlNode item in lists) { if (listRPS == null) { listRPS = item; } if (item.Name.Equals(tagAssinatura)) { lists = item.ChildNodes; break; } } } #endregion Governador Valadares foreach (XmlNode nodes in lists) { foreach (XmlNode childNodes in nodes.ChildNodes) { if (!childNodes.Name.Equals(tagAtributoId)) { continue; } var reference = new Reference { Uri = "" }; // pega o uri que deve ser assinada var 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; } } var signedXml = new SignedXml(conteudoXML); if (!string.IsNullOrWhiteSpace(pinCertificado)) { //x509Cert.SetPinPrivateKey(pinCertificado); } reference.AddTransform(new XmlDsigEnvelopedSignatureTransform()); reference.AddTransform(new XmlDsigC14NTransform()); switch (algorithmType) { case EnumAlgorithmType.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; } // Add an enveloped transformation to the reference. reference.AddTransform(new XmlDsigEnvelopedSignatureTransform()); reference.AddTransform(new XmlDsigC14NTransform()); signedXml.AddReference(reference); var keyInfo = new KeyInfo(); keyInfo.AddClause(new KeyInfoX509Data(x509Cert)); signedXml.KeyInfo = keyInfo; signedXml.ComputeSignature(); var xmlDigitalSignature = signedXml.GetXml(); if (tagAssinatura.Equals(tagAtributoId) && empresa.UnidadeFederativaCodigo == 3127701) { ///Desenvolvido especificamente para prefeitura de governador valadares listRPS.AppendChild(conteudoXML.ImportNode(xmlDigitalSignature, true)); } else { // Gravar o elemento no documento XML nodes.AppendChild(conteudoXML.ImportNode(xmlDigitalSignature, true)); } } } } } catch (CryptographicException ex) { AssinaturaValida = false; throw; } }
static void Main(string[] args) { X509Certificate2 x509Certificate2 = GetCertificate("990B25F50DC7E2B548BE75AFED579448"); //X509Certificate2 x509Certificate2 = GetCertificate("0efb7eebdcda4f64a718db3ff908b085"); //X509Certificate2 x509Certificate2 = GetCertificate("2E0A6058EA90DB8C46D1FD3513A877F8"); DCinemaSecurityMessageType extraTheatreMessage = new DCinemaSecurityMessageType(); XmlSerializer xmlSerializer = new XmlSerializer(extraTheatreMessage.GetType()); extraTheatreMessage.AuthenticatedPublic = new AuthenticatedPublicType(); extraTheatreMessage.AuthenticatedPublic.Id = "AuthenticatedPublic.Id." + Guid.NewGuid().ToString(); extraTheatreMessage.AuthenticatedPublic.MessageId = "urn:uuid:" + Guid.NewGuid().ToString(); extraTheatreMessage.AuthenticatedPublic.MessageType = "http://www.smpte-ra.org/schemas/430-3/2006/ETM"; extraTheatreMessage.AuthenticatedPublic.AnnotationText = new UserText(); extraTheatreMessage.AuthenticatedPublic.AnnotationText.Value = "Empty Extra-Theatre Message"; extraTheatreMessage.AuthenticatedPublic.AnnotationText.language = "en-us"; extraTheatreMessage.AuthenticatedPublic.IssueDate = DateTime.Now; X509IssuerSerial issuerSerial = new X509IssuerSerial(); issuerSerial.IssuerName = x509Certificate2.IssuerName.Name; issuerSerial.SerialNumber = x509Certificate2.SerialNumber; extraTheatreMessage.AuthenticatedPublic.Signer = issuerSerial; extraTheatreMessage.AuthenticatedPrivate = new AuthenticatedPrivateType(); extraTheatreMessage.AuthenticatedPrivate.Id = "AuthenticatedPrivate.Id." + Guid.NewGuid().ToString(); #region Build the signature elements SignedXml signedXml = null; try { signedXml = new SignedXml(); signedXml.SigningKey = x509Certificate2.PrivateKey; //signedXml.SignedInfo.SignatureMethod = "http://www.w3.org/ 2001/04/xmldsig-more#rsasha256"; //signedXml.SignedInfo.SignatureMethod = "http://www.w3.org/2001/04/xmlenc#sha256"; signedXml.SignedInfo.CanonicalizationMethod = "http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments"; StringWriter stringWriter = new StringWriter(); xmlSerializer.Serialize(stringWriter, extraTheatreMessage); string serializedXML = stringWriter.ToString(); #region Build the AuthenticatedPublic DataObject & Reference string xmlAuthenticatedPublic = GetCleanElement(serializedXML, "AuthenticatedPublic"); XmlDocument docAuthenticatedPublic = new XmlDocument(); docAuthenticatedPublic.LoadXml(xmlAuthenticatedPublic.ToString()); //XmlAttribute attrAuthenticatedPublic = docAuthenticatedPublic.CreateAttribute("xmlns"); //attrAuthenticatedPublic.Value = "http://www.smpte-ra.org/schemas/430-3/2006/ETM"; //docAuthenticatedPublic.DocumentElement.Attributes.Append(attrAuthenticatedPublic); DataObject dataObjectAuthenticatedPublic = new DataObject("AuthenticatedPublic", "", "", docAuthenticatedPublic.DocumentElement); //DataObject dataObjectAuthenticatedPublic = new DataObject(); dataObjectAuthenticatedPublic.Data = docAuthenticatedPublic.ChildNodes; dataObjectAuthenticatedPublic.Id = "AuthenticatedPublic"; signedXml.AddObject(dataObjectAuthenticatedPublic); Reference referenceAuthenticatedPublic = new Reference(); referenceAuthenticatedPublic.Uri = "#AuthenticatedPublic"; referenceAuthenticatedPublic.DigestMethod = "http://www.w3.org/2001/04/xmlenc#sha256"; signedXml.AddReference(referenceAuthenticatedPublic); #endregion #region Build the AuthenticatedPublic DataObject & Reference string xmlAuthenticatedPrivate = GetCleanElement(serializedXML, "AuthenticatedPrivate"); XmlDocument docAuthenticatedPrivate = new XmlDocument(); docAuthenticatedPrivate.LoadXml(xmlAuthenticatedPrivate.ToString()); //XmlAttribute attrAuthenticatedPrivate = docAuthenticatedPrivate.CreateAttribute("xmlns"); //attrAuthenticatedPrivate.Value = "http://www.smpte-ra.org/schemas/430-3/2006/FLM"; //docAuthenticatedPrivate.DocumentElement.Attributes.Append(attrAuthenticatedPrivate); DataObject dataObjectAuthenticatedPrivate = new DataObject("AuthenticatedPrivate", "", "", docAuthenticatedPrivate.DocumentElement); //DataObject dataObjectAuthenticatedPrivate = new DataObject("AuthenticatedPrivate", "", "", docAuthenticatedPrivate.DocumentElement); //dataObjectAuthenticatedPrivate.Data = docAuthenticatedPrivate.ChildNodes; //dataObjectAuthenticatedPrivate.Id = "AuthenticatedPrivate"; signedXml.AddObject(dataObjectAuthenticatedPrivate); Reference referenceAuthenticatedPrivate = new Reference(); referenceAuthenticatedPrivate.Uri = "#AuthenticatedPrivate"; referenceAuthenticatedPrivate.DigestMethod = "http://www.w3.org/2001/04/xmlenc#sha256"; // Add the reference to the message. signedXml.AddReference(referenceAuthenticatedPrivate); #endregion // Add a KeyInfo. KeyInfo keyInfo = new KeyInfo(); keyInfo.AddClause(new KeyInfoX509Data(x509Certificate2, X509IncludeOption.WholeChain)); signedXml.KeyInfo = keyInfo; // Compute the signature. signedXml.ComputeSignature(); XmlElement singedElement = signedXml.GetXml(); XmlSerializer signedSerializer = new XmlSerializer(singedElement.GetType()); StreamWriter signedWriter = new StreamWriter("D:\\signedSerializer.Test.xml"); signedSerializer.Serialize(signedWriter, singedElement); signedWriter.Close(); } catch (CryptographicException e) { Console.WriteLine(e.Message); } #endregion #region Fill in the signature element extraTheatreMessage.Signature = signedXml.Signature.GetXml(); #endregion xmlSerializer.Serialize(Console.Out, extraTheatreMessage); Console.WriteLine("\r\n"); TextWriter WriteFileStream = new StreamWriter(@"\Source_SMPTE\Output\ExtraTheatreMessage.xml"); xmlSerializer.Serialize(WriteFileStream, extraTheatreMessage); WriteFileStream.Close(); ServiceExtraTheatreMessageClient client = new ServiceExtraTheatreMessageClient(); string response = client.ETM(extraTheatreMessage); DCinemaSecurityMessageType existingETM = new DCinemaSecurityMessageType(); TextReader readFileStream = new StreamReader(@"\Source_SMPTE\Input\DCinemaSecurityMessageType_AMC.xml"); existingETM = (DCinemaSecurityMessageType)xmlSerializer.Deserialize(readFileStream); readFileStream.Close(); existingETM.AuthenticatedPrivate = new AuthenticatedPrivateType(); existingETM.Signature = signedXml.Signature.GetXml(); WriteFileStream = new StreamWriter(@"\Source_SMPTE\Output\Read_ExtraTheatreMessage.xml"); xmlSerializer.Serialize(WriteFileStream, existingETM); WriteFileStream.Close(); response = client.ETM(existingETM); }
public string AssinaXML(string aXML, string pUri, string URI, string serialCertificado) { // open the XML file //StreamReader SR = File.OpenText(pArqXMLAssinar); String vXMLString = aXML; //SR.Close(); // return parameters this.vResultado = 0; this.vResultadoString = "Assinatura realizada com sucesso"; this.vXMLStringAssinado = String.Empty; try { // checking if there is a certified used on xml sign string _xnome = ""; bool vRetorna; X509Certificate2 _X509Cert = CertificadoDigital.ObtemCertificadoDigital(serialCertificado); if (_X509Cert == null) { vRetorna = false; } else { string x; x = _X509Cert.GetKeyAlgorithm().ToString(); // 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. try { doc.LoadXml(vXMLString); // cheching the elemento will be sign int qtdeRefUri = doc.GetElementsByTagName(pUri).Count; if (qtdeRefUri == 0) { this.vResultado = 4; this.vResultadoString = "A tag de assinatura " + pUri.Trim() + " não existe"; } else { if (qtdeRefUri > 1) { this.vResultado = 5; this.vResultadoString = "A tag de assinatura " + pUri.Trim() + " não é unica"; } else { try { // Create a SignedXml object. SignedXml signedXml = new SignedXml(doc); // Add the key to the SignedXml document signedXml.SigningKey = _X509Cert.PrivateKey; // Create a reference to be signed Reference reference = new Reference(); reference.Uri = URI; /*if (pUri.Trim() != "") * { * XmlAttributeCollection _Uri = doc.GetElementsByTagName(pUri).Item(0).Attributes; * * foreach (XmlAttribute _atributo in _Uri) * { * if (_atributo.Name == "Id") * reference.Uri = "#" + _atributo.InnerText; * } * } * else * { * reference.Uri = ""; * }*/ // 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(_X509Cert)); // 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 doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, true)); XmlDocument XMLDoc = new XmlDocument(); XMLDoc.PreserveWhitespace = false; XMLDoc = doc; // XML document already signed vXMLStringAssinado = XMLDoc.OuterXml; } catch (Exception caught) { this.vResultado = 6; this.vResultadoString = "Erro ao assinar o documento - " + caught.Message; } } } } catch (Exception caught) { this.vResultado = 3; this.vResultadoString = "XML mal formado - " + caught.Message; } } } catch (Exception caught) { this.vResultado = 1; this.vResultadoString = "Problema ao acessar o certificado digital" + caught.Message; } return(vXMLStringAssinado); }