Esempio n. 1
0
        private SignedXml GetXmlSignature(XmlDocument document, X509Certificate2 certificate, Guid requestId)
        {
            LogManager.LogTrace(string.Format("SE.GOV.MM.Integration.DeliveryMailbox.Signing.Handler.SignXmlDocumentHandler: incoming GetXmlSignature with RequestId: {0}", requestId));

            SignedXml signedXml = new SignedXml(document);

            signedXml.SigningKey = certificate.PrivateKey;

            // Retrieve the value of the "ID" attribute on the root assertion element.
            Reference reference = new Reference("");

            reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());

            signedXml.AddReference(reference);

            signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl;

            // Include the public key of the certificate in the assertion.
            signedXml.KeyInfo = new KeyInfo();

            var keyInfoData = new KeyInfoX509Data();

            keyInfoData.AddSubjectName(certificate.SubjectName.Name);
            keyInfoData.AddCertificate(certificate);
            signedXml.KeyInfo.AddClause(keyInfoData);

            signedXml.ComputeSignature();

            LogManager.LogTrace(string.Format("SE.GOV.MM.Integration.DeliveryMailbox.Signing.Handler.SignXmlDocumentHandler: leaving GetXmlSignature with RequestId: {0}", requestId));
            return(signedXml);
        }
Esempio n. 2
0
        private KeyInfo GetKeyInfo()
        {
            KeyInfo info = null;

            if (_keyInfoClauses.Count > 0)
            {
                info = new KeyInfo();
                KeyInfoX509Data clause = new KeyInfoX509Data();
                foreach (var item in _keyInfoClauses)
                {
                    switch (item)
                    {
                    case "RSAKeyValue":
                        RSACryptoServiceProvider pKey = (RSACryptoServiceProvider)_cert.PublicKey.Key;
                        info.AddClause(new RSAKeyValue((RSA)pKey));
                        break;

                    case "X509IssuerSerial":
                        clause.AddIssuerSerial(_cert.IssuerName.Name, _cert.SerialNumber);
                        break;

                    case "X509SubjectName":
                        clause.AddSubjectName(_cert.SubjectName.Name);
                        break;

                    case "X509Certificate":
                        clause.AddCertificate(_cert);
                        break;
                    }
                }
                info.AddClause(clause);
            }
            return(info);
        }
Esempio n. 3
0
        public XmlDocument FirmarDocumentXML(XmlDocument xmlDocument, string rutaArchivoCertificado, string passwordCertificado)
        {
            xmlDocument.PreserveWhitespace = true;
            XmlNode ExtensionContent = xmlDocument.GetElementsByTagName("ExtensionContent", "urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2").Item(0);

            ExtensionContent.RemoveAll();

            X509Certificate2         x509Certificate2 = new X509Certificate2(File.ReadAllBytes(rutaArchivoCertificado), passwordCertificado, X509KeyStorageFlags.Exportable);
            RSACryptoServiceProvider key = new RSACryptoServiceProvider(new CspParameters(24));

            SignedXml signedXml = new SignedXml(xmlDocument);
            XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();
            KeyInfo         keyInfo         = new KeyInfo();
            KeyInfoX509Data keyInfoX509Data = new KeyInfoX509Data(x509Certificate2);
            Reference       reference       = new Reference("");

            string exportarLlave = x509Certificate2.PrivateKey.ToXmlString(true);

            key.PersistKeyInCsp = false;
            key.FromXmlString(exportarLlave);
            reference.AddTransform(env);
            signedXml.SigningKey = key;
            Signature XMLSignature = signedXml.Signature;

            XMLSignature.SignedInfo.AddReference(reference);
            keyInfoX509Data.AddSubjectName(x509Certificate2.Subject);
            keyInfo.AddClause(keyInfoX509Data);
            XMLSignature.KeyInfo = keyInfo;
            XMLSignature.Id      = "SignatureKG";
            signedXml.ComputeSignature(); ExtensionContent.AppendChild(signedXml.GetXml());
            return(xmlDocument);
        }
Esempio n. 4
0
        private KeyInfo createKeyInfo(CertificateX509 certificate, string keyInfoType)
        {
            KeyInfo     keyInfo = new KeyInfo();
            KeyInfoType kinfo   = KeyInfoTypeUtils.getKeyInfoType(keyInfoType, this.error);

            switch (kinfo)
            {
            case KeyInfoType.KeyValue:

                if (SecurityUtils.compareStrings(certificate.getPublicKeyAlgorithm(), "RSA"))
                {
                    keyInfo.AddClause(new RSAKeyValue((RSA)certificate.getPublicKeyXML()));
                }
                else
                {
                    keyInfo.AddClause(new DSAKeyValue((DSA)certificate.getPublicKeyXML()));
                }
                break;

            case KeyInfoType.X509Certificate:

                KeyInfoX509Data keyInfoX509Data = new KeyInfoX509Data();
                keyInfoX509Data.AddCertificate((X509Certificate)certificate.Cert);
                keyInfoX509Data.AddSubjectName(certificate.Cert.SubjectName.Name);
                keyInfoX509Data.AddIssuerSerial(certificate.Cert.IssuerName.Name, certificate.Cert.SerialNumber);
                keyInfo.AddClause((KeyInfoClause)keyInfoX509Data);

                break;

            case KeyInfoType.NONE:
                keyInfo = null;
                break;
            }
            return(keyInfo);
        }
Esempio n. 5
0
        /// <summary>
        /// Firma un documento XML.
        /// </summary>
        /// <param name="documentoXML">Documento XML</param>
        /// <param name="certificado">Certificado</param>
        /// <returns>Documento Firmado</returns>
        protected string FirmarXml(XmlDocument documentoXML, X509Certificate2 certificado)
        {
            try
            {
                documentoXML.PreserveWhitespace = false;
                SignedXml signedXml = new SignedXml(documentoXML);
                signedXml.SigningKey = certificado.PrivateKey;

                KeyInfo         keyInfo = new KeyInfo();
                KeyInfoX509Data keyData = new KeyInfoX509Data(certificado);
                keyData.AddSubjectName(certificado.SubjectName.Name);
                keyInfo.AddClause(keyData);

                signedXml.KeyInfo      = keyInfo;
                signedXml.Signature.Id = "SignatureSP";
                Reference reference = new Reference("#SignatureSP");
                reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
                reference.Uri = "";

                signedXml.AddReference(reference);
                signedXml.ComputeSignature();
                signedXml.CheckSignature(certificado, true);

                string xml_string = documentoXML.InnerXml.ToString();
                xml_string = xml_string.Replace("<ext:UBLExtension><ext:ExtensionContent></ext:ExtensionContent></ext:UBLExtension>", "<ext:UBLExtension><ext:ExtensionContent>" + signedXml.GetXml().OuterXml + "</ext:ExtensionContent></ext:UBLExtension>");
                return(xml_string);
            }
            catch (Exception ex)
            {
                //System.Windows.Forms.MessageBox.Show(ex.ToString());
                clsBaseLog.cs_pxRegistarAdd("clsNegocioCE FirmarXml " + ex.ToString());
                return(null);
            }
        }
        /// <summary>
        /// Signs xmldocument
        /// </summary>
        /// <param name="xmlDoc">Document to sign</param>
        /// <param name="tagName">Element to insert signature after</param>
        public void SignXmlDocument(XmlDocument xmlDoc, string tagName, X509Certificate2 x509Certificate2 = null)
        {
            if (x509Certificate2 != null)
            {
                this.x509Certificate2 = x509Certificate2;
            }
            xmlDoc.Normalize();

            SignedXml signedXml = new SignedXml(xmlDoc);

            signedXml.SigningKey = this.x509Certificate2.PrivateKey;

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

            reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
            signedXml.AddReference(reference);

            // Specify a canonicalization method.
            signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl;
            signedXml.KeyInfo = new KeyInfo();

            var keyInfoData = new KeyInfoX509Data();

            keyInfoData.AddSubjectName(this.x509Certificate2.SubjectName.Name);
            keyInfoData.AddCertificate(this.x509Certificate2);
            signedXml.KeyInfo.AddClause(keyInfoData);

            signedXml.ComputeSignature();

            XmlNodeList nodes = xmlDoc.DocumentElement.GetElementsByTagName(tagName);

            nodes[0].ParentNode.InsertAfter(xmlDoc.ImportNode(signedXml.GetXml(), true), nodes[0]);
        }
Esempio n. 7
0
    static void Test6()     //Xml roundtrip
    {
        int i = 0;

        data = new KeyInfoX509Data();

        //add certs
        data.AddCertificate(TestCert);
        data.AddCertificate(EndCert);

        //add subject name
        data.AddSubjectName(TestCert.SubjectName.Name);
        data.AddSubjectName(EndCert.SubjectName.Name);

        //add subject keys
        data.AddSubjectKeyId(new byte[] { 1, 2, 3, 4, 5, 6 });
        data.AddSubjectKeyId(new byte[] { 7, 8, 9, 10, 11, 12 });

        //add issuer serials
        data.AddIssuerSerial(TestCert.IssuerName.Name, TestCert.SerialNumber);
        data.AddIssuerSerial(EndCert.IssuerName.Name, EndCert.SerialNumber);

        //add the crl
        byte[] b = { 100, 101, 102, 104 };
        data.CRL = b;

        KeyInfoX509Data rt = new KeyInfoX509Data();

        rt.LoadXml(data.GetXml());
        for (i = 0; i < rt.CRL.Length; i++)
        {
            rv = rt.CRL[i] == data.CRL[i];
        }

        for (i = 0; i < rt.Certificates.Count; i++)
        {
            rv = rt.Certificates[i].ToString() == data.Certificates[i].ToString();
        }
        for (i = 0; i < rt.SubjectKeyIds.Count; i++)
        {
            rv = rt.SubjectKeyIds[i].ToString() == data.SubjectKeyIds[i].ToString();
        }
        for (i = 0; i < rt.SubjectNames.Count; i++)
        {
            rv = rt.SubjectNames[i].ToString() == data.SubjectNames[i].ToString();
        }
    }
Esempio n. 8
0
        public static void SignXml(XmlDocument xmlDoc, X509Certificate2 uidCert)
        {
            RSACryptoServiceProvider rsaKey = (RSACryptoServiceProvider)uidCert.PrivateKey;


            // Check arguments.
            if (xmlDoc == null)
            {
                throw new ArgumentException("xmlDoc");
            }
            if (rsaKey == null)
            {
                throw new ArgumentException("Key");
            }

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

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


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

            KeyInfoX509Data clause = new KeyInfoX509Data();

            clause.AddSubjectName(uidCert.Subject);
            clause.AddCertificate(uidCert);
            keyInfo.AddClause(clause);
            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();

            System.Console.WriteLine(signedXml.GetXml().InnerXml);

            // Append the element to the XML document.
            xmlDoc.DocumentElement.AppendChild(xmlDoc.ImportNode(xmlDigitalSignature, true));
        }
Esempio n. 9
0
        private KeyInfo GetCertInfo(X509Certificate cert)
        {
            KeyInfo keyInfo = new KeyInfo();

            KeyInfoX509Data keyInfoData = new KeyInfoX509Data(cert.GetEncoded());

            keyInfoData.AddIssuerSerial(cert.IssuerDN.ToString(), cert.SerialNumber.ToString());
            keyInfoData.AddSubjectName(cert.SubjectDN.ToString());
            keyInfo.AddClause(keyInfoData);
            return(keyInfo);
        }
Esempio n. 10
0
        public void AddSubjectName_Null()
        {
            KeyInfoX509Data data = new KeyInfoX509Data();

            data.AddSubjectName(null);
            Assert.Null(data.Certificates);
            Assert.Null(data.CRL);
            Assert.Null(data.IssuerSerials);
            Assert.Null(data.SubjectKeyIds);
            Assert.Equal(1, data.SubjectNames.Count);
            Assert.Null(data.SubjectNames[0]);
            Assert.Equal("<X509Data xmlns=\"http://www.w3.org/2000/09/xmldsig#\"><X509SubjectName></X509SubjectName></X509Data>", data.GetXml().OuterXml);
        }
Esempio n. 11
0
        public void AddSubjectName_Null()
        {
            KeyInfoX509Data data = new KeyInfoX509Data();

            data.AddSubjectName(null);
            Assert.IsNull(data.Certificates, "Certificates");
            Assert.IsNull(data.CRL, "Certificates");
            Assert.IsNull(data.IssuerSerials, "IssuerSerials");
            Assert.IsNull(data.SubjectKeyIds, "SubjectKeyIds");
            Assert.AreEqual(1, data.SubjectNames.Count, "SubjectNames");
            Assert.IsNull(data.SubjectNames[0], "SubjectNames[0]");
            Assert.AreEqual("<X509Data xmlns=\"http://www.w3.org/2000/09/xmldsig#\"><X509SubjectName></X509SubjectName></X509Data>", data.GetXml().OuterXml, "XML");
        }
Esempio n. 12
0
        /// <summary>
        /// Creates a KeyInfo object based on information from specified certificate
        /// </summary>
        /// <param name="certificate">The certificate used to create the KeyInfo from</param>
        /// <returns>KeyInfo object</returns>
        private static KeyInfo CreateKeyInfoFromCertificate(X509Certificate2 certificate)
        {
            // create KeyInfoX509Data object & include certificate subject
            KeyInfoX509Data kiData = new KeyInfoX509Data(certificate);

            kiData.AddSubjectName(certificate.Subject);

            // create KeyInfo object with specified KeyInfoX509Data
            KeyInfo keyInfo = new KeyInfo();

            keyInfo.AddClause(kiData);

            return(keyInfo);
        }
Esempio n. 13
0
        private KeyInfo getKeyInfo()
        {
            X509Extension  extension = this.settings.Certificate.Extensions[1];
            AsnEncodedData asndata   = new AsnEncodedData(extension.Oid, extension.RawData);

            KeyInfoX509Data keyInfoData = new KeyInfoX509Data();

            keyInfoData.AddIssuerSerial(this.settings.Certificate.Issuer, this.settings.Certificate.SerialNumber);
            keyInfoData.AddSubjectName(this.settings.Certificate.SubjectName.Name);

            KeyInfo keyInfo = new KeyInfo();

            keyInfo.AddClause(keyInfoData);
            return(keyInfo);
        }
Esempio n. 14
0
        public void Complex()
        {
            KeyInfoX509Data data1 = new KeyInfoX509Data(cert);
            KeyInfoX509Data data2 = new KeyInfoX509Data();

            XmlElement xel = data1.GetXml();

            data2.LoadXml(xel);

            Assert.Equal((data1.GetXml().OuterXml), (data2.GetXml().OuterXml));
            byte[] c = (data1.Certificates[0] as X509Certificate).GetRawCertData();
            AssertCrypto.AssertEquals("Certificate[0]", cert, c);

            // add a second X.509 certificate
            X509Certificate x509 = new X509Certificate(cert2);

            data1.AddCertificate(x509);
            xel = data1.GetXml();
            data2.LoadXml(xel);
            Assert.Equal((data1.GetXml().OuterXml), (data2.GetXml().OuterXml));
            c = (data1.Certificates[1] as X509Certificate).GetRawCertData();
            Assert.Equal(cert2, c);

            // add properties from a third X.509 certificate
            x509 = new X509Certificate(cert3);
            data1.AddIssuerSerial(x509.Issuer, x509.GetSerialNumberString());
            xel = data1.GetXml();
            data2.LoadXml(xel);
            Assert.Equal((data1.GetXml().OuterXml), (data2.GetXml().OuterXml));
            // TODO: The type of IssuerSerial isn't documented

            // X509Certificate doesn't export SubjectKeyId so we must improvise
            byte[] skid = { 0xDE, 0xAD, 0xC0, 0xDE };
            data1.AddSubjectKeyId(skid);
            xel = data1.GetXml();
            data2.LoadXml(xel);
            Assert.Equal((data1.GetXml().OuterXml), (data2.GetXml().OuterXml));
            Assert.Equal(skid, (byte[])data1.SubjectKeyIds[0]);
            data1.AddSubjectName(x509.Subject);
            xel = data1.GetXml();
            data2.LoadXml(xel);
            Assert.Equal((data1.GetXml().OuterXml), (data2.GetXml().OuterXml));
            string s = (string)data1.SubjectNames[0];

            Assert.Equal(x509.Subject, s);
        }
        public void Complex()
        {
            KeyInfoX509Data data1 = new KeyInfoX509Data(cert);
            KeyInfoX509Data data2 = new KeyInfoX509Data();

            XmlElement xel = data1.GetXml();

            data2.LoadXml(xel);

            Assert.Equal((data1.GetXml().OuterXml), (data2.GetXml().OuterXml));
            byte[] c = (data1.Certificates[0] as X509Certificate).GetEncoded();
            AssertCrypto.AssertEquals("Certificate[0]", cert, c);


            X509Certificate x509 = new X509CertificateParser().ReadCertificate(cert2);

            data1.AddCertificate(x509);
            xel = data1.GetXml();
            data2.LoadXml(xel);
            Assert.Equal((data1.GetXml().OuterXml), (data2.GetXml().OuterXml));
            c = (data1.Certificates[1] as X509Certificate).GetEncoded();
            Assert.Equal(cert2, c);


            x509 = new X509CertificateParser().ReadCertificate(cert3);
            data1.AddIssuerSerial(x509.IssuerDN.ToString(), x509.SerialNumber.ToString());
            xel = data1.GetXml();
            data2.LoadXml(xel);
            Assert.Equal((data1.GetXml().OuterXml), (data2.GetXml().OuterXml));



            byte[] skid = { 0xDE, 0xAD, 0xC0, 0xDE };
            data1.AddSubjectKeyId(skid);
            xel = data1.GetXml();
            data2.LoadXml(xel);
            Assert.Equal((data1.GetXml().OuterXml), (data2.GetXml().OuterXml));
            Assert.Equal(skid, (byte[])data1.SubjectKeyIds[0]);
            data1.AddSubjectName(x509.SubjectDN.ToString());
            xel = data1.GetXml();
            data2.LoadXml(xel);
            Assert.Equal((data1.GetXml().OuterXml), (data2.GetXml().OuterXml));
            string s = (string)data1.SubjectNames[0];

            Assert.Equal(x509.SubjectDN.ToString(), s);
        }
Esempio n. 16
0
        private static XmlElement SignWithPrivateKey(XmlDocument doc, X509Certificate2 cert, AsymmetricAlgorithm privateKey, string signatureNsPrefix, bool includePublicKey)
        {
            SignedXmlWithPrefix signedXml = new SignedXmlWithPrefix(doc.DocumentElement)
            {
                SigningKey = privateKey
            };

            KeyInfo keyInfo = signedXml.KeyInfo;

            if (includePublicKey)
            {
                keyInfo.AddClause(new KeyInfoName("Public key of certificate"));
                keyInfo.AddClause(new RSAKeyValue((RSA)cert.PublicKey.Key));
            }
            KeyInfoX509Data x509data = new KeyInfoX509Data(cert);

            x509data.AddIssuerSerial(cert.Issuer, cert.SerialNumber);
            x509data.AddSubjectName(cert.Subject);
            keyInfo.AddClause(x509data);

            Reference reference = new Reference(string.Empty);

            reference.AddTransform(new XmlDsigEnvelopedSignatureTransform(true));
            reference.AddTransform(new XmlDsigC14NTransform());
            signedXml.AddReference(reference);

            // Връщат се старите алгоритми за подписване, използвани по подразбиране в .net framework
            // защото самият е-Автентикатор е стар и не разбира новите алгоритми, използвани по подразбиране в .net core.
            signedXml.SignedInfo.SignatureMethod = SignedXml.XmlDsigRSASHA1Url;
            reference.DigestMethod = SignedXml.XmlDsigSHA1Url;

            if (!string.IsNullOrEmpty(signatureNsPrefix))
            {
                signedXml.ComputeSignature(signatureNsPrefix);
                return(signedXml.GetXml(signatureNsPrefix));
            }
            signedXml.ComputeSignature();
            return(signedXml.GetXml());
        }
Esempio n. 17
0
        /// <summary>
        /// Signs an XmlDocument with an xml signature.
        /// </summary>
        public XmlDocument SignXmlDocument(XmlDocument document, X509Certificate2 certificate, Guid requestId)
        {
            LogManager.LogTrace(string.Format("SE.GOV.MM.Integration.Signing.Handler.SignXmlDocumentHandler: incoming SignXmlDocument with RequestId: {0}", requestId));

            document.Normalize();

            SignedXml signedXml = new SignedXml(document);

            signedXml.SigningKey = certificate.PrivateKey;

            // Retrieve the value of the "ID" attribute on the root assertion element.
            Reference reference = new Reference("");

            reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());

            signedXml.AddReference(reference);

            signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl;

            // Include the public key of the certificate in the assertion.
            signedXml.KeyInfo = new KeyInfo();

            var keyInfoData = new KeyInfoX509Data();

            keyInfoData.AddSubjectName(certificate.SubjectName.Name);
            keyInfoData.AddCertificate(certificate);
            signedXml.KeyInfo.AddClause(keyInfoData);

            signedXml.ComputeSignature();

            // Append the computed signature. The signature must be placed as the sibling of the Issuer element.
            XmlNodeList nodes = document.DocumentElement.GetElementsByTagName("Delivery");

            nodes[0].ParentNode.InsertAfter(document.ImportNode(signedXml.GetXml(), true), nodes[0]);

            LogManager.LogTrace(string.Format("SE.GOV.MM.Integration.Signing.Handler.SignXmlDocumentHandler: leaving SignXmlDocument with RequestId: {0}", requestId));
            return(document);
        }
Esempio n. 18
0
        /// <summary>
        /// Computes digital signature and adds it to an XML element.
        /// </summary>
        /// <param name="xml">The XML on which the signature is to be computed.</param>
        /// <returns>The Signature element of the XML.</returns>
        /// <exception cref="NotSupportedException"></exception>
        public XElement ComputeSignature(XElement xml)
        {
#if NET46
            ValidateNull(xml, nameof(xml));
            ValidateNull(Signer, nameof(Signer));
            if (!Signer.HasPrivateKey)
            {
                throw new CryptographicException(NoPrivateKey);
            }

            var signedXml = new SignedXml(GetXmlDocument(xml))
            {
                SigningKey = Signer.PrivateKey
            };

            // Add Reference.
            var reference = new Reference(string.Empty);
            reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
            signedXml.AddReference(reference);

            // Add Key Info.
            var keyInfo = new KeyInfo();
            var clause  = new KeyInfoX509Data(Signer);
            clause.AddSubjectName(Signer.Subject);
            keyInfo.AddClause(clause);
            signedXml.KeyInfo = keyInfo;

            // Compute Signature.
            signedXml.ComputeSignature();
            var signatureXml = GetXDocument(signedXml.GetXml()).Root;
            xml.Add(signatureXml);

            return(signatureXml);
#else
            throw new NotSupportedException(NotSupportedXmlSignature);
#endif
        }
Esempio n. 19
0
        public string FirmarXml(string tramaXml, Int32 TipoDocumento)
        {
            // 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 | X509KeyStorageFlags.UserKeySet);

            var xmlDoc = new XmlDocument();

            string resultado;

            var betterBytes = Encoding.Convert(Encoding.UTF8,
                                               Encoding.GetEncoding(_encodingIso),
                                               Convert.FromBase64String(tramaXml));

            using (var documento = new MemoryStream(betterBytes))
            {
                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      = "ERWIN";
                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());

                using (var memDoc = new MemoryStream())
                {
                    using (var writer = XmlWriter.Create(memDoc,
                                                         new XmlWriterSettings {
                        Encoding = Encoding.GetEncoding(_encodingIso)
                    }))
                    {
                        xmlDoc.WriteTo(writer);
                    }

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

            return(resultado);
        }
Esempio n. 20
0
        public void firmaDigital(string filexml)
        {
            try
            {
                String local_xmlArchivo = pathxml + filexml;
                //    String local_xmlArchivo = @"D:\sistema\20151228\xml\20427799973-03-BB11-00095393.xml";
                String local_typoDocumento = string.Empty;
                String local_nombreXML     = System.IO.Path.GetFileName(local_xmlArchivo);
                if (local_nombreXML.Substring(12, 2) != "RC")
                {
                    local_typoDocumento = local_nombreXML.Substring(12, 2);
                }
                else
                {
                    local_typoDocumento = "RC";
                }
                this.pathcert = pathcert + @"\Certificado\" + "XXXXXXXXXXXXXXXXXXXXXX==.p12";
                X509Certificate2 MiCertificado = new X509Certificate2(this.pathcert, "asdqwezcx");
                XmlDocument      xmlDoc        = new XmlDocument();
                xmlDoc.PreserveWhitespace = true;
                xmlDoc.Load(local_xmlArchivo);
                //RSACryptoServiceProvider y X509Certificate
                SignedXml signedXml = new SignedXml(xmlDoc);

                signedXml.SigningKey = MiCertificado.PrivateKey;

                KeyInfo KeyInfo = new KeyInfo();

                Reference Reference = new Reference();
                Reference.Uri = "";

                Reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());


                signedXml.AddReference(Reference);

                X509Chain X509Chain = new X509Chain();
                X509Chain.Build(MiCertificado);

                X509ChainElement local_element = X509Chain.ChainElements[0];
                KeyInfoX509Data  x509Data      = new KeyInfoX509Data(local_element.Certificate);
                String           subjectName   = local_element.Certificate.Subject;

                x509Data.AddSubjectName(subjectName);
                KeyInfo.AddClause(x509Data);

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

                XmlElement signature = signedXml.GetXml();
                signature.Prefix = "ds";
                signedXml.ComputeSignature();

                foreach (XmlNode node in signature.SelectNodes("descendant-or-self::*[namespace-uri()='http://www.w3.org/2000/09/xmldsig#']"))
                {
                    if (node.LocalName == "Signature")
                    {
                        XmlAttribute newAttribute = xmlDoc.CreateAttribute("Id");
                        newAttribute.Value = "SignatureSP";
                        node.Attributes.Append(newAttribute);
                        break;
                    }
                }
                String local_xpath = string.Empty;
                XmlNamespaceManager nsMgr;
                nsMgr = new XmlNamespaceManager(xmlDoc.NameTable);
                nsMgr.AddNamespace("sac", "urn:sunat:names:specification:ubl:peru:schema:xsd:SunatAggregateComponents-1");
                nsMgr.AddNamespace("ccts", "urn:un:unece:uncefact:documentation:2");
                nsMgr.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");


                switch (local_typoDocumento)
                {
                case "01":
                case "03":
                    //factura / boleta
                    nsMgr.AddNamespace("tns", "urn:oasis:names:specification:ubl:schema:xsd:Invoice-2");
                    local_xpath = "/tns:Invoice/ext:UBLExtensions/ext:UBLExtension[2]/ext:ExtensionContent";
                    break;

                case "07":
                    //credit note
                    nsMgr.AddNamespace("tns", "urn:oasis:names:specification:ubl:schema:xsd:CreditNote-2");
                    local_xpath = "/tns:CreditNote/ext:UBLExtensions/ext:UBLExtension[2]/ext:ExtensionContent";
                    break;

                case "08":
                    //debit note
                    nsMgr.AddNamespace("tns", "urn:oasis:names:specification:ubl:schema:xsd:DebitNote-2");
                    local_xpath = "/tns:DebitNote/ext:UBLExtensions/ext:UBLExtension[2]/ext:ExtensionContent";
                    break;

                case "RA":     //Communicacion de baja
                    nsMgr.AddNamespace("tns", "urn:sunat:names:specification:ubl:peru:schema:xsd:VoidedDocuments-1");
                    local_xpath = "/tns:VoidedDocuments/ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent";
                    break;

                case "RC":      //Resument de diario
                    nsMgr.AddNamespace("tns", "urn:sunat:names:specification:ubl:peru:schema:xsd:SummaryDocuments-1");
                    local_xpath = "/tns:SummaryDocuments/ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent";
                    break;
                }
                nsMgr.AddNamespace("cac", "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2");
                nsMgr.AddNamespace("udt", "urn:un:unece:uncefact:data:specification:UnqualifiedDataTypesSchemaModule:2");
                nsMgr.AddNamespace("ext", "urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2");
                nsMgr.AddNamespace("qdt", "urn:oasis:names:specification:ubl:schema:xsd:QualifiedDatatypes-2");
                nsMgr.AddNamespace("cbc", "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2");
                nsMgr.AddNamespace("ds", "http://www.w3.org/2000/09/xmldsig#");

                xmlDoc.SelectSingleNode(local_xpath, nsMgr).AppendChild(xmlDoc.ImportNode(signature, true));
                xmlDoc.Save(local_xmlArchivo);
                XmlNodeList nodeList = xmlDoc.GetElementsByTagName("ds:Signature");
                //el nodo <ds:Signature> debe existir unicamente 1 vez
                if (nodeList.Count != 1)
                {
                    throw new Exception("Se produjo un error en la firma del documento");
                }

                signedXml.LoadXml((XmlElement)nodeList[0]);

                //verificacion de la firma generada
                if (signedXml.CheckSignature() == false)
                {
                    this.IsSigned = false;
                }
                else
                {
                    this.IsSigned = true;
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
Esempio n. 21
0
        private 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", CommonExtensionComponents)
                                    .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();

                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);
        }
Esempio n. 22
0
        //public static string RetornarXmlFirmado(string xmlString, string rutaCertificado, string claveCertificado, out string hash)
        //{
        //    hash = null;

        //    XmlDocument documentXml = new XmlDocument();

        //    documentXml.PreserveWhitespace = true;
        //    documentXml.LoadXml(xmlString);
        //    var nodoExtension = documentXml.GetElementsByTagName("ExtensionContent", "urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2").Item(0);

        //    if (nodoExtension == null)
        //    {
        //        throw new InvalidOperationException("No se pudo encontrar el nodo ExtensionContent en el XML");
        //    }

        //    nodoExtension.RemoveAll();

        //    SignedXml firmado = new SignedXml(documentXml);

        //    var xmlSignature = firmado.Signature;

        //    byte[] certificadoByte = File.ReadAllBytes(rutaCertificado);
        //    X509Certificate2 certificado = new X509Certificate2();
        //    //certificado.Import(certificadoByte, claveCertificado, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);
        //    certificado.Import(certificadoByte, claveCertificado, X509KeyStorageFlags.Exportable);
        //    firmado.SigningKey = certificado.GetRSAPrivateKey();
        //    //firmado.SigningKey = (RSA)certificado.PrivateKey;
        //    //firmado.SigningKey = certificado.PrivateKey;

        //    //digest info agregada en la seccion firma
        //    var env = new XmlDsigEnvelopedSignatureTransform();
        //    Reference reference = new Reference();
        //    reference.AddTransform(env);

        //    reference.Uri = "";
        //    firmado.AddReference(reference);
        //    firmado.SignedInfo.SignatureMethod = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";

        //    reference.DigestMethod = "http://www.w3.org/2001/04/xmlenc#sha256";

        //    var keyInfoData = new KeyInfoX509Data(certificado);
        //    keyInfoData.AddSubjectName(certificado.Subject);

        //    // info para la llave publica
        //    KeyInfo keyInfo = new KeyInfo();
        //    keyInfo.AddClause(keyInfoData);
        //    //keyInfo.sub

        //    xmlSignature.KeyInfo = keyInfo;
        //    xmlSignature.Id = "signatureKG";
        //    firmado.ComputeSignature();


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

        //    XmlNode xmlNodeFirmado = firmado.GetXml();
        //    xmlNodeFirmado.Prefix = "ds";

        //    //XmlNode xmlNodeContent = documentXml.CreateElement("ext", "ExtensionContent", "urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2");
        //    //xmlNodeContent.AppendChild(xmlNodeFirmado);

        //    //XmlNode xmlNode = documentXml.CreateElement("ext", "UBLExtension", "urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2");
        //    //xmlNode.AppendChild(xmlNodeContent);

        //    nodoExtension.AppendChild(xmlNodeFirmado);

        //    var settings = new XmlWriterSettings()
        //    {
        //        Encoding = Encoding.UTF8,
        //        Indent = true,
        //        IndentChars = "\t",
        //        NewLineChars = Environment.NewLine

        //    };

        //    string resultado = String.Empty;
        //    using (var memDoc = new MemoryStream())
        //    {

        //        using (var writer = XmlWriter.Create(memDoc, settings))
        //        {
        //            //XDocument xDocument = XDocument.Parse(documentXml.OuterXml);
        //            //xDocument.WriteTo(writer);
        //            documentXml.WriteTo(writer);
        //        }

        //        //resultado = Encoding.Unicode.GetString(memDoc.ToArray());
        //        //resultado = Encoding.GetEncoding("ISO-8859-1").GetString(memDoc.ToArray());
        //        //resultado = Convert.ToBase64String(memDoc.ToArray());
        //        resultado = Encoding.UTF8.GetString(memDoc.ToArray());

        //    }
        //    return resultado;
        //}

        public static string RetornarXmlFirmado(string prefijoComprobanteBusqueda, string tnsString, string xmlString, string rutaCertificado, string claveCertificado, out string hash)
        {
            hash = null;

            XmlDocument xmlDocument = new XmlDocument();

            xmlDocument.PreserveWhitespace = true;
            xmlDocument.LoadXml(xmlString);

            X509Certificate2 certificado = new X509Certificate2(rutaCertificado, claveCertificado);

            XmlNamespaceManager nsMgr = new XmlNamespaceManager(xmlDocument.NameTable);

            nsMgr.AddNamespace("tns", tnsString);
            nsMgr.AddNamespace("ext", "urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2");

            XmlElement elem = xmlDocument.CreateElement("ext:ExtensionContent", "urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2");

            xmlDocument.SelectSingleNode($"{prefijoComprobanteBusqueda}/ext:UBLExtensions/ext:UBLExtension", nsMgr).AppendChild(elem);

            SignedXml signedXml = new SignedXml(xmlDocument);

            signedXml.SigningKey = certificado.GetRSAPrivateKey();
            System.Security.Cryptography.Xml.KeyInfo KeyInfo = new System.Security.Cryptography.Xml.KeyInfo();

            System.Security.Cryptography.Xml.Reference Reference = new System.Security.Cryptography.Xml.Reference();
            Reference.Uri = "";

            Reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
            signedXml.AddReference(Reference);

            X509Chain X509Chain = new X509Chain();

            X509Chain.Build(certificado);

            X509ChainElement local_element = X509Chain.ChainElements[0];
            KeyInfoX509Data  x509Data      = new KeyInfoX509Data(local_element.Certificate);

            string subjectName = local_element.Certificate.Subject;

            x509Data.AddSubjectName(subjectName);
            KeyInfo.AddClause(x509Data);
            signedXml.Signature.Id = "signatureKG";
            signedXml.KeyInfo      = KeyInfo;
            signedXml.ComputeSignature();
            XmlElement signature = signedXml.GetXml();
            XmlNode    dg        = signature.GetElementsByTagName("DigestValue", "http://www.w3.org/2000/09/xmldsig#")[0];
            XmlNode    sg        = signature.GetElementsByTagName("SignatureValue", "http://www.w3.org/2000/09/xmldsig#")[0];

            hash = dg.InnerText;
            //SignatureValue = sg.InnerText;

            signature.Prefix = "ds";
            //SetPrefix("ds", signature);

            elem.AppendChild(signature);

            MemoryStream msXMLFirmado = new MemoryStream();

            xmlDocument.Save(msXMLFirmado);

            //msXMLFirmado.Position = 1;

            return(Encoding.UTF8.GetString(msXMLFirmado.ToArray()).Substring(1));
        }
Esempio n. 23
0
        public XmlDocument CreateXml(IList <SmpService> services)
        {
            var firstService = services.First();
            var participant  = Peppol.Common.Model.ParticipantIdentifier.Parse(firstService.PeppolParticipant.Identifier);
            var documentType = DocumentTypeIdentifier.Parse(firstService.PeppolDocument.Identifier);


            var signedServiceMetadata = new SignedServiceMetadata();
            var serviceMetadata       = new ServiceMetadata();

            signedServiceMetadata.ServiceMetadata = serviceMetadata;
            var serviceInfo = new ServiceInformationType();

            serviceMetadata.ServiceInformation = serviceInfo;

            serviceInfo.ParticipantIdentifier                = new ParticipantIdentifier();
            serviceInfo.ParticipantIdentifier.Scheme         = participant.Scheme.Identifier;
            serviceInfo.ParticipantIdentifier.PrimitiveValue = participant.Identifier;

            serviceInfo.DocumentIdentifier                = new DocumentIdentifier();
            serviceInfo.DocumentIdentifier.Scheme         = documentType.Scheme.Identifier;
            serviceInfo.DocumentIdentifier.PrimitiveValue = documentType.Identifier;
            serviceInfo.ProcessList = new ProcessListType();

            foreach (var service in services)
            {
                var process = new ProcessType();
                serviceInfo.ProcessList.Process.Add(process);
                var processIdentifier =
                    Peppol.Common.Model.ProcessIdentifier.Parse(service.PeppolProcess.Identifier);
                process.ProcessIdentifier                = new ProcessIdentifier();
                process.ProcessIdentifier.Scheme         = processIdentifier.Scheme.Identifier;
                process.ProcessIdentifier.PrimitiveValue = processIdentifier.Identifier;
                process.ServiceEndpointList              = new ServiceEndpointList();

                foreach (var endpoint in service.Endpoints)
                {
                    var xEndpoint = new EndpointType();
                    xEndpoint.EndpointReference = new EndpointReference();
                    xEndpoint.EndpointReference.Address.PrimitiveValue = endpoint.Endpoint;
                    xEndpoint.EndpointReference.ReferenceParameters    = new ReferenceParameters();
                    xEndpoint.EndpointReference.Metadata = new Metadata();
                    xEndpoint.TransportProfile           = "busdox-transport-as2-ver1p0";
                    xEndpoint.Certificate = endpoint.Certificate;
                    xEndpoint.MinimumAuthenticationLevel    = endpoint.MinimumAuthenticationLevel;
                    xEndpoint.RequireBusinessLevelSignature = endpoint.RequireBusinessLevelSignature;
                    xEndpoint.ServiceExpirationDate         = new XmlDateTime(endpoint.ServiceExpirationDate);
                    xEndpoint.ServiceActivationDate         = new XmlDateTime(endpoint.ServiceActivationDate);
                    xEndpoint.ServiceDescription            = endpoint.ServiceDescription;
                    xEndpoint.TechnicalContactUrl           = endpoint.TechnicalContactUrl;
                    process.ServiceEndpointList.Endpoint.Add(xEndpoint);
                }
            }


            var certPath   = "conf\\test-keystore.pfx";
            var certPass   = "******";
            var collection = new X509Certificate2Collection();

            collection.Import(certPath, certPass, X509KeyStorageFlags.PersistKeySet);
            AsymmetricAlgorithm key  = null;
            X509Certificate     cert = null;

            foreach (var certificate in collection)
            {
                if (certificate.HasPrivateKey)
                {
                    key  = certificate.PrivateKey;
                    cert = certificate;
                }
            }
            signedServiceMetadata.Signature            = new Xml.Busdox.ds.Signature();
            signedServiceMetadata.Signature.SignedInfo = new Xml.Busdox.ds.SignedInfo();
            signedServiceMetadata.Signature.SignedInfo.Reference.Add(new Xml.Busdox.ds.Reference());
            var xmlRoot = signedServiceMetadata.ToXmlElement(true, Encoding.UTF8, EOLType.CRLF);

            xmlRoot.RemoveChild(xmlRoot.LastChild);

            var xmlDoc = new XmlDocument();

            xmlDoc.PreserveWhitespace = true;
            xmlDoc.LoadXml(xmlRoot.OuterXml);

            var signedXml = new SignedXml(xmlDoc);

            signedXml.SigningKey = key;

            var reference = new Reference();

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

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

            signedXml.KeyInfo = new KeyInfo();
            var keyClause = new KeyInfoX509Data(cert);

            Debug.Assert(cert != null, nameof(cert) + " != null");
            keyClause.AddSubjectName(cert.Subject);
            signedXml.KeyInfo.AddClause(keyClause);

            var xmlDigitalSignature = signedXml.GetXml();

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

            return(xmlDoc);
        }
Esempio n. 24
0
	static void Test6() //Xml roundtrip
		{
		int i = 0 ; 
		data = new KeyInfoX509Data() ; 

		//add certs
		data.AddCertificate( TestCert ) ; 
		data.AddCertificate( EndCert ) ; 

		//add subject name
		data.AddSubjectName( TestCert.SubjectName.Name ) ; 
		data.AddSubjectName( EndCert.SubjectName.Name ) ; 
		
		//add subject keys
		data.AddSubjectKeyId( new byte[]{1,2,3,4,5,6} ) ; 
		data.AddSubjectKeyId( new byte[]{7,8,9,10,11,12} ) ; 

		//add issuer serials
		data.AddIssuerSerial( TestCert.IssuerName.Name , TestCert.SerialNumber ) ; 
		data.AddIssuerSerial( EndCert.IssuerName.Name , EndCert.SerialNumber ) ; 

		//add the crl
		byte[] b = { 100, 101 , 102 , 104 } ; 
		data.CRL = b ;

		KeyInfoX509Data rt = new KeyInfoX509Data() ; 
		rt.LoadXml( data.GetXml() ) ; 
		for( i = 0 ; i < rt.CRL.Length ; i++ ) 
			{
			rv = rt.CRL[i] == data.CRL[i] ; 
			}

		for( i = 0 ; i < rt.Certificates.Count ; i++ ) 
			{
			rv = rt.Certificates[i].ToString() == data.Certificates[i].ToString() ; 
			}
		for( i = 0 ; i < rt.SubjectKeyIds.Count ; i++ ) 
			{
			rv = rt.SubjectKeyIds[i].ToString() == data.SubjectKeyIds[i].ToString() ; 
			}
		for( i = 0 ; i < rt.SubjectNames.Count ; i++ ) 
			{
			rv = rt.SubjectNames[i].ToString() == data.SubjectNames[i].ToString() ;
			}
		}
Esempio n. 25
0
        public string[] FirmarXml(string tramaXml)
        {
            // Vamos a firmar el XML con la ruta del certificado que está como serializado.
            var certificate = new X509Certificate2(Convert.FromBase64String(RutaCertificadoDigital),
                                                   PasswordCertificado, X509KeyStorageFlags.DefaultKeySet);

            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", CommonExtensionComponents)
                                    .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.GetRSAPrivateKey();
                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      = "SignatureErick";
                signedXml.ComputeSignature();

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

                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);
                    }
                    //using (XmlWriter writer = XmlWriter.Create(rutaXML, settings))
                    //{
                    //    Type typeToSerialize = typeof(InvoiceType);
                    //    XmlSerializer xs = new XmlSerializer(typeToSerialize);
                    //    xs.Serialize(writer, Documento);
                    //}
                    resultado = Convert.ToBase64String(memDoc.ToArray());
                }
            }

            string[] Res = new string[2];
            Res[0] = resultado;
            Res[1] = DigestValue;
            return(Res);
        }
Esempio n. 26
0
        public FirmadoResponse FirmaXMl(FirmadoRequest request)
        {
            var response = new FirmadoResponse();

            var certificate = new X509Certificate2();

            certificate.Import(request.ruta_Firma, request.contra_Firma, X509KeyStorageFlags.MachineKeySet);

            var xmlDoc = new XmlDocument();

            xmlDoc.PreserveWhitespace = true;
            xmlDoc.Load(request.ruta_xml);

            var nodoExtension = xmlDoc.GetElementsByTagName("ExtensionContent", "urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2").Item(request.flg_firma);

            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 = 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      = "SignFacturacionElectronica";
            signedXml.ComputeSignature();

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

            nodoExtension.AppendChild(signedXml.GetXml());

            using (var memDoc = new MemoryStream())
            {
                using (var writer = XmlWriter.Create(memDoc,
                                                     new XmlWriterSettings {
                    Encoding = Encoding.GetEncoding("utf-8")
                }))
                {
                    xmlDoc.WriteTo(writer);
                }

                xmlDoc.Save(request.ruta_xml);
            }

            return(response);
        }
Esempio n. 27
0
        public void Serialize(XmlWriter writer,
                              X509Certificate2 signingKey,
                              string id,
                              string issuerName,
                              string samlUrl,
                              string wsFedUrl)
        {
            if (writer == null)
            {
                throw new ArgumentNullException(nameof(writer));
            }
            if (string.IsNullOrWhiteSpace(id))
            {
                throw new ArgumentNullException(nameof(id));
            }
            if (string.IsNullOrWhiteSpace(issuerName))
            {
                throw new ArgumentNullException(nameof(issuerName));
            }
            if (string.IsNullOrWhiteSpace(samlUrl))
            {
                throw new ArgumentNullException(nameof(samlUrl));
            }
            if (string.IsNullOrWhiteSpace(wsFedUrl))
            {
                throw new ArgumentNullException(nameof(wsFedUrl));
            }

            var keyInfo = new KeyInfoX509Data(signingKey);

            keyInfo.AddIssuerSerial(signingKey.IssuerName.Name, signingKey.SerialNumber);
            keyInfo.AddSubjectName(signingKey.SubjectName.Name);

            var keyInfoXml = keyInfo.GetXml().OuterXml;

            writer.WriteStartElement("EntityDescriptor", Saml20Namespace);
            writer.WriteAttributeString("ID", id);
            writer.WriteAttributeString("entityID", issuerName);

            //IDPSSODescriptor
            writer.WriteStartElement("IDPSSODescriptor", Saml20Namespace);
            writer.WriteAttributeString("protocolSupportEnumeration", "urn:oasis:names:tc:SAML:2.0:protocol");

            //KeyDescriptor
            writer.WriteStartElement("KeyDescriptor", Saml20Namespace);
            writer.WriteAttributeString("use", "signing");
            writer.WriteStartElement("KeyInfo", XmlDSigNamespace);
            writer.WriteRaw(keyInfoXml);
            writer.WriteEndElement();
            writer.WriteEndElement();

            //SingleLogoutService
            writer.WriteStartElement("SingleLogoutService", Saml20Namespace);
            writer.WriteAttributeString("Binding", "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST");
            writer.WriteAttributeString("Location", samlUrl);
            writer.WriteEndElement();

            //SingleSignOnService
            writer.WriteStartElement("SingleSignOnService", Saml20Namespace);
            writer.WriteAttributeString("Binding", "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST");
            writer.WriteAttributeString("Location", samlUrl);
            writer.WriteEndElement();

            writer.WriteEndElement();

            //RoleDescriptor
            WriteRoleDescriptor(writer, issuerName, wsFedUrl, keyInfoXml, "SecurityTokenServiceType");

            //RoleDescriptor
            WriteRoleDescriptor(writer, issuerName, wsFedUrl, keyInfoXml, "ApplicationServiceType");

            writer.WriteEndElement();
        }
Esempio n. 28
0
        ///////////////////////////////////////////////////////////////////////
        ///
        /// <summary>
        /// Carry out the Sign command.
        /// </summary>
        ///
        static void DoSignCommand(string title, X509Certificate2 certificate)
        {
            Console.WriteLine();
            Console.WriteLine("Signing Xml file \"" + fileNames[0] + "\"...");
            Console.WriteLine();

            // display more details for verbose operation.
            if (verbose)
            {
                DisplayDetail(null, certificate, detached);
            }

            SignedXml signedXml         = new SignedXml();
            ICspAsymmetricAlgorithm csp = (ICspAsymmetricAlgorithm)certificate.PrivateKey;

            if (csp.CspKeyContainerInfo.RandomlyGenerated)
            {
                throw new InternalException("Internal error: This certificate does not have a corresponding private key.");
            }
            signedXml.SigningKey = (AsymmetricAlgorithm)csp;
            Console.WriteLine(signedXml.SigningKey.ToXmlString(false));

            if (detached)
            {
                Reference reference = new Reference();
                reference.Uri = "file://" + Path.GetFullPath((string)fileNames[0]);
                signedXml.AddReference(reference);
            }
            else
            {
                Reference reference = new Reference();
                reference.Uri = "#object-1";

                // Add an object
                XmlDocument dataObject = new XmlDocument();
                dataObject.PreserveWhitespace = true;
                XmlElement dataElement = (XmlElement)dataObject.CreateElement("DataObject", SignedXml.XmlDsigNamespaceUrl);
                dataElement.AppendChild(dataObject.CreateTextNode(new UTF8Encoding(false).GetString(ReadFile((string)fileNames[0]))));
                dataObject.AppendChild(dataElement);
                DataObject obj = new DataObject();
                obj.Data = dataObject.ChildNodes;
                obj.Id   = "object-1";
                signedXml.AddObject(obj);
                signedXml.AddReference(reference);
            }

            signedXml.KeyInfo = new KeyInfo();
            if (includeOptions.Count == 0)
            {
                signedXml.KeyInfo.AddClause(new KeyInfoX509Data(certificate, X509IncludeOption.ExcludeRoot));
            }
            else
            {
                KeyInfoX509Data keyInfoX509Data = new KeyInfoX509Data();
                foreach (IncludeOptions includeOption in includeOptions)
                {
                    switch (includeOption)
                    {
                    case IncludeOptions.ExcludeRoot:
                    case IncludeOptions.EndCertOnly:
                    case IncludeOptions.WholeChain:
                        keyInfoX509Data = new KeyInfoX509Data(certificate, (X509IncludeOption)includeOption);
                        break;

                    case IncludeOptions.SubjectName:
                        keyInfoX509Data.AddSubjectName(certificate.SubjectName.Name);
                        break;

                    case IncludeOptions.SKI:
                        X509ExtensionCollection extensions = certificate.Extensions;
                        foreach (X509Extension extension in extensions)
                        {
                            if (extension.Oid.Value == "2.5.29.14")   // OID for SKI extension
                            {
                                X509SubjectKeyIdentifierExtension ski = extension as X509SubjectKeyIdentifierExtension;
                                if (ski != null)
                                {
                                    keyInfoX509Data.AddSubjectKeyId(ski.SubjectKeyIdentifier);
                                    break;
                                }
                            }
                        }
                        break;

                    case IncludeOptions.IssuerSerial:
                        keyInfoX509Data.AddIssuerSerial(certificate.IssuerName.Name, certificate.SerialNumber);
                        break;
                    }

                    signedXml.KeyInfo.AddClause(keyInfoX509Data);
                }
            }

            // compute the signature
            signedXml.ComputeSignature();
            XmlElement xmlDigitalSignature = signedXml.GetXml();

            // write it out
            XmlTextWriter xmltw = new XmlTextWriter((string)fileNames[1], new UTF8Encoding(false));

            xmlDigitalSignature.WriteTo(xmltw);
            xmltw.Close();

            Console.WriteLine();
            Console.WriteLine("Signature written to file \"" + fileNames[1] + "\".");
            Console.WriteLine();

            return;
        }
Esempio n. 29
0
        private string FirmarXml(string pathxml, String etiquetapadre, string ruta, string claveCertificado)
        {
            XmlDocument xmlDoc = new XmlDocument();

            xmlDoc.PreserveWhitespace = true;
            xmlDoc.Load(pathxml);

            //var ruta = Server.MapPath("~/Certificado/");
            var DigestValue    = "";
            var SignatureValue = "";

            //X509Certificate2 myCert = new X509Certificate2(ruta + "Certificado_Sunat_PFX_Comerc.deCombustiblesTriveño_20171018.pfx", "#DESW2ASDZX");

            X509Certificate2         myCert = new X509Certificate2(ruta, claveCertificado);
            RSACryptoServiceProvider rsaKey = (RSACryptoServiceProvider)myCert.PrivateKey;
            SignedXml signedXml             = new SignedXml(xmlDoc);

            signedXml.SigningKey = rsaKey;

            Reference reference = new Reference();

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

            reference.AddTransform(env);
            signedXml.AddReference(reference);

            KeyInfo   KeyInfo   = new KeyInfo();
            X509Chain X509Chain = new X509Chain();

            X509Chain.Build(myCert);
            X509ChainElement local_element = X509Chain.ChainElements[0];
            KeyInfoX509Data  x509Data      = new KeyInfoX509Data(local_element.Certificate);
            String           subjectName   = local_element.Certificate.Subject;

            x509Data.AddSubjectName(subjectName);
            KeyInfo.AddClause(x509Data);

            signedXml.KeyInfo = KeyInfo;

            signedXml.ComputeSignature();

            XmlElement xmlDigitalSignature = signedXml.GetXml();

            xmlDigitalSignature.Prefix = "ds";
            signedXml.ComputeSignature();
            foreach (XmlNode node in xmlDigitalSignature.SelectNodes("descendant-or-self::*[namespace-uri()='http://www.w3.org/2000/09/xmldsig#']"))
            {
                if (node.LocalName == "Signature")
                {
                    XmlAttribute newAtribute = xmlDoc.CreateAttribute("Id");
                    newAtribute.Value = "SignatureSP";
                    node.Attributes.Append(newAtribute);
                }
            }

            XmlNamespaceManager nsMgr = new XmlNamespaceManager(xmlDoc.NameTable);

            nsMgr.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");

            string l_xpath = "";

            if (pathxml.Contains("-01-")) //factura
            {
                nsMgr.AddNamespace("sac", "urn:sunat:names:specification:ubl:peru:schema:xsd:SunatAggregateComponents-1");
                nsMgr.AddNamespace("ccts", "urn:un:unece:uncefact:documentation:2");
                nsMgr.AddNamespace("tns", "urn:oasis:names:specification:ubl:schema:xsd:Invoice-2");

                nsMgr.AddNamespace("cac", "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2");
                nsMgr.AddNamespace("udt", "urn:un:unece:uncefact:data:specification:UnqualifiedDataTypesSchemaModule:2");
                nsMgr.AddNamespace("ext", "urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2");
                nsMgr.AddNamespace("qdt", "urn:oasis:names:specification:ubl:schema:xsd:QualifiedDatatypes-2");
                nsMgr.AddNamespace("cbc", "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2");
                nsMgr.AddNamespace("ds", "http://www.w3.org/2000/09/xmldsig#");
                //l_xpath = "/tns:Invoice/ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent";
                l_xpath = "/tns:Invoice/ext:UBLExtensions/ext:UBLExtension[2]/ext:ExtensionContent";
            }
            if (pathxml.Contains("-03-")) //BOLETA
            {
                nsMgr.AddNamespace("sac", "urn:sunat:names:specification:ubl:peru:schema:xsd:SunatAggregateComponents-1");
                nsMgr.AddNamespace("ccts", "urn:un:unece:uncefact:documentation:2");
                nsMgr.AddNamespace("tns", "urn:oasis:names:specification:ubl:schema:xsd:Invoice-2");

                nsMgr.AddNamespace("cac", "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2");
                nsMgr.AddNamespace("udt", "urn:un:unece:uncefact:data:specification:UnqualifiedDataTypesSchemaModule:2");
                nsMgr.AddNamespace("ext", "urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2");
                nsMgr.AddNamespace("qdt", "urn:oasis:names:specification:ubl:schema:xsd:QualifiedDatatypes-2");
                nsMgr.AddNamespace("cbc", "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2");
                nsMgr.AddNamespace("ds", "http://www.w3.org/2000/09/xmldsig#");

                l_xpath = "/tns:Invoice/ext:UBLExtensions/ext:UBLExtension[2]/ext:ExtensionContent";
            }
            if (pathxml.Contains("-07-")) //nota de credito
            {
                nsMgr.AddNamespace("sac", "urn:sunat:names:specification:ubl:peru:schema:xsd:SunatAggregateComponents-1");
                nsMgr.AddNamespace("ccts", "urn:un:unece:uncefact:documentation:2");
                nsMgr.AddNamespace("tns", "urn:oasis:names:specification:ubl:schema:xsd:CreditNote-2");

                nsMgr.AddNamespace("cac", "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2");
                nsMgr.AddNamespace("udt", "urn:un:unece:uncefact:data:specification:UnqualifiedDataTypesSchemaModule:2");
                nsMgr.AddNamespace("ext", "urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2");
                nsMgr.AddNamespace("qdt", "urn:oasis:names:specification:ubl:schema:xsd:QualifiedDatatypes-2");
                nsMgr.AddNamespace("cbc", "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2");
                nsMgr.AddNamespace("ds", "http://www.w3.org/2000/09/xmldsig#");

                l_xpath = "/tns:CreditNote/ext:UBLExtensions/ext:UBLExtension[2]/ext:ExtensionContent";
            }
            if (pathxml.Contains("-08-"))//nota de d�bito
            {
                nsMgr.AddNamespace("sac", "urn:sunat:names:specification:ubl:peru:schema:xsd:SunatAggregateComponents-1");
                nsMgr.AddNamespace("ccts", "urn:un:unece:uncefact:documentation:2");
                nsMgr.AddNamespace("tns", "urn:oasis:names:specification:ubl:schema:xsd:DebitNote-2");

                nsMgr.AddNamespace("cac", "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2");
                nsMgr.AddNamespace("udt", "urn:un:unece:uncefact:data:specification:UnqualifiedDataTypesSchemaModule:2");
                nsMgr.AddNamespace("ext", "urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2");
                nsMgr.AddNamespace("qdt", "urn:oasis:names:specification:ubl:schema:xsd:QualifiedDatatypes-2");
                nsMgr.AddNamespace("cbc", "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2");
                nsMgr.AddNamespace("ds", "http://www.w3.org/2000/09/xmldsig#");

                l_xpath = "/tns:DebitNote/ext:UBLExtensions/ext:UBLExtension[2]/ext:ExtensionContent";
            }
            if (pathxml.Contains("RA")) // documento de baja
            {
                nsMgr.AddNamespace("tns", "urn:sunat:names:specification:ubl:peru:schema:xsd:VoidedDocuments-1");
                nsMgr.AddNamespace("sac", "urn:sunat:names:specification:ubl:peru:schema:xsd:SunatAggregateComponents-1");
                nsMgr.AddNamespace("cac", "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2");
                nsMgr.AddNamespace("ext", "urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2");
                nsMgr.AddNamespace("cbc", "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2");
                nsMgr.AddNamespace("ds", "http://www.w3.org/2000/09/xmldsig#");

                l_xpath = "/tns:VoidedDocuments/ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent";
            }
            if (pathxml.Contains("RC"))// documento de revision de boleta
            {
                nsMgr.AddNamespace("tns", "urn:sunat:names:specification:ubl:peru:schema:xsd:SummaryDocuments-1");
                nsMgr.AddNamespace("sac", "urn:sunat:names:specification:ubl:peru:schema:xsd:SunatAggregateComponents-1");
                nsMgr.AddNamespace("cac", "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2");
                nsMgr.AddNamespace("ext", "urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2");
                nsMgr.AddNamespace("cbc", "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2");
                nsMgr.AddNamespace("ds", "http://www.w3.org/2000/09/xmldsig#");

                l_xpath = "/tns:SummaryDocuments/ext:UBLExtensions/ext:UBLExtension/ext:ExtensionContent";
            }

            XmlNode counterSignature = xmlDoc.SelectSingleNode(l_xpath, nsMgr);

            counterSignature.AppendChild(xmlDoc.ImportNode(xmlDigitalSignature, true));

            XmlNodeList elemList = xmlDoc.GetElementsByTagName("DigestValue");

            for (int i = 0; i < elemList.Count; i++)
            {
                DigestValue = elemList[i].InnerXml;
            }

            XmlNodeList elemList2 = xmlDoc.GetElementsByTagName("SignatureValue");

            for (int i = 0; i < elemList2.Count; i++)
            {
                SignatureValue = elemList2[i].InnerXml;
            }
            xmlDoc.Save(pathxml);
            return(DigestValue + "|" + SignatureValue);
        }
Esempio n. 30
0
        async Task <FirmadoResponse> ICertificador.FirmarXml(FirmadoRequest request)
        {
            var task = Task.Factory.StartNew(() =>
            {
                var response = new FirmadoResponse();

                var certificate = new X509Certificate2();
                certificate.Import(Convert.FromBase64String(request.CertificadoDigital), request.PasswordCertificado, X509KeyStorageFlags.MachineKeySet);

                var xmlDoc = new XmlDocument();

                string resultado;

                var betterBytes = Encoding.Convert(Encoding.UTF8, Encoding.GetEncoding(Formatos.EncodingIso),
                                                   Convert.FromBase64String(request.TramaXmlSinFirma));

                using (var documento = new MemoryStream(betterBytes))
                {
                    xmlDoc.PreserveWhitespace = false;
                    xmlDoc.Load(documento);

                    var indiceNodo = request.UnSoloNodoExtension ?   0   :   1;

                    var nodoExtension = xmlDoc.GetElementsByTagName("ExtensionContent", EspacioNombres.ext).Item(indiceNodo);

                    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 = 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      = "SignatureSP";
                    signedXml.ComputeSignature();

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

                    response.ValorFirma = Convert.ToBase64String(signedXml.SignatureValue);

                    nodoExtension.AppendChild(signedXml.GetXml());

                    using (var memDoc = new MemoryStream())
                    {
                        using (var writer = XmlWriter.Create(memDoc, new XmlWriterSettings {
                            Encoding = Encoding.GetEncoding(Formatos.EncodingIso)
                        }))
                        {
                            xmlDoc.WriteTo(writer);
                        }
                        resultado = Convert.ToBase64String(memDoc.ToArray());
                    }
                }
                response.TramaXmlFirmado = resultado;

                return(response);
            });

            return(await task);
        }
Esempio n. 31
0
        public XmlDocument FirmarXml(XmlDocument xmlDoc, string ruc, ref string codigoHash, ref string firma)
        {
            XmlDocument xmlDocument = null;

            try
            {
                if (xmlDoc == null)
                {
                    ArgumentException nex = new ArgumentException("El documento XML generado es nulo.");
                    throw nex;
                }

                SignedXml signedXml = new SignedXml(xmlDoc);
                Reference reference = new Reference()
                {
                    Uri = ""
                };
                reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
                signedXml.AddReference(reference);
                string           carpetaCertificado       = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Certificado");
                string           nombreArchivoCertificado = string.Format("{0}.pfx", ruc);
                byte[]           bytesCertificado         = File.ReadAllBytes(Path.Combine(carpetaCertificado, nombreArchivoCertificado));
                X509Certificate2 certificado = new X509Certificate2(bytesCertificado, ruc); //DevuelveCertificado(ruc);
                string           subjectName = certificado.SubjectName.Name;

                KeyInfo keyInfo = new KeyInfo();
                try
                {
                    signedXml.SigningKey = certificado.PrivateKey;
                }
                catch
                {
                    Exception nex = new Exception("m_safeCertContext es un controlador no válido.");
                    throw nex;
                }
                KeyInfoX509Data kData = new KeyInfoX509Data(certificado);
                kData.AddSubjectName(subjectName);
                keyInfo.AddClause(kData);
                signedXml.KeyInfo      = keyInfo;
                signedXml.Signature.Id = "signatureKG";
                signedXml.ComputeSignature();
                XmlElement xmlDigitalSignature = signedXml.GetXml();
                var        insertoFirma        = false;
                InsertaFirma(xmlDoc.ChildNodes, xmlDigitalSignature, ref insertoFirma);
                if (!insertoFirma)
                {
                    throw new Exception("No se ha insertado la firma.");
                }
                else
                {
                    log.Info("Se firmó satisfactoriamente el comprobante.");
                }
                codigoHash                     = xmlDigitalSignature.ChildNodes[0].ChildNodes[2].ChildNodes[2].InnerText;
                firma                          = xmlDigitalSignature.ChildNodes[1].InnerText;
                keyInfo                        = null;
                reference                      = null;
                signedXml                      = null;
                xmlDigitalSignature            = null;
                xmlDocument                    = xmlDoc;
                xmlDocument.PreserveWhitespace = true;
            }
            catch (Exception exception)
            {
                log.Error(exception.Message, exception);
                throw;
            }
            return(xmlDocument);
        }