Пример #1
3
    // 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();
    }
Пример #2
2
	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);
	}
Пример #3
0
    // 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;
    }
Пример #4
0
    //-------------------------------------------------------------------------------------------
    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();
    }
Пример #5
0
        /// <summary>
        ///     Retornos:
        ///         Assinar : 0 - Assinatura realizada com sucesso
        ///                   1 - Erro: Problema ao acessar o certificado digital
        ///                   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
        /// </summary>
        /// <param name="xmlNfe">Documento XML a ser assinado</param>
        /// <param name="refUri">Referência da URI a ser assinada (Ex.: infCanc, infCTe, infInut, etc.)</param>
        /// <param name="x509Cert">certificado digital a ser utilizado na assinatura digital</param>
        /// <returns></returns>
        public int Assinar(ref XmlDocument doc, string refUri, X509Certificate2 x509Cert)
        {
            int resultado = 0;

            msgResultado = "Assinatura realizada com sucesso";
            try
            {
                // certificado para ser utilizado na assinatura
                string _xnome = "";
                if (x509Cert != null)
                {
                    _xnome = x509Cert.Subject.ToString();
                }

                string x = x509Cert.GetKeyAlgorithm().ToString();

                // Format the document to ignore white spaces.
                doc.PreserveWhitespace = true;

                // Recarrega XML para fazer o calculo do digest corretamente
                XmlDocument docTemp = new XmlDocument();
                docTemp.LoadXml(doc.InnerXml.ToString());
                doc = docTemp;

                // Load the passed XML file using it's name.
                try
                {
                    // 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";
                    }
                    // Existe 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 é única.";
                        }
                        else
                        {
                            try
                            {
                                // Create a SignedXml object.
                                SignedXml signedXml = new SignedXml(doc);

                                // Add the key to the SignedXml document
                                signedXml.SigningKey = x509Cert.PrivateKey;

                                if (x509Cert.PrivateKey == null)
                                {
                                    throw new Exception("Chave privada nula.");
                                }

                                // Create a reference to be signed
                                Reference reference = new Reference();

                                // pega o uri que deve ser assinada
                                XmlElement             e    = (XmlElement)doc.GetElementsByTagName(refUri).Item(0);
                                XmlAttributeCollection _Uri = e.Attributes;
                                foreach (XmlAttribute _atributo in _Uri)
                                {
                                    if (_atributo.Name == "Id")
                                    {
                                        reference.Uri = "#" + _atributo.InnerText;
                                        break;
                                    }
                                }

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

                                // Append the element to the XML document.
                                e.ParentNode.AppendChild(doc.ImportNode(xmlDigitalSignature, true));
                            }
                            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);
        }
Пример #6
0
        public static void FirmaXML(string RutaXml, string nombrexml)
        {
            try
            {
                //Declaro variable XMLDocument
                XmlDocument xmlDoc = new XmlDocument();
                // Cargo el documento en el xmlDoc
                xmlDoc.PreserveWhitespace = true;
                //var PathServer = ConfigurationManager.AppSettings["XmlServidor"];
                var    PathServer = @"C:\Users\Public\Documents\ArchivosXml";
                string pathXml    = PathServer + @"\sonna_judith_vega_solis.p12";
                xmlDoc.Load(@RutaXml);
                //string soapSecNS = "http://www.w3.org/2000/09/xmldsig#rsa-sha1";
                //Obtengo la firma en el Certificado X509
                X509Certificate2 uidCert = new X509Certificate2(pathXml, "Sonnav67", X509KeyStorageFlags.DefaultKeySet);
                //string nombre = uidCert.GetNameInfo(System.Security.Cryptography.X509Certificates.X509NameType.DnsName,true);
                //Console.WriteLine(nombre);
                //Inicializo el RSA
                RSACryptoServiceProvider rsaKey = (RSACryptoServiceProvider)uidCert.PrivateKey;

                //Agrego el SgnedXml que permite firmar el xml
                SignedXml signedXml = new SignedXml(xmlDoc);

                // Add the key to the SignedXml document.
                signedXml.SigningKey = rsaKey;

                signedXml.Signature.Id = newID("Signature");


                //Agregamos el metodo de firmado
                signedXml.SignedInfo.SignatureMethod = XmlDsigRSASHA1Url;

                signedXml.SignedInfo.Id = newID("Signature-SignedInfo");

                // Create a reference to be signed.
                Reference reference = new Reference();
                //reference.Id = newID("#Certificate");
                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);


                // Add an RSAKeyValue KeyInfo (optional; helps recipient find key to validate).
                KeyInfo keyInfo = new KeyInfo();

                KeyInfoX509Data clause = new KeyInfoX509Data();
                clause.AddSubjectName(uidCert.Subject);
                clause.AddCertificate(uidCert);
                keyInfo.AddClause(clause);

                keyInfo.Id = newID("Certificate1");

                signedXml.KeyInfo = keyInfo;

                // Compute the signature.
                signedXml.ComputeSignature();


                Boolean respuesta = signedXml.CheckSignature();
                System.Console.WriteLine(respuesta);

                // Get the XML representation of the signature and save
                // it to an XmlElement object.
                XmlElement xmlDigitalSignature = signedXml.GetXml();


                //XmlElement signature = signedXml.GetXml();
                foreach (XmlNode node in xmlDigitalSignature.SelectNodes(
                             "descendant-or-self::*[namespace-uri()='http://www.w3.org/2000/09/xmldsig#']"))
                {
                    node.Prefix = "ds";
                }


                System.Console.WriteLine(signedXml.GetXml().InnerXml);
                // Append the element to the XML document.
                xmlDoc.DocumentElement.AppendChild(xmlDoc.ImportNode(xmlDigitalSignature, true));


                //Preguntar sobre el directorio

                if (!Directory.Exists(PathServer + @"\Firmados\"))
                {
                    Directory.CreateDirectory(PathServer + @"\Firmados\");
                }


                xmlDoc.Save(@PathServer + @"\Firmados\" + @"\" + nombrexml + ".xml");
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            finally
            {
                System.Console.ReadLine();
            }
        }
Пример #7
0
        static XmlDocument SignXmlFile(
            XmlDocument doc,
            AsymmetricAlgorithm Key,
            X509Certificate Certificate,
            string DigestMethod = SignedXml.XmlDsigGost3411_2012_256Url)
        {
            // Создаем объект SignedXml по XML документу.
            SignedXml signedXml = new SignedXml(doc);

            // Добавляем ключ в SignedXml документ.
            signedXml.SigningKey = Key;

            // Создаем ссылку на node для подписи.
            // При подписи всего документа проставляем "".
            Reference reference = new Reference();

            reference.Uri = "";

            // Явно проставляем алгоритм хэширования,
            // по умолчанию SHA1.
            reference.DigestMethod = DigestMethod;

            // Добавляем transform на подписываемые данные
            // для удаления вложенной подписи.
            XmlDsigEnvelopedSignatureTransform env =
                new XmlDsigEnvelopedSignatureTransform();

            reference.AddTransform(env);

            // Добавляем СМЭВ трансформ.
            // начиная с .NET 4.5.1 для проверки подписи, необходимо добавить этот трансформ в довернные:
            // signedXml.SafeCanonicalizationMethods.Add("urn://smev-gov-ru/xmldsig/transform");
            XmlDsigSmevTransform smev =
                new XmlDsigSmevTransform();

            reference.AddTransform(smev);

            // Добавляем transform для канонизации.
            XmlDsigC14NTransform c14 = new XmlDsigC14NTransform();

            reference.AddTransform(c14);

            // Добавляем ссылку на подписываемые данные
            signedXml.AddReference(reference);

            // Создаем объект KeyInfo.
            KeyInfo keyInfo = new KeyInfo();

            // Добавляем сертификат в KeyInfo
            keyInfo.AddClause(new KeyInfoX509Data(Certificate));

            // Добавляем KeyInfo в SignedXml.
            signedXml.KeyInfo = keyInfo;

            // Можно явно проставить алгоритм подписи: ГОСТ Р 34.10.
            // Если сертификат ключа подписи ГОСТ Р 34.10
            // и алгоритм ключа подписи не задан, то будет использован
            // XmlDsigGost3410Url
            // signedXml.SignedInfo.SignatureMethod =
            //     CPSignedXml.XmlDsigGost3410_2012_256Url;

            // Вычисляем подпись.
            signedXml.ComputeSignature();

            // Получаем XML представление подписи и сохраняем его
            // в отдельном node.
            XmlElement xmlDigitalSignature = signedXml.GetXml();

            // Добавляем node подписи в XML документ.
            doc.DocumentElement.AppendChild(doc.ImportNode(
                                                xmlDigitalSignature, true));

            // При наличии стартовой XML декларации ее удаляем
            // (во избежание повторного сохранения)
            if (doc.FirstChild is XmlDeclaration)
            {
                doc.RemoveChild(doc.FirstChild);
            }

            return(doc);
        }
Пример #8
0
        /// <summary>
        /// Creates a new pending request for the current session.
        /// </summary>
        /// <param name="landingUrl">The landing page of the SignResponse</param>
        /// <param name="language">The language of the e-contract.be pages, <c>null</c> for the default language</param>
        /// <param name="properties">Additional properties (location, role, visibility info, ...) for the signature request</param>
        /// <param name="authorization">The optional authorization that the signer must match too to be authorized</param>
        /// <returns>The base64 encoded PendingRequest, to be used as value for the "PendingRequest"-input</returns>
        public string GeneratePendingRequest(Uri landingUrl, string language, SignatureRequestProperties properties, Authorization authorization)
        {
            if (landingUrl == null)
            {
                throw new ArgumentNullException("landingUrl");
            }

            //Prepare browser post message (to return)
            var pendingRequest = new PendingRequest()
            {
                OptionalInputs = new OptionalInputs()
                {
                    AdditionalProfile = "urn:oasis:names:tc:dss:1.0:profiles:asynchronousprocessing",
                    ResponseID        = this.ServerId,
                    MessageID         = new AttributedURIType()
                    {
                        Value = this.ClientId
                    },
                    Timestamp = new TimestampType()
                    {
                        Created = new AttributedDateTime()
                        {
                            Value = DateTime.UtcNow
                        },
                        Expires = new AttributedDateTime()
                        {
                            Value = DateTime.UtcNow.AddMinutes(10)
                        }
                    },
                    ReplyTo = new EndpointReferenceType()
                    {
                        Address = new AttributedURIType()
                        {
                            Value = landingUrl.AbsoluteUri
                        }
                    },
                    ReturnSignerIdentity          = new ReturnSignerIdentity(),
                    Language                      = string.IsNullOrEmpty(language) ? null : language,
                    VisibleSignatureConfiguration = properties?.Configuration,
                    Policy = authorization?.Policy
                },
            };

            //Prepare Sign
            var pendingRequestXml = new XmlDocument()
            {
                PreserveWhitespace = true
            };

            using (var pendingRequestWriter = pendingRequestXml.CreateNavigator().AppendChild())
            {
                requestSerializer.Serialize(pendingRequestWriter, pendingRequest);
            }

            var signedXml = new SignedXml(pendingRequestXml);

            signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl;
            signedXml.SignedInfo.SignatureMethod        = SignedXml.XmlDsigHMACSHA1Url;
            var docRef = new Reference("")
            {
                DigestMethod = "http://www.w3.org/2000/09/xmldsig#sha1"
            };

            docRef.AddTransform(new XmlDsigEnvelopedSignatureTransform());
            docRef.AddTransform(new XmlDsigExcC14NTransform());
            signedXml.AddReference(docRef);

            //Add Key Info
            var keyRefXml = new XmlDocument()
            {
                PreserveWhitespace = true
            };

            if (null == tRefSerializer)
            {
                tRefSerializer = new XmlSerializer(typeof(SecurityTokenReferenceType), null, new Type[0], new XmlRootAttribute("SecurityTokenReference"), "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
            }
            using (var keyRefXmlWriter = keyRefXml.CreateNavigator().AppendChild())
            {
                tRefSerializer.Serialize(keyRefXmlWriter, this.KeyReference);
            }
            signedXml.KeyInfo = new KeyInfo();
            signedXml.KeyInfo.AddClause(new KeyInfoNode(keyRefXml.DocumentElement));

            //Compute signature
            signedXml.ComputeSignature(new HMACSHA1(this.KeyValue));

            //Append signature to document
            var nsmgr = new XmlNamespaceManager(pendingRequestXml.NameTable);

            nsmgr.AddNamespace("async", "urn:oasis:names:tc:dss:1.0:profiles:asynchronousprocessing:1.0");
            nsmgr.AddNamespace("dss", "urn:oasis:names:tc:dss:1.0:core:schema");
            pendingRequestXml.SelectSingleNode("/async:PendingRequest/dss:OptionalInputs", nsmgr).AppendChild(signedXml.GetXml());

            trace.TraceEvent(TraceEventType.Information, 0, "Generated pending request");
            msgTrace.TraceData(TraceEventType.Information, 0, pendingRequestXml.CreateNavigator());

            //Serialize and encode
            var stream = new MemoryStream();

            pendingRequestXml.Save(stream);

            return(Convert.ToBase64String(stream.ToArray()));
        }
Пример #9
0
        /// <summary>
        /// Đây là ví dụ ký một Thẻ, chúng ta có thể ký nhiều thẻ bằng cách tạo nhiều Reference
        /// SignedXml signer = new SignedXml(doc);
        /// signer.AddReference(new Reference("#tag1"));
        /// signer.AddReference(new Reference("#tag3"));
        /// </summary>
        /// <param name="xmldoc"></param>
        /// <param name="cert">Certificate này phải chứa Private Key</param>
        /// <param name="uri">chứa URI tới dữ liệu cần ký: nếu Uri="" tức là ký toàn bộ tài liệu</param>
        /// <returns></returns>
        public static string Sign(XmlDocument xmldoc, X509Certificate2 cert, string uri)
        {
            const bool c14 = true;

            if (xmldoc == null || cert == null)
            {
                return(null);
            }
            if (String.IsNullOrEmpty(uri))
            {
                throw new Exception("Chưa cung cấp thông tin id thẻ invoiceData");
            }

            if (!uri.StartsWith("#"))
            {
                uri = "#" + uri;
            }

            if (!cert.HasPrivateKey)
            {
                throw new Exception("Chứng thư không có khóa bí mật");
            }

            // Creating the XML signing object.
            SignedXml sxml = new SignedXml(xmldoc);

            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.
            sxml.KeyInfo = keyInfo;

            sxml.SigningKey = cert.PrivateKey;

            // Set the canonicalization method for the document.
            sxml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigCanonicalizationUrl; // No comments.

            ////============================Add SignatureProperties===========================//

            // Create an empty reference (not enveloped) for the XPath
            // transformation.
            Reference r = new Reference(uri);

            // Create the XPath transform and add it to the reference list.
            r.AddTransform(new XmlDsigEnvelopedSignatureTransform());
            if (c14)
            {
                XmlDsigC14NTransform c14t = new XmlDsigC14NTransform();
                r.AddTransform(c14t);
            }

            Reference reference = new Reference("#AMadeUpTimeStamp");

            // Create the XPath transform and add it to the reference list.
            reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
            if (c14)
            {
                XmlDsigC14NTransform c14t = new XmlDsigC14NTransform();
                reference.AddTransform(c14t);
            }

            ////============================Add SignatureProperties===========================//

            // Add the reference to the SignedXml object.
            sxml.AddReference(r);
            sxml.Signature.Id = "seller";
            // Compute the signature.
            sxml.ComputeSignature();

            // Get the signature XML and add it to the document element.
            XmlElement sig = sxml.GetXml();

            xmldoc.DocumentElement.AppendChild(sig);

            return(xmldoc.OuterXml);
        }
Пример #10
0
        /// <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();
            }
        }
Пример #11
0
        private void CreateCrypto(string pyt, ref XmlDocument doc, TextBox textBoxName)
        {
            XmlTextReader gf   = new XmlTextReader(pyt);
            string        buff = doc.OuterXml;
            int           j    = 0;

            //Проверка есть ли уже криптография
            for (int i = 0; i < buff.Length; i++)
            {
                string sig = "Signature";
                char   a   = buff[i];
                char   b   = sig[j];
                if (buff[i] == sig[j])
                {
                    string str = "";
                    for (int k = 0; k < sig.Length; k++)
                    {
                        str += buff[i + k];
                    }
                    //j++;
                    if (str == sig)
                    {
                        MessageBox.Show("Ключ уже создан");
                        goto BB;
                    }
                }
            }
            DSA        Key        = DSA.Create();
            string     xmls       = Key.ToXmlString(false);
            XmlElement xmlElement = doc.CreateElement("KEy");

            xmlElement.InnerText = xmls;
            doc.DocumentElement.AppendChild(xmlElement);
            dris.Key = Key;
            SignedXml signedXml = new SignedXml(doc);

            signedXml.SigningKey = Key;
            Reference reference = new Reference();

            reference.Uri = "";
            XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();

            reference.AddTransform(env);
            signedXml.AddReference(reference);
            signedXml.ComputeSignature();
            XmlElement xmlDigitalSignature = signedXml.GetXml();

            doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, true));

            if (doc.FirstChild is XmlDeclaration)
            {
                doc.RemoveChild(doc.FirstChild);
            }
            gf.Close();
            XmlTextWriter xmltw = new XmlTextWriter(pyt, System.Text.Encoding.UTF8);

            doc.WriteTo(xmltw);
            xmltw.Close();
            BB :;
            if (gf.ReadState != ReadState.Closed)
            {
                gf.Close();
            }

            //XmlDocument doc = new XmlDocument();
            //doc.PreserveWhitespace = false;
            //XmlTextReader gf = new XmlTextReader(pyt);
            //doc.Load(gf);
            //string buff = doc.OuterXml;
            //int j = 0;
            ////Проверка есть ли уже криптография
            //for(int i =0;i<buff.Length;i++)
            //{
            //    string sig = "Signature";
            //    char a = buff[i];
            //    char b = sig[j];
            //    if(buff[i]==sig[j])
            //    {
            //        string str = "";
            //        for(int k=0;k<sig.Length;k++)
            //        {
            //            str += buff[i + k];
            //        }
            //        //j++;
            //        if(str == sig)
            //        {
            //            MessageBox.Show("Ключ уже создан");
            //            goto BB;
            //        }
            //    }
            //}
            //DSA Key = DSA.Create();
            //dris.Key = Key;
            //SignedXml signedXml = new SignedXml(doc);
            //signedXml.SigningKey = Key;
            //Signature XMLSignature = signedXml.Signature;
            //Reference reference = new Reference("");
            //XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();
            //reference.AddTransform(env);
            //XMLSignature.SignedInfo.AddReference(reference);
            //KeyInfo keyInfo = new KeyInfo();
            //keyInfo.AddClause(new DSAKeyValue((DSA)Key));
            //XMLSignature.KeyInfo = keyInfo;
            //signedXml.ComputeSignature();
            //XmlElement xmlDigitalSignature = signedXml.GetXml();
            //doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, true));
            ////DSA dfs = DSA.Create();
            ////dfs.FromXmlString("");
            //XmlElement ssdw = doc.CreateElement("Key", Key.SignatureAlgorithm);
            //doc.DocumentElement.AppendChild(ssdw);
            //if (doc.FirstChild is XmlDeclaration)
            //{
            //    doc.RemoveChild(doc.FirstChild);
            //}
            //gf.Close();
            ////doc.Save(pyt);
            //XmlTextWriter xmltw = new XmlTextWriter(pyt, System.Text.Encoding.UTF8);
            //doc.WriteTo(xmltw);
            //xmltw.Close();
            //BB:;
            ////
        }
Пример #12
0
        public string FirmarXml(string tramaXml)
        {
            // Vamos a firmar el XML con la ruta del certificado que está como serializado.

            var certificate = new X509Certificate2();

            certificate.Import(Convert.FromBase64String(RutaCertificadoDigital),
                               PasswordCertificado, X509KeyStorageFlags.MachineKeySet);

            var xmlDoc = new XmlDocument();

            string resultado;

            using (var documento = new MemoryStream(Convert.FromBase64String(tramaXml)))
            {
                xmlDoc.PreserveWhitespace = true;
                xmlDoc.Load(documento);
                int tipo;

                if (TipoDocumento == 1 || TipoDocumento == 2 || TipoDocumento == 3 || TipoDocumento == 4)
                {
                    tipo = 1;
                }
                else
                {
                    tipo = 0;
                }

                var nodoExtension = xmlDoc.GetElementsByTagName("ExtensionContent", EspacioNombres.ext)
                                    .Item(tipo);
                if (nodoExtension == null)
                {
                    throw new InvalidOperationException("No se pudo encontrar el nodo ExtensionContent en el XML");
                }
                nodoExtension.RemoveAll();

                // Creamos el objeto SignedXml.
                var signedXml = new SignedXml(xmlDoc)
                {
                    SigningKey = (RSA)certificate.PrivateKey
                };
                signedXml.SigningKey = certificate.PrivateKey;
                var xmlSignature = signedXml.Signature;

                var env = new XmlDsigEnvelopedSignatureTransform();

                var reference = new Reference(string.Empty);
                reference.AddTransform(env);
                xmlSignature.SignedInfo.AddReference(reference);

                var keyInfo  = new KeyInfo();
                var x509Data = new KeyInfoX509Data(certificate);

                x509Data.AddSubjectName(certificate.Subject);

                keyInfo.AddClause(x509Data);
                xmlSignature.KeyInfo = keyInfo;
                xmlSignature.Id      = "SignatureErickOrlando";
                signedXml.ComputeSignature();

                // Recuperamos el valor Hash de la firma para este documento.
                if (reference.DigestValue != null)
                {
                    DigestValue = Convert.ToBase64String(reference.DigestValue);
                }
                ValorFirma = Convert.ToBase64String(signedXml.SignatureValue);

                nodoExtension.AppendChild(signedXml.GetXml());

                var settings = new XmlWriterSettings()
                {
                    Encoding = Encoding.GetEncoding("ISO-8859-1")
                };

                using (var memDoc = new MemoryStream())
                {
                    using (var writer = XmlWriter.Create(memDoc, settings))
                    {
                        xmlDoc.WriteTo(writer);
                    }

                    resultado = Convert.ToBase64String(memDoc.ToArray());
                }
            }

            return(resultado);
        }
Пример #13
0
        /// <summary>
        /// Signs a XML file (enveloping signature) using a digital certificate
        /// </summary>
        /// <param name="encodingPath">Used for non-xml, the root path of the document being signed, used for temporary encoding file</param>
        /// <param name="signatureType">This will be XML or Non-XML</param>
        /// <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(XmlSignatureType signatureType, byte[] xml, string certFile, string certPassword, bool signWithSha256, string encodingPath = "")
        {
            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!");
            }

            //If this is NOT XML, then we have to convert it and stick it in XML first
            if (signatureType == XmlSignatureType.NonXML)
            {
                //base64 encode it
                string strEncodedImage;
                strEncodedImage = System.Convert.ToBase64String(xml, 0, xml.Length);

                //create a small xml file and put the encoded Image data inside
                // Create an XmlWriterSettings object with the correct options.
                XmlWriter         writer   = null;
                XmlWriterSettings settings = new XmlWriterSettings();
                settings.Indent             = true;
                settings.IndentChars        = ("\t");
                settings.OmitXmlDeclaration = false;
                settings.NewLineHandling    = NewLineHandling.Replace;
                settings.CloseOutput        = true;

                string metadataFileName = encodingPath + "\\TempEncoded.xml";

                // Create the XmlWriter object and write some content.
                writer = XmlWriter.Create(metadataFileName, settings);
                writer.WriteStartElement("Wrapper", "");
                writer.WriteString(strEncodedImage);
                writer.WriteEndElement();

                //Close the XmlTextWriter.
                writer.WriteEndDocument();
                writer.Close();
                writer.Flush();
                xml = File.ReadAllBytes(encodingPath + "\\TempEncoded.xml");
            }


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

                // create 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)));
            }
        }
Пример #14
0
    // 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);
    }
Пример #15
0
        private static string AddSignature(X509Certificate2 certificate, string xml, bool useFingerprint, bool addReferenceURI)
        {
            var doc = new XmlDocument
            {
                PreserveWhitespace = true
            };

            try
            {
                doc.LoadXml(xml);
            }
            catch (Exception)
            {
                return(xml);
            }

            // document is empty, parse issue, etc
            if (doc.DocumentElement == null)
            {
                return(xml);
            }

            // already has a signature on the root element
            if (doc.DocumentElement["Signature", SignedXml.XmlDsigNamespaceUrl] != null)
            {
                return(xml);
            }

            var rsaKey = (RSACryptoServiceProvider)certificate.PrivateKey;

            var ki = new KeyInfo();

            if (useFingerprint)
            {
                ki.AddClause(new KeyInfoName(certificate.Thumbprint));
            }
            else
            {
                ki.AddClause(new KeyInfoX509Data(certificate));
            }

            var signedXml = new SignedXml(doc)
            {
                SigningKey = rsaKey
            };

            var reference = new Reference("")
            {
                DigestMethod = "http://www.w3.org/2001/04/xmlenc#sha256"
            };

            if (addReferenceURI)
            {
                reference.Uri = "#_a75adf55-01d7-40cc-929f-dbd8372ebdfc";
            }
            reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
            reference.AddTransform(new XmlDsigExcC14NTransform());

            signedXml.Signature.SignedInfo.AddReference(reference);
            signedXml.Signature.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl;
            signedXml.Signature.SignedInfo.SignatureMethod        = XmlDsigRsaSha256Url;
            signedXml.Signature.KeyInfo = ki;

            signedXml.ComputeSignature();
            var signature = signedXml.GetXml().CloneNode(true);

            doc.DocumentElement.AppendChild(doc.ImportNode(signature, true));

            return(doc.OuterXml);
        }
Пример #16
0
        /// <summary>
        /// O método assina digitalmente o arquivo XML passado por parâmetro e
        /// grava o XML assinado com o mesmo nome, sobreponto o XML informado por parâmetro.
        /// Disponibiliza também uma propriedade com uma string do xml assinado (this.vXmlStringAssinado)
        /// </summary>
        /// <param name="conteudoXML">Conteúdo do XML</param>
        /// <param name="tagAssinatura">Nome da tag onde é para ficar a assinatura</param>
        /// <param name="tagAtributoId">Nome da tag que tem o atributo ID, tag que vai ser assinada</param>
        /// <param name="x509Cert">Certificado a ser utilizado na assinatura</param>
        /// <param name="empresa">Índice da empresa que está solicitando a assinatura</param>
        /// <param name="algorithmType">Tipo de algoritimo para assinatura do XML.</param>
        /// <remarks>
        /// Autor: Wandrey Mundin Ferreira
        /// Data: 04/06/2008
        /// </remarks>
        private void Assinar(XmlDocument conteudoXML,
                             string tagAssinatura,
                             string tagAtributoId,
                             X509Certificate2 x509Cert,
                             int empresa,
                             AlgorithmType algorithmType,
                             bool comURI)
        {
            try
            {
                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)");
                }
                // Existe mais de uma tag a ser assinada
                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) && Empresas.Configuracoes[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;
                            }

                            // Create a reference to be signed
                            Reference reference = new Reference();
                            reference.Uri = "";

                            // pega o uri que deve ser assinada
                            XmlElement childElemen = (XmlElement)childNodes;

                            if (comURI)
                            {
                                if (childElemen.GetAttributeNode("Id") != null)
                                {
                                    reference.Uri = "#" + childElemen.GetAttributeNode("Id").Value;
                                }
                                else if (childElemen.GetAttributeNode("id") != null)
                                {
                                    reference.Uri = "#" + childElemen.GetAttributeNode("id").Value;
                                }
                            }

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

#if _fw46
                            //A3
                            if (!String.IsNullOrEmpty(Empresas.Configuracoes[empresa].CertificadoPIN) &&
                                clsX509Certificate2Extension.IsA3(x509Cert) &&
                                !Empresas.Configuracoes[empresa].CertificadoPINCarregado)
                            {
                                x509Cert.SetPinPrivateKey(Empresas.Configuracoes[empresa].CertificadoPIN);
                                Empresas.Configuracoes[empresa].CertificadoPINCarregado = true;
                            }

                            if (algorithmType.Equals(AlgorithmType.Sha256))
                            {
                                signedXml.SignedInfo.SignatureMethod = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";
                                signedXml.SigningKey = x509Cert.GetRSAPrivateKey();
                            }
#endif

                            if (algorithmType.Equals(AlgorithmType.Sha1))
                            {
                                signedXml.SigningKey = x509Cert.PrivateKey;
                            }

                            // Add an enveloped transformation to the reference.
                            reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
                            reference.AddTransform(new XmlDsigC14NTransform());

                            // Add the reference to the SignedXml object.
                            signedXml.AddReference(reference);

#if _fw46
                            if (algorithmType.Equals(AlgorithmType.Sha256))
                            {
                                reference.DigestMethod = "http://www.w3.org/2001/04/xmlenc#sha256";
                            }
#endif

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

                            if (tagAssinatura.Equals(tagAtributoId) && Empresas.Configuracoes[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)
            {
                #region #10316

                /*
                 * Solução para o problema do certificado do tipo A3
                 * Marcelo
                 * 29/07/2013
                 */

                AssinaturaValida = false;

                if (clsX509Certificate2Extension.IsA3(x509Cert))
                {
                    x509Cert = Empresas.ResetCertificado(empresa);
                    if (!TesteCertificado)
                    {
                        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());// #12342 concatenar com a mensagem original
                    }
                }
                else
                {
                    throw;
                }

                #endregion #10316
            }
            catch
            {
                throw;
            }
        }
Пример #17
0
        private static XmlDocument SignXml()
        {
            XmlDocument xmlDoc = new XmlDocument();

            xmlDoc.PreserveWhitespace = true;
            xmlDoc.Load(".\\certificates\\samlRequestTemplate.xml");
            X509Certificate2 certificate = CertificateHelper.GetCertificate(".\\certificates\\HuaweiCA.p12", "Pr0d1234");

            //AsymmetricAlgorithm key = certificate.PrivateKey;
            AsymmetricAlgorithm key = certificate.PrivateKey;

            XmlNamespaceManager ns = new XmlNamespaceManager(xmlDoc.NameTable);

            ns.AddNamespace("saml", "urn:oasis:names:tc:SAML:2.0:assertion");
            ns.AddNamespace("samlp", "urn:oasis:names:tc:SAML:2.0:protocol");

            XmlElement issuerNode = (XmlElement)xmlDoc.DocumentElement.SelectSingleNode("saml:Issuer", ns);

            SignedXml signedXml = new SignedXml(xmlDoc.DocumentElement);

            signedXml.SigningKey = key;
            signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl;

            KeyInfo keyInfo = new KeyInfo();

            //XmlDocument keyDoc = new XmlDocument();

            //keyDoc.LoadXml(certificate.PublicKey.Key.ToXmlString(false));
            //keyInfo.LoadXml(keyDoc.DocumentElement);
            keyInfo.AddClause(new KeyInfoX509Data(certificate));
            signedXml.KeyInfo = keyInfo;

            string refId = xmlDoc.DocumentElement.GetAttribute("ID");

            Reference reference = new Reference();

            reference.Uri = "#" + refId;

            XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();

            reference.AddTransform(env);

            XmlDsigExcC14NTransform env2 = new XmlDsigExcC14NTransform();

            env2.InclusiveNamespacesPrefixList = "#default code ds kind rw saml samlp typens";
            reference.AddTransform(env2);

            signedXml.AddReference(reference);

            signedXml.ComputeSignature();
            XmlElement xmlDigitalSignature = signedXml.GetXml();

            xmlDoc.DocumentElement.InsertAfter(xmlDoc.ImportNode(xmlDigitalSignature, true), issuerNode);

            //xmlDoc.NameTable.Add("samlp");
            //XmlElement nameIDPolicyElem = xmlDoc.CreateElement("samlp", "NameIDPolicy", "urn:oasis:names:tc:SAML:2.0:protocol");
            //nameIDPolicyElem.SetAttribute("AllowCreate", "False");

            //xmlDoc.DocumentElement.AppendChild(nameIDPolicyElem);

            xmlDoc.Save("samleRequestCSharp.xml");

            return(xmlDoc);
        }
Пример #18
0
        private bool WriteLicenseToFile(string appDir, bool spfold, int version)
        {
            var str1 = string.Format("{0}-{1}-{2}-{3}-{4}", "U3", "AAAA", "AAAA", "AAAA", "AAAA");

            var byteList1 = new List <byte>();


            byteList1.AddRange(Encoding.ASCII.GetBytes(string.Format("{0}-{1}", str1, "NUUN")));
            if (version != 20172)
            {
                List <string> stringList = new List <string>()
                {
                    "<root>",
                    "  <TimeStamp2 Value=\"cn/lkLOZ3vFvbQ==\"/>",
                    "  <TimeStamp Value=\"jWj8PXAeZMPzUw==\"/>",
                    "  <License id=\"Terms\">",
                    "    <ClientProvidedVersion Value=\"\"/>",
                    string.Format("    <DeveloperData Value=\"{0}\"/>", (object)Convert.ToBase64String(byteList1.ToArray())),
                    "    <Features>"
                };

                foreach (var num in LicHeader.ReadAll())
                {
                    stringList.Add(string.Format("      <Feature Value=\"{0}\"/>", (object)num));
                }
                stringList.Add("    </Features>");
                if (version < 500)
                {
                    stringList.Add("    <LicenseVersion Value=\"4.x\"/>");
                }
                if (version >= 500 && version < 2017)
                {
                    stringList.Add("    <LicenseVersion Value=\"5.x\"/>");
                }
                if (version == 2017)
                {
                    stringList.Add("    <LicenseVersion Value=\"2017.x\"/>");
                }
                if (version == 20171)
                {
                    stringList.Add("    <LicenseVersion Value=\"6.x\"/>");
                }
                stringList.Add("    <MachineBindings>");
                stringList.Add("    </MachineBindings>");
                stringList.Add("    <MachineID Value=\"\"/>");
                stringList.Add("    <SerialHash Value=\"\"/>");
                stringList.Add(string.Format("    <SerialMasked Value=\"{0}-XXXX\"/>", (object)str1));
                DateTime now = DateTime.Now;
                stringList.Add(string.Format("    <StartDate Value=\"{0}T00:00:00\"/>", (object)now.AddDays(-1.0).ToString("yyyy-MM-dd")));
                stringList.Add("    <StopDate Value=\"\"/>");
                stringList.Add(string.Format("    <UpdateDate Value=\"{0}T00:00:00\"/>", (object)now.AddYears(10).ToString("yyyy-MM-dd")));
                stringList.Add("  </License>");
                stringList.Add("");
                stringList.Add("<Signature xmlns=\"http://www.w3.org/2000/09/xmldsig#\">");
                stringList.Add("<SignedInfo>");
                stringList.Add("<CanonicalizationMethod Algorithm=\"http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments\"/>");
                stringList.Add("<SignatureMethod Algorithm=\"http://www.w3.org/2000/09/xmldsig#rsa-sha1\"/>");
                stringList.Add("<Reference URI=\"#Terms\">");
                stringList.Add("<Transforms>");
                stringList.Add("<Transform Algorithm=\"http://www.w3.org/2000/09/xmldsig#enveloped-signature\"/>");
                stringList.Add("</Transforms>");
                stringList.Add("<DigestMethod Algorithm=\"http://www.w3.org/2000/09/xmldsig#sha1\"/>");
                stringList.Add("<DigestValue>oeMc1KScgy617DHMPTxbYhqNjIM=</DigestValue>");
                stringList.Add("</Reference>");
                stringList.Add("</SignedInfo>");
                stringList.Add("<SignatureValue>WuzMPTi0Ko1vffk9gf9ds/iU0b0K8UHaLpi4kWgm6q1am5MPTYYnzH1InaSWuzYo");
                stringList.Add("EpJThKspOZdO0JISeEolNdJVf3JpsY55OsD8UaruvhwZn4r9pLeNSC7SzQ1rvAWP");
                stringList.Add("h77XaHizhVVs15w6NYevP27LTxbZaem5L8Zs+34VKXQFeG4g0dEI/Jhl70TqE0CS");
                stringList.Add("YNF+D0zqEtyMNHsh0Rq/vPLSzPXUN12jfPLZ3dO9B+9/mG7Ljd6emZjjLZUVuSKQ");
                stringList.Add("uKxN5jlHZsm2kRMudijICV6YOWMPT+oZePlCg+BJQg5/xcN5aYVBDZhNeuNwQL1H");
                stringList.Add("MPT/GJPxVuETgd9k8c4uDg==</SignatureValue>");
                stringList.Add("</Signature>");
                stringList.Add("</root>");

                string str2 = "";
                if (version < 500)
                {
                    str2 = "Unity_v4.x.ulf";
                }
                if (version >= 500 && version < 2017)
                {
                    str2 = "Unity_v5.x.ulf";
                }
                if (version == 2017)
                {
                    str2 = "Unity_v2017.x.ulf";
                }
                if (version == 20171)
                {
                    str2 = "Unity_lic.ulf";
                }

                var path = string.Empty;
                if (spfold)
                {
                    path = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "\\Unity";
                    if (!Directory.Exists(path))
                    {
                        try
                        {
                            Directory.CreateDirectory(path);
                        }
                        catch (Exception ex)
                        {
                            spfold = false;
                            var num = (int)MessageBox.Show(ex.Message, string.Empty, MessageBoxButtons.OK);
                        }
                    }
                }
                if (spfold)
                {
                    if (File.Exists(path + "/" + str2))
                    {
                        spfold = TestAtr(path + "/" + str2);
                        if (spfold && MessageBox.Show(string.Format("Replace the \"{0}\\{1}\"?", path, str2), string.Empty,
                                                      MessageBoxButtons.YesNo, MessageBoxIcon.Question) != System.Windows.Forms.DialogResult.OK)
                        {
                            stringList.Clear();
                            return(true);
                        }
                    }
                    if (spfold)
                    {
                        try
                        {
                            if (version < 500)
                            {
                                str2 = "Unity_v4.x.ulf";
                            }
                            if (version >= 500 && version < 2017)
                            {
                                str2 = "Unity_v5.x.ulf";
                            }
                            if (version == 2017)
                            {
                                str2 = "Unity_v2017.x.ulf";
                            }
                            if (version == 20171)
                            {
                                str2 = "Unity_lic.ulf";
                            }
                            if (str2 == "Unity_lic.ulf")
                            {
                                using (FileStream fileStream = new FileStream(path + "/" + str2, FileMode.Append))
                                {
                                    foreach (object obj in stringList)
                                    {
                                        byte[] bytes = Encoding.ASCII.GetBytes(string.Format("{0}\r", obj));
                                        fileStream.Write(bytes, 0, bytes.Length);
                                    }
                                    fileStream.Flush();
                                    fileStream.Close();
                                }
                            }
                            else
                            {
                                File.WriteAllLines(path + "/" + str2, (IEnumerable <string>)stringList);
                            }
                        }
                        catch (Exception ex)
                        {
                            spfold = false;
                            int num = (int)MessageBox.Show(ex.Message, string.Empty, MessageBoxButtons.OK);
                        }
                    }
                }
                if (!spfold)
                {
                    if (File.Exists(appDir + "/" + str2))
                    {
                        if (TestAtr(appDir + "/" + str2))
                        {
                            if (MessageBox.Show(string.Format("Replace the \"{0}\\{1}\"?", appDir, str2), string.Empty,
                                                MessageBoxButtons.YesNo, MessageBoxIcon.Question) !=
                                System.Windows.Forms.DialogResult.OK)
                            {
                                stringList.Clear();
                                return(true);
                            }
                        }
                        else
                        {
                            stringList.Clear();
                            return(false);
                        }
                    }
                    try
                    {
                        if (version < 500)
                        {
                            str2 = "Unity_v4.x.ulf";
                        }
                        if (version >= 500 && version < 2017)
                        {
                            str2 = "Unity_v5.x.ulf";
                        }
                        if (version == 2017)
                        {
                            str2 = "Unity_v2017.x.ulf";
                        }
                        if (version == 20171)
                        {
                            str2 = "Unity_lic.ulf";
                        }
                        if (str2 == "Unity_lic.ulf")
                        {
                            using (FileStream fileStream = new FileStream(path + "/" + str2, FileMode.Append))
                            {
                                foreach (object obj in stringList)
                                {
                                    byte[] bytes = Encoding.ASCII.GetBytes(string.Format("{0}\r", obj));
                                    fileStream.Write(bytes, 0, bytes.Length);
                                }
                                fileStream.Flush();
                                fileStream.Close();
                            }
                        }
                        else
                        {
                            File.WriteAllLines(path + "/" + str2, (IEnumerable <string>)stringList);
                        }
                    }
                    catch (Exception ex)
                    {
                        stringList.Clear();
                        int num = (int)MessageBox.Show(ex.Message, string.Empty, MessageBoxButtons.OK);
                        return(false);
                    }
                }
                stringList.Clear();
                return(true);
            }
            string s = string.Format("{0}-{1}-{2}-{3}-{4}-{5}", "U3", "AAAA", "AAAA", "AAAA", "AAAA", "AAAA");

            int[] numArray = LicHeader.ReadAll();
            if (s.Length != 27)
            {
                int num = (int)MessageBox.Show("Invalid Key must be \"27\" chars.", string.Empty, MessageBoxButtons.OK);
                return(false);
            }
            string path2        = "Unity_lic.ulf";
            string str3         = s.Remove(s.Length - 4, 4) + "XXXX";
            string base64String = Convert.ToBase64String(((IEnumerable <byte>)((IEnumerable <byte>) new byte[4]
            {
                (byte)1,
                (byte)0,
                (byte)0,
                (byte)0
            }).Concat <byte>((IEnumerable <byte>)Encoding.ASCII.GetBytes(s)).ToArray <byte>()).ToArray <byte>());
            string   str4     = "6.x";
            string   str5     = "false";
            string   str6     = "";
            DateTime dateTime = DateTime.UtcNow;

            dateTime = dateTime.AddDays(-1.0);
            string str7 = dateTime.ToString("s", (IFormatProvider)CultureInfo.InvariantCulture);
            Dictionary <string, string> dictionary = new Dictionary <string, string>();
            string str8  = "";
            string str9  = "";
            string str10 = "";
            string str11 = "";

            dateTime = DateTime.UtcNow;
            dateTime = dateTime.AddYears(10);
            string            str12        = dateTime.ToString("s", (IFormatProvider)CultureInfo.InvariantCulture);
            MemoryStream      memoryStream = new MemoryStream();
            XmlWriterSettings settings     = new XmlWriterSettings()
            {
                Indent             = true,
                IndentChars        = "  ",
                NewLineChars       = "\n",
                OmitXmlDeclaration = true,
                Encoding           = Encoding.ASCII
            };

            using (XmlWriter xmlWriter = XmlWriter.Create((Stream)memoryStream, settings))
            {
                xmlWriter.WriteStartElement("root");
                xmlWriter.WriteStartElement("License");
                xmlWriter.WriteAttributeString("id", "Terms");
                xmlWriter.WriteStartElement("AlwaysOnline");
                xmlWriter.WriteAttributeString("Value", str5);
                xmlWriter.WriteEndElement();
                xmlWriter.WriteStartElement("ClientProvidedVersion");
                xmlWriter.WriteAttributeString("Value", str6);
                xmlWriter.WriteEndElement();
                xmlWriter.WriteStartElement("DeveloperData");
                xmlWriter.WriteAttributeString("Value", base64String);
                xmlWriter.WriteEndElement();
                xmlWriter.WriteStartElement("Features");
                foreach (int num in numArray)
                {
                    xmlWriter.WriteStartElement("Feature");
                    xmlWriter.WriteAttributeString("Value", num.ToString());
                    xmlWriter.WriteEndElement();
                }
                xmlWriter.WriteFullEndElement();
                xmlWriter.WriteStartElement("InitialActivationDate");
                xmlWriter.WriteAttributeString("Value", str7);
                xmlWriter.WriteEndElement();
                xmlWriter.WriteStartElement("LicenseVersion");
                xmlWriter.WriteAttributeString("Value", str4);
                xmlWriter.WriteEndElement();
                xmlWriter.WriteStartElement("MachineBindings");
                foreach (KeyValuePair <string, string> keyValuePair in dictionary)
                {
                    xmlWriter.WriteStartElement("Binding");
                    xmlWriter.WriteAttributeString("Key", keyValuePair.Key);
                    xmlWriter.WriteAttributeString("Value", keyValuePair.Value);
                    xmlWriter.WriteEndElement();
                }
                xmlWriter.WriteFullEndElement();
                xmlWriter.WriteStartElement("MachineID");
                xmlWriter.WriteAttributeString("Value", str8);
                xmlWriter.WriteEndElement();
                xmlWriter.WriteStartElement("SerialHash");
                xmlWriter.WriteAttributeString("Value", str9);
                xmlWriter.WriteEndElement();
                xmlWriter.WriteStartElement("SerialMasked");
                xmlWriter.WriteAttributeString("Value", str3);
                xmlWriter.WriteEndElement();
                xmlWriter.WriteStartElement("StartDate");
                xmlWriter.WriteAttributeString("Value", str10);
                xmlWriter.WriteEndElement();
                xmlWriter.WriteStartElement("StopDate");
                xmlWriter.WriteAttributeString("Value", str11);
                xmlWriter.WriteEndElement();
                xmlWriter.WriteStartElement("UpdateDate");
                xmlWriter.WriteAttributeString("Value", str12);
                xmlWriter.WriteEndElement();
                xmlWriter.WriteEndElement();
                xmlWriter.WriteEndElement();
                xmlWriter.Flush();
            }
            memoryStream.Position = 0L;
            XmlDocument document = new XmlDocument()
            {
                PreserveWhitespace = true
            };

            document.Load((Stream)memoryStream);
            SignedXml signedXml = new SignedXml(document)
            {
                SigningKey = (AsymmetricAlgorithm) new RSACryptoServiceProvider()
            };
            Reference reference = new Reference()
            {
                Uri = "#Terms"
            };

            reference.AddTransform((System.Security.Cryptography.Xml.Transform) new XmlDsigEnvelopedSignatureTransform());
            signedXml.AddReference(reference);
            signedXml.ComputeSignature();
            StringBuilder output = new StringBuilder();

            using (XmlWriter w = XmlWriter.Create(output, settings))
            {
                XmlDocument xmlDocument1 = new XmlDocument();
                string      innerXml     = document.InnerXml;
                xmlDocument1.InnerXml = innerXml;
                XmlDocument xmlDocument2    = xmlDocument1;
                XmlElement  documentElement = xmlDocument2.DocumentElement;
                if (documentElement != null)
                {
                    XmlNode newChild = xmlDocument2.ImportNode((XmlNode)signedXml.GetXml(), true);
                    documentElement.AppendChild(newChild);
                }
                xmlDocument2.Save(w);
                w.Flush();
            }
            string contents = output.Replace(" />", "/>").ToString();
            string str13    = spfold ? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "Unity") : appDir;
            string path1    = Path.Combine(str13, path2);

            try
            {
                Directory.CreateDirectory(str13);
                if (File.Exists(path1) && this.TestAtr(path1) && MessageBox.Show(string.Format("Replace the \"{0}\"?", (object)path1), string.Empty, MessageBoxButtons.YesNo, MessageBoxIcon.Question) != System.Windows.Forms.DialogResult.OK)
                {
                    return(true);
                }
                File.WriteAllText(path1, contents);
            }
            catch (Exception ex)
            {
                int num = (int)MessageBox.Show(ex.Message, string.Empty, MessageBoxButtons.OK);
                return(false);
            }
            return(true);
        }
        /// <summary>
        /// 该方法进行数字签名XML文件传递的参数和
        ///写相同名称,sobreponto通过参数告知XML签署的XML。
        ///它还提供了一个与物业签订XML字符串(this.vXmlStringAssinado)
        /// </summary>
        /// <param name="arqXmlAssinar">要签名XML文件名</param>
        /// <param name="tagAssinatura">标签名在得到签名</param>
        /// <param name="tagAtributoId">有将要签署的ID属性标记标签名称</param>
        /// <param name="x509Cert">在签名时使用证书</param>
        public void EncryptXmlDocument(string arqXmlAssinar, string tagAssinatura, string tagAtributoId, X509Certificate2 x509Cert)
        {
            StreamReader sr = null;

            try
            {
                //打开XML文件进行签名和阅读你的内容
                sr = System.IO.File.OpenText(arqXmlAssinar);
                var xmlString = sr.ReadToEnd();
                sr.Close();
                sr = null;
                // 创建一个新的XML文档。
                XmlDocument doc = new XmlDocument {
                    PreserveWhitespace = false
                };
                doc.LoadXml(xmlString);
                if (doc.GetElementsByTagName(tagAssinatura).Count == 0)
                {
                    throw new Exception(tagAssinatura.Trim());
                }
                if (doc.GetElementsByTagName(tagAtributoId).Count == 0)
                {
                    throw new Exception(tagAtributoId.Trim());
                }
                // 有多个标记进行签名
                XmlNodeList lists = doc.GetElementsByTagName(tagAssinatura);
                foreach (XmlNode nodes in lists)
                {
                    foreach (XmlNode childNodes in nodes.ChildNodes)
                    {
                        if (!childNodes.Name.Equals(tagAtributoId))
                        {
                            continue;
                        }
                        if (childNodes.NextSibling != null && childNodes.NextSibling.Name.Equals("Signature"))
                        {
                            continue;
                        }
                        //创建要签名的引用
                        Reference reference = new Reference {
                            Uri = ""
                        };
                        //需要要签名的孩子
                        XmlElement childElemen = (XmlElement)childNodes;
                        if (childElemen.GetAttributeNode("Id") != null)
                        {
                            var attributeNode = childElemen.GetAttributeNode("Id");
                            if (attributeNode != null)
                            {
                                reference.Uri = "#" + attributeNode.Value;
                            }
                        }
                        else if (childElemen.GetAttributeNode("id") != null)
                        {
                            var attributeNode = childElemen.GetAttributeNode("id");
                            if (attributeNode != null)
                            {
                                reference.Uri = "#" + attributeNode.Value;
                            }
                        }
                        XmlDocument documentoNovo = new XmlDocument();
                        documentoNovo.LoadXml(nodes.OuterXml);
                        // 创建一个SignedXml对象。
                        SignedXml signedXml = new SignedXml(documentoNovo)
                        {
                            SigningKey = x509Cert.PrivateKey
                        };
                        // 将密钥添加到签名的Xml文档
                        // 向引用添加包络变换。
                        XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();
                        reference.AddTransform(env);
                        XmlDsigC14NTransform c14 = new XmlDsigC14NTransform();
                        reference.AddTransform(c14);
                        // 将引用添加到SignedXml对象。
                        signedXml.AddReference(reference);
                        // 创建一个新的键入对象
                        KeyInfo keyInfo = new KeyInfo();
                        // 将证书加载到KeyInfoX509Data对象中
                        //并将它添加到KeyInfo对象。
                        keyInfo.AddClause(new KeyInfoX509Data(x509Cert));
                        //将KeyInfo对象添加到SignedXml对象。
                        signedXml.KeyInfo = keyInfo;
                        signedXml.ComputeSignature();
                        // 获取签名的XML表示并保存它到一个XmlElement对象。
                        XmlElement xmlDigitalSignature = signedXml.GetXml();
                        // 保存该元素的XML文档中
                        nodes.AppendChild(doc.ImportNode(xmlDigitalSignature, true));
                    }
                }

                var xmlDoc = doc;
                // XML的更新字符串已经签约
                var stringXmlAssinado = xmlDoc.OuterXml;
                // 编写XML高清签名
                StreamWriter sw2 = System.IO.File.CreateText(arqXmlAssinar);
                sw2.Write(stringXmlAssinado);
                sw2.Close();
            }
            catch (CryptographicException ex)
            {
                throw new CryptographicException(ex.Message);
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
            finally
            {
                if (sr != null)
                {
                    sr.Close();
                }
            }
        }
Пример #20
0
    // Sign an XML file and save the signature in a new file.
    public static void SignXmlFile(string FileName, string SignedFileName, RSA Key)
    {
        // Create a new XML document.
        XmlDocument doc = new XmlDocument();

        // Format the document to ignore white spaces.
        doc.PreserveWhitespace = false;

        // Load the passed XML file using it's name.
        doc.Load(new XmlTextReader(FileName));

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

        // Add the key to the SignedXml document.
        signedXml.SigningKey = Key;

        // Specify a canonicalization method.
        signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NWithCommentsTransformUrl;

        // Set the InclusiveNamespacesPrefixList property.
        XmlDsigExcC14NWithCommentsTransform canMethod = (XmlDsigExcC14NWithCommentsTransform)signedXml.SignedInfo.CanonicalizationMethodObject;

        canMethod.InclusiveNamespacesPrefixList = "Sign";

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


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


        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();
    }
Пример #21
0
        /// <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="xml">
        /// 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>
        /// <param name="signatureMethod">Identifier of the signature method.</param>
        /// <param name="digestMethod">Identifier of the digest method.</param>
        public void SignXml(string certFriendlyName, XmlDocument xml, string targetReferenceId,
                            bool includePublicKey, string signatureMethod, string digestMethod)
        {
            if (string.IsNullOrEmpty(certFriendlyName))
            {
                throw new Saml2Exception(Resources.SignedXmlInvalidCertFriendlyName);
            }

            if (xml == null)
            {
                throw new Saml2Exception(Resources.SignedXmlInvalidXml);
            }

            if (string.IsNullOrEmpty(targetReferenceId))
            {
                throw new Saml2Exception(Resources.SignedXmlInvalidTargetRefId);
            }

            var cert = m_certificateFactory.GetCertificateByFriendlyName(certFriendlyName, m_logger);

            if (cert == null)
            {
                throw new Saml2Exception(Resources.SignedXmlCertNotFound);
            }

            using (var signingKey = cert.GetRSAPrivateKey())
            {
                var signedXml = new SignedXml(xml)
                {
                    SigningKey = signingKey
                };

                signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl;
                if (signatureMethod != null)
                {
                    signedXml.SignedInfo.SignatureMethod = signatureMethod;
                }

                if (includePublicKey)
                {
                    var keyInfo = new KeyInfo();
                    keyInfo.AddClause(new KeyInfoX509Data(cert));
                    signedXml.KeyInfo = keyInfo;
                }

                var reference = new Reference {
                    Uri = "#" + targetReferenceId
                };

                reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
                reference.AddTransform(new XmlDsigExcC14NTransform());
                if (digestMethod != null)
                {
                    reference.DigestMethod = digestMethod;
                }

                signedXml.AddReference(reference);
                signedXml.ComputeSignature();

                var xmlSignature = signedXml.GetXml();

                var nsMgr = new XmlNamespaceManager(xml.NameTable);
                nsMgr.AddNamespace("ds", SignedXml.XmlDsigNamespaceUrl);
                nsMgr.AddNamespace("saml", Saml2Constants.NamespaceSamlAssertion);
                nsMgr.AddNamespace("samlp", Saml2Constants.NamespaceSamlProtocol);

                var issuerNode = TryGetNode(xml, nsMgr, "saml:Issuer");
                if (issuerNode != null)
                {
                    RequireRootElement(xml).InsertAfter(xmlSignature, issuerNode);
                }
                else
                {
                    // Insert as a child to the target reference id
                    var targetNode = RequireNode(xml, nsMgr, "//*[@ID='" + targetReferenceId + "']");
                    targetNode.PrependChild(xmlSignature);
                }
            }
        }
Пример #22
0
        public XmlDocument Assinar(string lsConteudoXML, string pUri, X509Certificate2 pCertificado, TipoAssinatura tipoassinatura, string idUri)
        {
            pUri = "Reinf";

            //Abrir o arquivo XML a ser assinado e ler o seu conteúdo
            string vXMLString = lsConteudoXML;

            //if (!string.IsNullOrEmpty(pArqXMLAssinar))
            //{
            //    using (StreamReader SR = File.OpenText(pArqXMLAssinar))
            //    {
            //        vXMLString = SR.ReadToEnd();
            //        SR.Close();
            //    }
            //}

            //Atualizar atributos de retorno com conteúdo padrão
            this.vResultado       = 0;
            this.vResultadoString = "Assinatura realizada com sucesso";

            try
            {
                // Verifica o certificado a ser utilizado na assinatura
                string _xnome = "";
                if (pCertificado != null)
                {
                    _xnome = pCertificado.Subject.ToString();
                }

                X509Certificate2 _X509Cert = new X509Certificate2();
                X509Store        store     = new X509Store("MY", StoreLocation.CurrentUser);
                store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
                X509Certificate2Collection collection  = (X509Certificate2Collection)store.Certificates;
                X509Certificate2Collection collection1 = (X509Certificate2Collection)collection.Find(X509FindType.FindBySubjectDistinguishedName, _xnome, false);

                if (collection1.Count == 0)
                {
                    this.vResultado       = 2;
                    this.vResultadoString = "Problemas no certificado digital";
                }
                else
                {
                    // 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 = false;

                    // Load the passed XML file using it’s name.
                    try
                    {
                        doc.LoadXml(vXMLString);

                        // Verifica se a tag a ser assinada existe é única
                        int qtdeRefUri = doc.GetElementsByTagName(pUri).Count;

                        if (qtdeRefUri == 0)
                        {
                            // a URI indicada não existe
                            this.vResultado       = 4;
                            this.vResultadoString = "A tag de assinatura " + pUri.Trim() + " não existe";
                        }
                        // Exsiste mais de uma tag a ser assinada
                        else
                        {
                            if (qtdeRefUri > 1)
                            {
                                // existe mais de uma URI indicada
                                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);

                                    #region Alteracao01
                                    //                                if (!COM_Pin) &&
                                    //clsX509Certificate2Extension.IsA3(x509Cert) &&
                                    //!Empresas.Configuracoes[empresa].CertificadoPINCarregado)
                                    //                                {
                                    //                                    x509Cert.SetPinPrivateKey(Empresas.Configuracoes[empresa].CertificadoPIN);
                                    //                                    Empresas.Configuracoes[empresa].CertificadoPINCarregado = true;
                                    //                                }

                                    if (tipoassinatura == TipoAssinatura.Sha256)
                                    {
                                        signedXml.SignedInfo.SignatureMethod = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";
                                        signedXml.SigningKey = _X509Cert.GetRSAPrivateKey();
                                    }
                                    else
                                    {
                                        signedXml.SigningKey = _X509Cert.PrivateKey;
                                    }
                                    #endregion Alteracao01

                                    // Add the key to the SignedXml document
                                    //signedXml.SigningKey = _X509Cert.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;
                                    reference.Uri = "#" + idUri;

                                    //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);
                                    #region Alteracao2
                                    if (tipoassinatura == TipoAssinatura.Sha256)
                                    {
                                        reference.DigestMethod = "http://www.w3.org/2001/04/xmlenc#sha256";
                                    }
                                    #endregion Alteracao2

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

                                    // Gravar o elemento no documento XML
                                    doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, true));
                                    XMLDoc = new XmlDocument();
                                    XMLDoc.PreserveWhitespace = false;
                                    XMLDoc = doc;

                                    // Atualizar a string do XML já assinada
                                    this.vXMLStringAssinado = XMLDoc.OuterXml;

                                    // Gravar o XML no HD
                                    //wob alterei
                                    //StreamWriter SW_2 = File.CreateText(pArqXMLAssinar);
                                    //SW_2.Write(this.vXMLStringAssinado);
                                    //SW_2.Close();
                                }
                                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(XMLDoc);
        }
Пример #23
0
        public XmlDocument AssinaXML(string xml, string strUri, X509Certificate2 _X509Cert)
        {
            try
            {
                string x = _X509Cert.GetKeyAlgorithm().ToString();

                XmlDocument doc = new XmlDocument();
                doc.PreserveWhitespace = false;
                doc.LoadXml(xml);


                //Verifica se a tag a ser assinada existe e é única
                int qtdeRefUri = doc.GetElementsByTagName(strUri).Count;

                if (qtdeRefUri == 0)
                {
                    //' a URI indicada não existe
                    //Console.WriteLine("A tag de assinatura " + strUri + " não existe no XML. (Código do Erro: 4)");
                    //Throw New Exception("A tag de assinatura " & strUri.Trim() & " não existe no XML. (Código do Erro: 4)")
                    //intResultado = 4;
                }
                else
                {
                    if (doc.GetElementsByTagName("Signature").Count == 0)
                    {
                        SignedXml signedXml = new SignedXml(doc);
                        signedXml.SigningKey = _X509Cert.PrivateKey;


                        Reference reference = new Reference();


                        //pega o uri que deve ser assinada
                        XmlAttributeCollection _Uri = doc.GetElementsByTagName(strUri).Item(0).Attributes;
                        foreach (XmlAttribute _atributo in _Uri)
                        {
                            if (_atributo.Name == "Id")
                            {
                                reference.Uri = "#" + _atributo.InnerText;
                            }
                        }



                        XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();
                        reference.AddTransform(env);

                        XmlDsigC14NTransform c14 = new XmlDsigC14NTransform();
                        reference.AddTransform(c14);


                        signedXml.AddReference(reference);


                        KeyInfo keyInfo = new KeyInfo();
                        keyInfo.AddClause(new KeyInfoX509Data(_X509Cert));


                        signedXml.KeyInfo = keyInfo;
                        signedXml.ComputeSignature();

                        XmlElement xmlDigitalSignature = signedXml.GetXml();


                        if (strUri == "infNFe" || strUri == "infInut")
                        {
                            doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, true));
                        }
                        else if (strUri == "infEvento")
                        {
                            doc.GetElementsByTagName("evento").Item(0).AppendChild(doc.ImportNode(xmlDigitalSignature, true));
                        }


                        /*
                         * string caminho = strUri != "infEvento" ? @"C:\Documents and Settings\Renan\Desktop\gerarxmlASSINADO.xml" : @"C:\Documents and Settings\Renan\Desktop\new20Assinada - CCe.xml";
                         * using (XmlTextWriter xmlWriter = new XmlTextWriter(caminho, null))
                         * {
                         *  xmlWriter.Formatting = Formatting.None;
                         *  doc.Save(xmlWriter);
                         * }
                         */
                    }
                }

                return(doc);
            }
            catch (Exception)
            {
                throw;
            }
        }
Пример #24
0
        // 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();
        }
Пример #25
0
        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");

                    signedXml.SigningKey = ReadCard(Key, certificatePassword);
                    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");

                    var id = node.Attributes.GetNamedItem("Id").InnerText;

                    _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";
                    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 eSocialNode = node.ParentNode;
                    if (eSocialNode == null)
                    {
                        throw new Exception("Não foi possível encontrar o Nó do eSocial");
                    }

                    eSocialNode.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;
            }
        }
Пример #26
0
        // Sign an XML file and save the signature in a new file.
        public static void SignXmlFile(string FileName, string SignedFileName, RSA Key)
        {
            // Check the arguments.
            if (FileName == null)
            {
                throw new ArgumentNullException("FileName");
            }
            if (SignedFileName == null)
            {
                throw new ArgumentNullException("SignedFileName");
            }
            if (Key == null)
            {
                throw new ArgumentNullException("Key");
            }


            // Create a new XML document.
            XmlDocument doc = new XmlDocument();

            // Format the document to ignore white spaces.
            doc.PreserveWhitespace = false;

            // Load the passed XML file using it's name.
            doc.Load(new XmlTextReader(FileName));

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

            // Add the key to the SignedXml document.
            signedXml.SigningKey = Key;

            // Get the signature object from the SignedXml object.
            Signature XMLSignature = signedXml.Signature;

            // Create a reference to be signed.  Pass ""
            // to specify that all of the current XML
            // document should be signed.
            Reference reference = new Reference("");

            // Add an enveloped transformation to the reference.
            XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();

            reference.AddTransform(env);

            // Add the Reference object to the Signature object.
            XMLSignature.SignedInfo.AddReference(reference);

            // Add an RSAKeyValue KeyInfo (optional; helps recipient find key to validate).
            KeyInfo keyInfo = new KeyInfo();

            keyInfo.AddClause(new RSAKeyValue((RSA)Key));

            // Add the KeyInfo object to the Reference object.
            XMLSignature.KeyInfo = keyInfo;

            // Compute the signature.
            signedXml.ComputeSignature();

            // Get the XML representation of the signature and save
            // it to an XmlElement object.
            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();
        }
        private static bool hashsignfile(string file)
        {
            try
            {
                if (selectedcert == null)
                {
                    selectedcert = selectcert();
                }

                string hash = hashfile(file);

                FileInfo info = new FileInfo(file);
                Directory.SetCurrentDirectory(info.Directory.FullName);

                System.IO.MemoryStream mxml = new System.IO.MemoryStream();

                XmlWriter xwriter = XmlWriter.Create(mxml);
                xwriter.WriteStartDocument();
                xwriter.WriteStartElement("DigiSig");
                xwriter.WriteElementString("hash", hash);
                xwriter.WriteElementString("size", info.Length.ToString());
                xwriter.WriteElementString("signtime", DateTime.Now.ToString());
                xwriter.WriteElementString("creator", System.Security.Principal.WindowsIdentity.GetCurrent().Name);

                xwriter.WriteEndElement();
                xwriter.WriteEndDocument();
                xwriter.Flush();

                mxml.Position = 0;
                XmlDocument xmldoc = new XmlDocument();
                xmldoc.Load(mxml);

                /*CspParameters parms = new CspParameters(1);
                 * parms.KeyContainerName = selectedcert;
                 * RSACryptoServiceProvider csp = new RSACryptoServiceProvider(parms);*/

                RSACryptoServiceProvider csp = (RSACryptoServiceProvider)selectedcert.PrivateKey;

                Reference r = new Reference("");
                r.AddTransform(new XmlDsigEnvelopedSignatureTransform(false));

                SignedXml sxml = new SignedXml(xmldoc);
                sxml.SigningKey = csp;
                sxml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigCanonicalizationUrl;
                sxml.AddReference(r);
                sxml.ComputeSignature();

                XmlElement sig = sxml.GetXml();
                xmldoc.DocumentElement.AppendChild(sig);

                XmlTextWriter writer = new XmlTextWriter(file + ".sha", UTF8Encoding.UTF8);
                writer.Formatting = Formatting.Indented;
                xmldoc.WriteTo(writer);
                writer.Flush();
                writer.Close();
                //appLog.WriteEntry("Hashed File: "+file, System.Diagnostics.EventLogEntryType.Information);
                return(true);
            }
            catch (Exception e)
            {
                //appLog.WriteEntry(e.Message + e.StackTrace, System.Diagnostics.EventLogEntryType.Warning);
                //Console.WriteLine(e.Message + e.TargetSite);
                return(false);
            }
        }
Пример #28
0
    // <Snippet2>
    // Sign an XML file and save the signature in a new file.
    public static void SignXmlFile(string FileName, string SignedFileName, DSA DSAKey)
    {
        // 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 DSA key to the SignedXml document.
        signedXml.SigningKey = DSAKey;

        // Create a reference to be signed.
        Reference reference = new Reference();

        reference.Uri = "";

        // Add a transformation to the reference.
        Transform trns = new XmlDsigC14NTransform();

        reference.AddTransform(trns);

        // 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 a DSAKeyValue to the KeyInfo (optional; helps recipient find key to validate).
        KeyInfo keyInfo = new KeyInfo();

        keyInfo.AddClause(new DSAKeyValue((DSA)DSAKey));
        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();
    }
Пример #29
0
	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 Assinar(Nota nota, X509Certificate2 x509Cert, String TagAssinatura, String URI = "")
        {
            string xmlString;

            using (var srReader = File.OpenText(nota.CaminhoFisico))
            {
                xmlString = srReader.ReadToEnd();
            }

            // Create a new XML document.
            var doc = new XmlDocument();

            // Format the document to ignore white spaces.
            doc.PreserveWhitespace = false;
            doc.LoadXml(xmlString);

            XmlDocument xMLDoc;

            var reference = new Reference();

            if (!String.IsNullOrEmpty(nota.NotaId))
            {
                reference.Uri = "#" + TagAssinatura + nota.NotaId;
            }
            else if (!String.IsNullOrEmpty(URI))
            {
                reference.Uri = URI;
            }

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

            // Add the key to the SignedXml document
            signedXml.SigningKey = x509Cert.PrivateKey;

            // 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(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.
            var xmlDigitalSignature = signedXml.GetXml();

            // Gravar o elemento no documento XML
            var assinaturaNodes = doc.GetElementsByTagName(TagAssinatura);

            foreach (XmlNode nodes in assinaturaNodes)
            {
                nodes.AppendChild(doc.ImportNode(xmlDigitalSignature, true));
                break;
            }

            xMLDoc = new XmlDocument();
            xMLDoc.PreserveWhitespace = false;
            xMLDoc = doc;

            // Atualizar a string do XML já assinada
            var StringXMLAssinado = xMLDoc.OuterXml;

            //Atualiza a nota assinada
            nota.ConteudoXml = StringXMLAssinado;

            // Gravar o XML Assinado no HD
            var SignedFile = nota.CaminhoFisico;
            var SW_2       = File.CreateText(SignedFile);

            SW_2.Write(StringXMLAssinado);
            SW_2.Close();

            return(SignedFile);
        }
            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;
            }
Пример #32
0
        /// <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;
            signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl;

            if (includePublicKey)
            {
                var keyInfo = new KeyInfo();
                keyInfo.AddClause(new KeyInfoX509Data(cert));
                signedXml.KeyInfo = keyInfo;
            }

            var reference = new Reference();

            reference.Uri = "#" + targetReferenceId;

            reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
            reference.AddTransform(new XmlDsigExcC14NTransform());

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

            var     root       = RequireRootElement(xml);
            XmlNode issuerNode = root.SelectSingleNode("saml:Issuer", nsMgr);

            if (issuerNode != null)
            {
                root.InsertAfter(xmlSignature, issuerNode);
            }
            else
            {
                // Insert as a child to the target reference id
                XmlNode targetNode = root.SelectSingleNode("//*[@ID='" + targetReferenceId + "']", nsMgr);
                targetNode.PrependChild(xmlSignature);
            }
        }
Пример #33
0
        public static XmlDocument SignXml(string XMLtext, string SubjectName, string privateKey)
        {
            if (null == XMLtext)
            {
                throw new ArgumentNullException("XMLtext");
            }
            if (null == SubjectName)
            {
                throw new ArgumentNullException("SubjectName");
            }

            // Load the certificate from the certificate store.
            X509Certificate2 cert = new X509Certificate2(StringToByteArray(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.LoadXml(XMLtext);

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

            RSA rsa = new RSACng();

            rsa.ImportRSAPrivateKey(Convert.FromBase64String(privateKey), out _);
            // Add the key to the SignedXml document.
            signedXml.SigningKey = rsa;

            // 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.
            return(doc);
        }
Пример #34
0
    // 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());
    }
Пример #35
0
    // <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.
        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();
        }
    }
Пример #36
0
    // 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();
    }
Пример #37
0
        /// <summary>
        /// Message signing
        /// </summary>
        public virtual byte[] Sign(
            ISignableMessage message,
            X509Configuration x509Configuration)
        {
            if (message == null)
            {
                throw new ArgumentNullException("message");
            }
            if (x509Configuration == null ||
                x509Configuration.SignatureCertificate == null
                )
            {
                throw new ArgumentNullException("certificate");
            }

            // first, serialize to XML
            var messageBody = this.messageSerializer.Serialize(message, new MessageSerializationParameters()
            {
                ShouldBase64Encode = false,
                ShouldDeflate      = false
            });

            var xml = new XmlDocument();

            xml.LoadXml(messageBody);

            // sign the node with the id
            var reference = new Reference("#" + message.ID);
            var envelope  = new XmlDsigEnvelopedSignatureTransform(true);

            reference.AddTransform(envelope);

            // canonicalization
            var c14 = new XmlDsigExcC14NTransform();

            c14.Algorithm = SignedXml.XmlDsigExcC14NTransformUrl;
            reference.AddTransform(c14);

            // some more spells depending on SHA1 vs SHA256
            var signed = new SignedXml(xml);

            signed.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl;
            switch (x509Configuration.SignatureAlgorithm)
            {
            case SignatureAlgorithm.SHA1:
                signed.SigningKey = x509Configuration.SignatureCertificate.PrivateKey;
                signed.SignedInfo.SignatureMethod = SignedXml.XmlDsigRSASHA1Url;
                reference.DigestMethod            = SignedXml.XmlDsigSHA1Url;
                break;

            case SignatureAlgorithm.SHA256:
                signed.SigningKey = x509Configuration.SignatureCertificate.ToSha256PrivateKey();
                signed.SignedInfo.SignatureMethod = SignedXml.XmlDsigRSASHA256Url;
                reference.DigestMethod            = SignedXml.XmlDsigSHA256Url;
                break;
            }

            if (x509Configuration.IncludeKeyInfo)
            {
                var key     = new System.Security.Cryptography.Xml.KeyInfo();
                var keyData = new KeyInfoX509Data(x509Configuration.SignatureCertificate);
                key.AddClause(keyData);
                signed.KeyInfo = key;
            }

            // show the reference
            signed.AddReference(reference);
            // create the signature
            signed.ComputeSignature();
            var signature = signed.GetXml();

            // insert the signature into the document
            var element = xml.DocumentElement.ChildNodes[0];

            xml.DocumentElement.InsertAfter(xml.ImportNode(signature, true), element);

            // log
            new LoggerFactory().For(this).Debug(Event.SignedMessage, xml.OuterXml);

            // convert
            return(this.encoding.GetBytes(xml.OuterXml));
        }