Esempio n. 1
1
        /// <exception cref="System.IO.IOException"></exception>
        //private CmsSignedDataGenerator CreateCMSSignedDataGenerator(ContentSigner contentSigner
        //    , DigestCalculatorProvider digestCalculatorProvider, SignatureParameters parameters
        //    , CAdESProfileBES cadesProfile, bool includeUnsignedAttributes, CmsSignedData originalSignedData
        //    )
        private CmsSignedDataGenerator CreateCMSSignedDataGenerator(ISigner signer
            , SignatureParameters parameters, CAdESProfileBES cadesProfile
            , bool includeUnsignedAttributes, CmsSignedData originalSignedData
            )
        {
            try
            {
                CmsSignedDataGenerator generator = new CmsSignedDataGenerator();
                X509Certificate signerCertificate = parameters.SigningCertificate;

                //X509CertificateHolder certHolder = new X509CertificateHolder(signerCertificate.GetEncoded());
                ArrayList certList = new ArrayList();
                certList.Add(signerCertificate);
                IX509Store certHolder = X509StoreFactory.Create("CERTIFICATE/COLLECTION",
                    new X509CollectionStoreParameters(certList));

                //jbonilla - El provider siempre es BC C#
                //SignerInfoGeneratorBuilder sigInfoGeneratorBuilder = new SignerInfoGeneratorBuilder
                //    (digestCalculatorProvider);

                CmsAttributeTableGenerator signedAttrGen = new DefaultSignedAttributeTableGenerator
                    (new AttributeTable(cadesProfile.GetSignedAttributes(parameters)));

                CmsAttributeTableGenerator unsignedAttrGen = new SimpleAttributeTableGenerator
                    ((includeUnsignedAttributes) ? new AttributeTable(cadesProfile.GetUnsignedAttributes
                    (parameters)) : null);

                //jbonilla - No existe ContentSigner en BC C#
                //SignerInfoGenerator sigInfoGen = sigInfoGeneratorBuilder.Build(contentSigner, certHolder);                

                //generator.AddSignerInfoGenerator(sigInfoGen);
                generator.SignerProvider = signer;
                generator.AddSigner(new NullPrivateKey(), signerCertificate, parameters.SignatureAlgorithm.GetOid()
                    , parameters.DigestAlgorithm.GetOid(), signedAttrGen, unsignedAttrGen);

                if (originalSignedData != null)
                {
                    generator.AddSigners(originalSignedData.GetSignerInfos());
                }
                //ICollection<X509Certificate> certs = new AList<X509Certificate>();
                IList certs = new ArrayList();
                //certs.AddItem(parameters.SigningCertificate);
                certs.Add(parameters.SigningCertificate);
                if (parameters.CertificateChain != null)
                {
                    foreach (X509Certificate c in parameters.CertificateChain)
                    {
                        if (!c.SubjectDN.Equals(parameters.SigningCertificate.SubjectDN))
                        {
                            //certs.AddItem(c);
                            certs.Add(c);
                        }
                    }
                }
                //JcaCertStore certStore = new JcaCertStore(certs);
                IX509Store certStore = X509StoreFactory.Create("Certificate/Collection",
                    new X509CollectionStoreParameters(certs));
                generator.AddCertificates(certStore);
                if (originalSignedData != null)
                {
                    generator.AddCertificates(originalSignedData.GetCertificates("Collection"));
                }
                return generator;
            }
            catch (CmsException e)
            {
                throw new IOException("CmsException", e);
            }
            catch (CertificateEncodingException e)
            {
                throw new IOException("CertificateEncodingException", e);
            }
            /*catch (OperatorCreationException e)
			{
				throw new IOException(e);
			}*/
        }
Esempio n. 2
0
        public void RunInvoiceSignature()
        {
            XadesService        xadesService = new XadesService();
            SignatureParameters parametros   = new SignatureParameters();

            string ficheroFactura = Path.Combine(rootDirectory, @"Facturae.xml");

            // Política de firma de factura-e 3.1
            parametros.SignaturePolicyInfo = new SignaturePolicyInfo
            {
                PolicyIdentifier = "http://www.facturae.es/politica_de_firma_formato_facturae/politica_de_firma_formato_facturae_v3_1.pdf",
                PolicyHash       = "Ohixl6upD6av8N7pEvDABhEL6hM="
            };
            parametros.SignaturePackaging = SignaturePackaging.ENVELOPED;
            parametros.InputMimeType      = "text/xml";
            parametros.SignerRole         = new SignerRole();
            parametros.SignerRole.ClaimedRoles.Add("emisor");

            using (parametros.Signer = new Signer(_signCertificate))
            {
                using (FileStream fs = new FileStream(ficheroFactura, FileMode.Open))
                {
                    var docFirmado = xadesService.Sign(fs, parametros);
                    ValidateDocument(docFirmado.Document.OuterXml);
                }
            }
        }
Esempio n. 3
0
 public void FirmaXML_Xades(string pathXML, string thumbprintCertificado)
 {
     try
     {
         X509Certificate2 cert = GetCertificateByThumbprint(thumbprintCertificado);
         // 'Ejemplo de un valor Thumbprint: C2E8D9DA714C98ED14B88ECBC4C3E5F3BD64F125
         // 'Si no se quiere leer el certificado del repositorio, se puede cargar el certificado directamente
         // 'Dim cert As X509Certificate2 = New X509Certificate2("rutaArchivoCertificado", "clave")
         XadesService        xadesService = new XadesService();
         SignatureParameters parametros   = new SignatureParameters();
         parametros.SignaturePolicyInfo = new SignaturePolicyInfo();
         parametros.SignaturePolicyInfo.PolicyIdentifier = "https://tribunet.hacienda.go.cr/docs/esquemas/2016/v4.1/Resolucion_Comprobantes_Electronicos_DGT-R-48" +
                                                           "-2016.pdf";
         parametros.SignaturePolicyInfo.PolicyHash = "Ohixl6upD6av8N7pEvDABhEL6hM=";
         parametros.SignaturePackaging             = SignaturePackaging.ENVELOPED;
         parametros.DataFormat = new DataFormat();
         parametros.Signer     = new FirmaXadesNet.Crypto.Signer(cert);
         FileStream fs = new FileStream((pathXML + "_01_SF.xml"), FileMode.Open);
         FirmaXadesNet.Signature.SignatureDocument docFirmado = xadesService.Sign(fs, parametros);
         docFirmado.Save((pathXML + "_02_Firmado.xml"));
         // El documento se firma con el dll FirmaXadesNet
         // Esta libreria fue creada por Departamento de Nuevas Tecnolog�as - Direcci�n General de Urbanismo Ayuntamiento de Cartagena
         // 'Fuente original se puede descargar en administracionelectronica.gob.es/ctt/firmaxadesnet
         // 'La libreria se modific� levemente para que pueda funcionar para Costa Rica.
         // 'Cambios por Roy Rojas - [email protected] - 06/Febrero/2018
         fs.Close();
         docFirmado = null;
     }
     catch (Exception ex)
     {
         throw;
     }
 }
Esempio n. 4
0
        /// <summary>The ID of xades:SignedProperties is contained in the signed content of the xades Signature.
        ///     </summary>
        /// <remarks>
        /// The ID of xades:SignedProperties is contained in the signed content of the xades Signature. We must create this
        /// ID in a deterministic way. The signingDate and signingCertificate are mandatory in the more basic level of
        /// signature, we use them as "seed" for generating the ID.
        /// </remarks>
        /// <param name="params"></param>
        /// <returns></returns>
        internal virtual string ComputeDeterministicId(SignatureParameters parameters)
        {
            try
            {
                IDigest digest = DigestUtilities.GetDigest("MD5");

                byte[] block;
                block = Encoding.ASCII.GetBytes(parameters.SigningDate.ToString());
                digest.BlockUpdate(block, 0, block.Length);
                block = parameters.SigningCertificate.GetEncoded();
                digest.BlockUpdate(block, 0, block.Length);

                string md5id = "id" + Hex.ToHexString(DigestUtilities.DoFinal(digest));
                return(md5id);
            }
            catch (NoSuchAlgorithmException ex)
            {
                LOG.Error(ex.Message);
                throw new Exception("MD5 Algorithm not found !");
            }
            catch (CertificateEncodingException)
            {
                throw new Exception("Certificate encoding exception");
            }
        }
Esempio n. 5
0
        protected internal virtual Stream GetToBeSignedStream(Document document, SignatureParameters
                                                              parameters)
        {
            XmlDocument    envelopedSignatureXmlDocument;
            XadesSignedXml xadesSignedXml;

            envelopedSignatureXmlDocument = XmlUtils.ToXmlDocument(document);
            xadesSignedXml = CreateFromXmlDocument(envelopedSignatureXmlDocument);

            string uid         = ComputeDeterministicId(parameters);
            string signatureId = "sigId-" + uid;
            string signedId    = "xades-" + uid;

            xadesSignedXml.Signature.Id = signatureId;

            XadesObject xadesObject = new XadesObject();

            //xadesObject.Id = "XadesObject";
            xadesObject.QualifyingProperties.SignedProperties.Id = signedId;
            xadesObject.QualifyingProperties.Target = "#" + signatureId;

            this.AddSignedSignatureProperties(
                xadesObject.QualifyingProperties.SignedProperties.SignedSignatureProperties,
                xadesObject.QualifyingProperties.SignedProperties.SignedDataObjectProperties,
                xadesObject.QualifyingProperties.UnsignedProperties.UnsignedSignatureProperties,
                parameters);

            xadesSignedXml.AddXadesObject(xadesObject);

            return(xadesSignedXml.PreComputeSignature());
        }
Esempio n. 6
0
        private void btnContraFirma_Click(object sender, EventArgs e)
        {
            if (_signatureDocument == null)
            {
                return;
            }

            FrmSeleccionarFirma frm = new FrmSeleccionarFirma(_signatureDocument);

            if (frm.ShowDialog() != System.Windows.Forms.DialogResult.OK)
            {
                MessageBox.Show("Debe seleccionar una firma");
                return;
            }

            SignatureParameters parametros = ObtenerParametrosFirma();

            parametros.SignaturePolicyInfo = null;
            parametros.Certificate         = CertUtil.SelectCertificate();

            using (parametros.Signer = new Signer((X509Certificate2)parametros.Certificate))
            {
                CadesService cs = new CadesService();

                _signatureDocument = cs.CounterSign(_signatureDocument, frm.SignerInfo, parametros);
            }

            MessageBox.Show("Signature completed, you can now save the signature or extend it to CAdES-T.", "CAdES signature test",
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
Esempio n. 7
0
        private void btnGenerar_Click(object sender, EventArgs e)
        {
            XadesService        xadesService = new XadesService();
            SignatureParameters parametros   = new SignatureParameters();

            string ficheroFactura = Application.StartupPath + "\\Facturae.xml";

            // Política de firma de factura-e 3.1
            parametros.SignaturePolicyInfo = new SignaturePolicyInfo();
            parametros.SignaturePolicyInfo.PolicyIdentifier = "http://www.facturae.es/politica_de_firma_formato_facturae/politica_de_firma_formato_facturae_v3_1.pdf";
            parametros.SignaturePolicyInfo.PolicyHash       = "Ohixl6upD6av8N7pEvDABhEL6hM=";
            parametros.SignaturePackaging = SignaturePackaging.ENVELOPED;
            parametros.InputMimeType      = "text/xml";
            parametros.SignerRole         = new SignerRole();
            parametros.SignerRole.ClaimedRoles.Add("emisor");

            using (parametros.Signer = new Signer(FirmaXadesNet.Utils.CertUtil.SelectCertificate()))
            {
                using (FileStream fs = new FileStream(ficheroFactura, FileMode.Open))
                {
                    var docFirmado = xadesService.Sign(fs, parametros);

                    if (saveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    {
                        docFirmado.Save(saveFileDialog1.FileName);
                        MessageBox.Show("Fichero guardado correctamente.");
                    }
                }
            }
        }
        public static String Firmar(Documento doc, String p12, String password)
        {
            XadesService        xadesService = new XadesService( );
            SignatureParameters parametros   = new SignatureParameters( );

            // Política de firma de factura-e 3.1
            parametros.SignaturePolicyInfo = new SignaturePolicyInfo( );
            parametros.SignaturePolicyInfo.PolicyIdentifier = "https://tribunet.hacienda.go.cr/docs/esquemas/2016/v4/Resolucion%20Comprobantes%20Electronicos%20%20DGT-R-48-2016.pdf";
            parametros.SignaturePolicyInfo.PolicyHash       = "V8lVVNGDCPen6VELRD1Ja8HARFk=";
            parametros.SignaturePackaging  = SignaturePackaging.ENVELOPED;
            parametros.DataFormat          = new DataFormat( );
            parametros.DataFormat.MimeType = "text/xml";
            parametros.SignerRole          = new SignerRole( );
            parametros.SignerRole.ClaimedRoles.Add("emisor");
            parametros.Signer = new Signer(new X509Certificate2(p12, password));


            Stream stream = new MemoryStream( );

            doc.OptenerXML_Nofirmado( ).Save(stream);
            // Rewind the stream ready to read from it elsewhere
            stream.Position = 0;

            var docFirmado = xadesService.Sign(stream, parametros);

            byte[] AsBytes = docFirmado.GetDocumentBytes( );
            return(Convert.ToBase64String(AsBytes).Replace("\n", ""));
        }
Esempio n. 9
0
        private void btnFirmarHuella_Click(object sender, EventArgs e)
        {
            if (!rbInternnallyDetached.Checked)
            {
                MessageBox.Show("Por favor, seleccione el tipo de firma internally detached.");
                return;
            }

            if (string.IsNullOrEmpty(txtFichero.Text))
            {
                MessageBox.Show("Debe seleccionar un fichero para firmar.");
                return;
            }

            XadesService xadesService = new XadesService();

            SignatureParameters parametros = ObtenerParametrosFirma();

            parametros.SignaturePackaging     = SignaturePackaging.HASH_INTERNALLY_DETACHED;
            parametros.DataFormat             = new DataFormat();
            parametros.DataFormat.MimeType    = "hash/sha256";
            parametros.DataFormat.Description = "Hash value encoded in binary format";

            using (FileStream fs = new FileStream(txtFichero.Text, FileMode.Open))
            {
                using (parametros.Signer = new Signer(CertUtil.SelectCertificate()))
                {
                    _signatureDocument = xadesService.Sign(fs, parametros);
                }
            }

            MessageBox.Show("Firma completada, ahora puede Guardar la firma o ampliarla a Xades-T.", "Test firma XADES",
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
Esempio n. 10
0
        /*
         * /// <exception cref="System.IO.IOException"></exception>
         * public override Document ExtendDocument(Document document, Document originalDocument
         *  , SignatureParameters parameters)
         * {
         *  CAdESSignatureExtension extension = GetExtensionProfile(parameters);
         *  if (extension != null)
         *  {
         *      return extension.ExtendSignatures(document, originalDocument, parameters);
         *  }
         *  else
         *  {
         *      //LOG.Info("No extension for " + parameters.SignatureFormat);
         *  }
         *  return document;
         * }
         */

        private CmsSignedDataGenerator CreateCMSSignedDataGenerator(ISignatureFactory factory,
                                                                    SignatureParameters parameters, CAdESProfileBES cadesProfile,
                                                                    bool includeUnsignedAttributes, CmsSignedData originalSignedData
                                                                    )
        {
            var signedAttrGen = new DefaultSignedAttributeTableGenerator(
                new AttributeTable(cadesProfile.GetSignedAttributes(parameters)));

            SimpleAttributeTableGenerator unsignedAttrGen = null;

            if (includeUnsignedAttributes)
            {
                var attributes = cadesProfile.GetUnsignedAttributes(parameters);
                if (attributes.Count != 0)
                {
                    unsignedAttrGen = new SimpleAttributeTableGenerator(new AttributeTable(attributes));
                }
            }

            SignerInfoGeneratorBuilder sigInfoGeneratorBuilder = new SignerInfoGeneratorBuilder();

            sigInfoGeneratorBuilder.WithSignedAttributeGenerator(signedAttrGen);
            if (unsignedAttrGen != null)
            {
                sigInfoGeneratorBuilder.WithUnsignedAttributeGenerator(unsignedAttrGen);
            }

            CmsSignedDataGenerator generator = new CmsSignedDataGenerator();

            generator.AddSignerInfoGenerator(sigInfoGeneratorBuilder.Build(factory, parameters.SigningCertificate));

            if (originalSignedData != null)
            {
                generator.AddSigners(originalSignedData.GetSignerInfos());
            }

            var certs = new List <X509Certificate>();

            certs.Add(parameters.SigningCertificate);
            if (parameters.CertificateChain != null)
            {
                foreach (X509Certificate cert in parameters.CertificateChain)
                {
                    if (!cert.SubjectDN.Equals(parameters.SigningCertificate.SubjectDN))
                    {
                        certs.Add(cert);
                    }
                }
            }
            IX509Store certStore = X509StoreFactory.Create("Certificate/Collection",
                                                           new X509CollectionStoreParameters(certs));

            generator.AddCertificates(certStore);
            if (originalSignedData != null)
            {
                generator.AddCertificates(originalSignedData.GetCertificates("Collection"));
            }

            return(generator);
        }
Esempio n. 11
0
        private void btnFirmar_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtFichero.Text))
            {
                MessageBox.Show("Debe seleccionar un fichero para firmar.");
                return;
            }

            CadesService        cs         = new CadesService();
            SignatureParameters parametros = ObtenerParametrosFirma();

            parametros.Certificate = CertUtil.SelectCertificate();
            parametros.MimeType    = MimeTypeInfo.GetMimeType(txtFichero.Text);

            if (rbAttachedImplicit.Checked)
            {
                parametros.SignaturePackaging = SignaturePackaging.ATTACHED_IMPLICIT;
            }
            else
            {
                parametros.SignaturePackaging = SignaturePackaging.DETACHED_EXPLICIT;
            }

            using (parametros.Signer = new Signer((X509Certificate2)parametros.Certificate))
            {
                using (FileStream fs = new FileStream(txtFichero.Text, FileMode.Open))
                {
                    _signatureDocument = cs.Sign(fs, parametros);
                }
            }

            MessageBox.Show("Signature completed, you can now save the signature or extend it to CAdES-T.", "CAdES signature test",
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
Esempio n. 12
0
        public async Task <string> RunGetFacturaeSignedActivity([ActivityTrigger] string facturae)
        {
            var certificate = await keyvaultService.GetCertificateAsync(configuration["AppSettings:KeyVault:Certificate:Name"]);

            var signedDocument             = new MemoryStream();
            SignatureParameters parameters = new SignatureParameters
            {
                // Política de firma de factura-e 3.1
                SignaturePolicyInfo = new SignaturePolicyInfo
                {
                    PolicyIdentifier = "http://www.facturae.es/politica_de_firma_formato_facturae/politica_de_firma_formato_facturae_v3_1.pdf",
                    PolicyHash       = "Ohixl6upD6av8N7pEvDABhEL6hM="
                },
                SignaturePackaging = SignaturePackaging.ENVELOPED,
                DataFormat         = new DataFormat
                {
                    MimeType = "text/xml"
                },
                SignerRole = new SignerRole()
            };

            parameters.SignerRole.ClaimedRoles.Add("emisor");

            using (parameters.Signer = new Signer(certificate))
            {
                var xmlDocument = new XmlDocument();
                xmlDocument.LoadXml(facturae);
                var signed = xadesService.Sign(xmlDocument, parameters);
                signed.Save(signedDocument);
            }

            return(System.Convert.ToBase64String(signedDocument.ToArray()));
        }
        private void PrepareSignature(SignatureDocument sigDocument, SignatureParameters parameters)
        {
            sigDocument.XadesSignature.SignedInfo.SignatureMethod = parameters.SignatureMethod.URI;

            AddCertificateInfo(sigDocument, parameters);
            AddXadesInfo(sigDocument, parameters);

            foreach (Reference reference in sigDocument.XadesSignature.SignedInfo.References)
            {
                reference.DigestMethod = parameters.DigestMethod.URI;
            }

            if (parameters.SignatureDestination != null)
            {
                SetSignatureDestination(sigDocument, parameters.SignatureDestination);
            }

            if (parameters.XPathTransformations.Count > 0)
            {
                foreach (var xPathTrans in parameters.XPathTransformations)
                {
                    AddXPathTransform(sigDocument, xPathTrans.Namespaces, xPathTrans.XPathExpression);
                }
            }
        }
Esempio n. 14
0
		private Attribute MakeSigningCertificateAttribute(SignatureParameters parameters)
		{
			try
			{
				byte[] certHash = DigestUtilities.CalculateDigest
                    (parameters.DigestAlgorithm.GetName(),
                    parameters.SigningCertificate.GetEncoded());
                    
				if (parameters.DigestAlgorithm == DigestAlgorithm.SHA1)
				{
					SigningCertificate sc = new SigningCertificate(new EssCertID(certHash));
					return new Attribute(PkcsObjectIdentifiers.IdAASigningCertificate, new DerSet(sc
						));
				}
				else
				{
					EssCertIDv2 essCert = new EssCertIDv2(new AlgorithmIdentifier(parameters.DigestAlgorithm
						.GetOid()), certHash);
					SigningCertificateV2 scv2 = new SigningCertificateV2(new EssCertIDv2[] { essCert }
						);
					return new Attribute(PkcsObjectIdentifiers.IdAASigningCertificateV2, new DerSet
						(scv2));
				}
			}
			catch (NoSuchAlgorithmException e)
			{
				throw new RuntimeException(e);
			}
			catch (CertificateException e)
			{
				throw new RuntimeException(e);
			}
		}
Esempio n. 15
0
        private void AddSignedSignatureProperties(SignedSignatureProperties signedSignatureProperties,
                                                  SignedDataObjectProperties signedDataObjectProperties,
                                                  UnsignedSignatureProperties unsignedSignatureProperties,
                                                  SignatureParameters parameters
                                                  )
        {
            XmlDocument xmlDocument;
            Cert        cert;

            SystemX509.X509Certificate2 x509Cert;

            x509Cert = DotNetUtilities.ToX509Certificate2(parameters.SigningCertificate);

            xmlDocument = new XmlDocument();

            cert = new Cert();
            cert.IssuerSerial.X509IssuerName       = x509Cert.IssuerName.Name;
            cert.IssuerSerial.X509SerialNumber     = x509Cert.SerialNumber;
            cert.CertDigest.DigestMethod.Algorithm = SignedXml.XmlDsigSHA1Url;
            cert.CertDigest.DigestValue            = x509Cert.GetCertHash();
            signedSignatureProperties.SigningCertificate.CertCollection.Add(cert);

            signedSignatureProperties.SigningTime = parameters.SigningDate;

            signedSignatureProperties.SignaturePolicyIdentifier.SignaturePolicyImplied = true;

            DataObjectFormat newDataObjectFormat = new DataObjectFormat();

            //TODO jbonilla - Replace Description with text parameter
            newDataObjectFormat.Description = "Generado con 'intisign'";
            newDataObjectFormat.MimeType    = "text/xml";
            newDataObjectFormat.ObjectReferenceAttribute = "#xml_ref_id";
            signedDataObjectProperties.DataObjectFormatCollection.Add(newDataObjectFormat);
        }
Esempio n. 16
0
        /// <exception cref="System.IO.IOException"></exception>
        public virtual Document ExtendSignature(object signatureId, Document document, Document
                                                originalData, SignatureParameters parameters)
        {
            if (this.tspSource == null)
            {
                throw new ConfigurationException(ConfigurationException.MSG.CONFIGURE_TSP_SERVER);
            }

            XmlDocument    envelopedSignatureXmlDocument;
            XmlDocument    xadesDocument;
            XmlElement     signature;
            XadesSignedXml xadesSignedXml;

            xadesDocument = XmlUtils.ToXmlDocument(document);
            xadesDocument.PreserveWhitespace = true;
            xadesDocument.Load(document.OpenStream());

            xadesSignedXml = new XadesSignedXml(xadesDocument.DocumentElement); //Needed if it is a enveloped signature document

            signature = xadesSignedXml.GetIdElement(xadesDocument, (string)signatureId);

            xadesSignedXml.LoadXml(signature);

            ExtendSignatureTag(xadesSignedXml);

            envelopedSignatureXmlDocument = XmlUtils.ToXmlDocument(originalData);
            return(XmlUtils.ToDocument(envelopedSignatureXmlDocument, xadesSignedXml));
        }
Esempio n. 17
0
        /// <summary>
        /// Method that performs the signing process
        /// </summary>
        /// <param name="input"></param>
        /// <param name="parameters"></param>
        /// <param name="signedData"></param>
        /// <returns></returns>
        private SignatureDocument ComputeSignature(CmsProcessableByteArray content, SignatureParameters parameters, CmsSignedData signedData)
        {
            byte[] toBeSigned = ToBeSigned(content, parameters, signedData, false);
            byte[] signature  = parameters.Signer.SignData(toBeSigned, parameters.DigestMethod);

            PreComputedSigner            preComputedSigner = new PreComputedSigner(signature);
            CustomCMSSignedDataGenerator generator         = CreateSignedGenerator(preComputedSigner, parameters, signedData);
            CmsSignedData newSignedData = null;

            if (parameters.SignaturePackaging == SignaturePackaging.ATTACHED_IMPLICIT && parameters.PreCalculatedDigest == null)
            {
                newSignedData = generator.Generate(content, true);
            }
            else
            {
                if (parameters.PreCalculatedDigest != null)
                {
                    generator.PreCalculatedDigest = parameters.PreCalculatedDigest;

                    newSignedData = generator.Generate(null, false);
                }
                else if (content != null)
                {
                    newSignedData = generator.Generate(content, false);
                }
                else
                {
                    generator.PreCalculatedDigest = GetDigestValue(signedData.GetSignerInfos(), parameters.DigestMethod);

                    newSignedData = generator.Generate(null, false);
                }
            }

            return(new SignatureDocument(new CmsSignedData(newSignedData.GetEncoded())));
        }
Esempio n. 18
0
        private Attribute MakeSigningCertificateAttribute(SignatureParameters parameters)
        {
            try
            {
                byte[] certHash = DigestUtilities.CalculateDigest
                                      (parameters.DigestAlgorithm.GetName(),
                                      parameters.SigningCertificate.GetEncoded());

                if (parameters.DigestAlgorithm == DigestAlgorithm.SHA1)
                {
                    SigningCertificate sc = new SigningCertificate(new EssCertID(certHash));
                    return(new Attribute(PkcsObjectIdentifiers.IdAASigningCertificate, new DerSet(sc
                                                                                                  )));
                }
                else
                {
                    EssCertIDv2 essCert = new EssCertIDv2(new AlgorithmIdentifier(parameters.DigestAlgorithm
                                                                                  .GetOid()), certHash);
                    SigningCertificateV2 scv2 = new SigningCertificateV2(new EssCertIDv2[] { essCert }
                                                                         );
                    return(new Attribute(PkcsObjectIdentifiers.IdAASigningCertificateV2, new DerSet
                                             (scv2)));
                }
            }
            catch (NoSuchAlgorithmException e)
            {
                throw new RuntimeException(e);
            }
            catch (CertificateException e)
            {
                throw new RuntimeException(e);
            }
        }
Esempio n. 19
0
        private void Encode(SignatureParameters param)
        {
            NtruSign         ntru = new NtruSign(param);
            SignatureKeyPair kp   = ntru.generateKeyPair();

            // encode to byte[] and reconstruct
            byte[]           pub  = kp.pub.getEncoded();
            byte[]           priv = kp.priv.getEncoded();
            SignatureKeyPair kp2  = new SignatureKeyPair(new SignaturePrivateKey(priv), new SignaturePublicKey(pub));

            Assert.Equals(kp.pub, kp2.pub);
            Assert.Equals(kp.priv, kp2.priv);

            // encode to OutputStream and reconstruct
            MemoryStream bos1 = new MemoryStream();
            MemoryStream bos2 = new MemoryStream();

            kp.priv.writeTo(bos1);
            kp.pub.writeTo(bos2);
            MemoryStream     bis1 = new MemoryStream(bos1.ToArray());
            MemoryStream     bis2 = new MemoryStream(bos2.ToArray());
            SignatureKeyPair kp3  = new SignatureKeyPair(new SignaturePrivateKey(bis1), new SignaturePublicKey(bis2));

            Assert.Equals(kp.pub, kp3.pub);
            Assert.Equals(kp.priv, kp3.priv);
            // Assert.assertNull(kp3.priv.getBasis(0).h); ToDo: why?
        }
Esempio n. 20
0
        /// <summary>The ID of xades:SignedProperties is contained in the signed content of the xades Signature.
        /// 	</summary>
        /// <remarks>
        /// The ID of xades:SignedProperties is contained in the signed content of the xades Signature. We must create this
        /// ID in a deterministic way. The signingDate and signingCertificate are mandatory in the more basic level of
        /// signature, we use them as "seed" for generating the ID.
        /// </remarks>
        /// <param name="params"></param>
        /// <returns></returns>
        internal virtual string ComputeDeterministicId(SignatureParameters parameters)
        {
            try
            {
                IDigest digest = DigestUtilities.GetDigest("MD5");

                byte[] block;
                block = Encoding.ASCII.GetBytes(parameters.SigningDate.ToString());
                digest.BlockUpdate(block, 0, block.Length);
                block = parameters.SigningCertificate.GetEncoded();
                digest.BlockUpdate(block, 0, block.Length);

                string md5id = "id" + Hex.ToHexString(DigestUtilities.DoFinal(digest));
                return md5id;
            }
            catch (NoSuchAlgorithmException ex)
            {
                LOG.Error(ex.Message);
                throw new Exception("MD5 Algorithm not found !");
            }
            catch (CertificateEncodingException)
            {
                throw new Exception("Certificate encoding exception");
            }
        }
Esempio n. 21
0
        /// <summary><inheritDoc></inheritDoc></summary>
        /// <exception cref="System.IO.IOException"></exception>
        protected override Document SignDocumentInternal(Document document, SignatureParameters parameters,
                                                         DigestSigner signer)
        {
            if (parameters.SignaturePackaging != SignaturePackaging.ENVELOPING &&
                parameters.SignaturePackaging != SignaturePackaging.DETACHED)
            {
                throw new ArgumentException("Unsupported signature packaging " + parameters.SignaturePackaging);
            }

            ExternalDigestSigner   factory   = new ExternalDigestSigner(signer, parameters);
            CmsSignedDataGenerator generator = CreateCMSSignedDataGenerator(
                factory, parameters, GetSigningProfile(parameters), true, null);

            byte[]                  toBeSigned     = Streams.ReadAll(document.OpenStream());
            var                     content        = new CmsProcessableByteArray(toBeSigned);
            CmsSignedData           data           = generator.Generate(content, parameters.SignaturePackaging != SignaturePackaging.DETACHED);
            Document                signedDocument = new CMSSignedDocument(data);
            CAdESSignatureExtension extension      = GetExtensionProfile(parameters);

            if (extension != null)
            {
                signedDocument = extension.ExtendSignatures(
                    new CMSSignedDocument(data), document, parameters);
            }
            return(signedDocument);
        }
Esempio n. 22
0
        string SignDocument(X509Certificate2 signCertificate, System.IO.Stream inputStream, SignatureProductionPlace signatureProductionPlace, string timeStampUrl = "https://freetsa.org/tsr", SignatureFormat format = SignatureFormat.XAdES_T)
        {
            FirmaXadesNet.XadesService svc = new FirmaXadesNet.XadesService();

            var parameters = new SignatureParameters()
            {
                SignatureMethod          = SignatureMethod.RSAwithSHA256,
                SigningDate              = DateTime.Now,
                SignaturePackaging       = SignaturePackaging.ENVELOPED,
                InputMimeType            = "text/xml",
                SignatureProductionPlace = signatureProductionPlace
            };

            parameters.SignatureCommitments.Add(new SignatureCommitment(SignatureCommitmentType.ProofOfOrigin));

            using (parameters.Signer = new Signer(signCertificate))
            {
                var signedDocument = svc.Sign(inputStream, parameters);
                signedDocument.Document.PreserveWhitespace = true;
                UpgradeParameters xadesTparameters = new UpgradeParameters()
                {
                    TimeStampClient = new TimeStampClient(timeStampUrl)
                };
                if (format == SignatureFormat.XAdES_XL)
                {
                    xadesTparameters.OCSPServers.Add(new OcspServer("http://srvdc06.crossroad.ltd/ocsp"));
                }
                XadesUpgraderService upgrader = new XadesUpgraderService();
                upgrader.Upgrade(signedDocument, format, xadesTparameters);

                return(signedDocument.Document.OuterXml);
            }
        }
        public SignatureDocument Sign(XmlDocument input, SignatureParameters parameters)
        {
            if (parameters.Signer == null)
            {
                throw new Exception("Es necesario un certificado válido para la firma");
            }

            if (input == null && string.IsNullOrEmpty(parameters.ExternalContentUri))
            {
                throw new Exception("No se ha especificado ningún contenido a firmar");
            }

            SignatureDocument signatureDocument = new SignatureDocument();

            switch (parameters.SignaturePackaging)
            {
            case SignaturePackaging.ENVELOPED:
                SetContentEnveloped(signatureDocument, input);
                break;

            case SignaturePackaging.ENVELOPING:
                SetContentEveloping(signatureDocument, input);
                break;
            }

            SetSignatureId(signatureDocument.XadesSignature);

            PrepareSignature(signatureDocument, parameters);

            ComputeSignature(signatureDocument);

            signatureDocument.UpdateDocument();

            return(signatureDocument);
        }
Esempio n. 24
0
        static SignatureInstrumentParameters Create(
            TestContext ctx, InstrumentationCategory category, SignatureInstrumentType type,
            SignatureAndHashAlgorithm algorithm, CipherSuiteCode cipher)
        {
            var parameters = CreateParameters(category, type, algorithm.Hash, algorithm.Signature, cipher);

            parameters.ClientCertificate        = ResourceManager.MonkeyCertificate;
            parameters.RequireClientCertificate = true;

            var signatureParameters = new SignatureParameters();

            signatureParameters.Add(algorithm);

            switch (type)
            {
            case SignatureInstrumentType.ClientSignatureAlgorithmAndCipher:
                parameters.ClientSignatureParameters = signatureParameters;
                parameters.ClientCiphers             = new CipherSuiteCode[] { cipher };
                break;

            case SignatureInstrumentType.ServerSignatureAlgorithmAndCipher:
                parameters.ServerSignatureAlgorithm = algorithm;
                parameters.ServerCiphers            = new CipherSuiteCode[] { cipher };
                break;

            default:
                ctx.AssertFail("Unsupported signature instrument: '{0}'.", type);
                break;
            }

            return(parameters);
        }
Esempio n. 25
0
        /// <summary>
        /// Método para crear el atributo que contiene la información sobre la acción del firmante sobre el documento firmado
        /// </summary>
        /// <param name="parameters"></param>
        /// <returns></returns>
        private IEnumerable <BcCms.Attribute> MakeCommitmentTypeIndicationAttributes(SignatureParameters parameters)
        {
            List <Asn1Encodable> commitments = new List <Asn1Encodable>();

            foreach (var commitmentType in parameters.SignatureCommitments)
            {
                List <Asn1Encodable> qualifiers = new List <Asn1Encodable>();

                foreach (var qualifier in commitmentType.CommitmentTypeQualifiers)
                {
                    qualifiers.Add(new DerObjectIdentifier(qualifier));
                }

                commitments.Add(new CommitmentTypeIndication(commitmentType.CommitmentType.Oid, new DerSequence(qualifiers.ToArray())));
            }

            List <BcCms.Attribute> attributes = new List <BcCms.Attribute>();

            foreach (var commitmentType in commitments)
            {
                attributes.Add(new BcCms.Attribute(PkcsObjectIdentifiers.IdAAEtsCommitmentType, new DerSet(commitmentType)));
            }

            return(attributes);
        }
Esempio n. 26
0
        private void IsValid()
        {
            // test valid key pairs
            NtruSign         ntru = null;
            SignatureKeyPair kp   = null;

            SignatureParameters[] paramSets = new SignatureParameters[] { SignatureParameters.TEST157, SignatureParameters.TEST157_PROD };
            foreach (SignatureParameters param in paramSets)
            {
                ntru = new NtruSign(param);
                kp   = ntru.generateKeyPair();
                Assert.True(kp.isValid());
            }

            // test an invalid key pair
            int q = kp.pub.q;

            kp.pub.h.Multiply(101);   // make h invalid
            kp.pub.h.ModPositive(q);
            Assert.False(kp.isValid());
            int inv101 = IntEuclidean.Calculate(101, q).X;

            kp.pub.h.Multiply(inv101);   // restore h
            kp.pub.h.ModPositive(q);
            IntegerPolynomial f = kp.priv.getBasis(0).f.ToIntegerPolynomial();

            f.Multiply(3);   // make f invalid
            kp.priv.getBasis(0).f = f;
            Assert.False(kp.isValid());
        }
Esempio n. 27
0
        private void btnFirmarHuella_Click(object sender, EventArgs e)
        {
            if (!rbInternnallyDetached.Checked)
            {
                MessageBox.Show("Please select the type of signature internally detached.");
                return;
            }

            if (string.IsNullOrEmpty(txtFichero.Text))
            {
                MessageBox.Show("You must select a file to sign.");
                return;
            }

            XadesService xadesService = new XadesService();

            SignatureParameters parametros = ObtenerParametrosFirma();

            parametros.SignaturePackaging = SignaturePackaging.INTERNALLY_DETACHED;
            parametros.InputMimeType      = "hash/sha256";

            using (FileStream fs = new FileStream(txtFichero.Text, FileMode.Open))
            {
                using (parametros.Signer = new Signer(SelectCertificate()))
                {
                    _signatureDocument = xadesService.Sign(fs, parametros);
                }
            }

            MessageBox.Show("Signature completed, you can now Save the signature or expand it to Xades-T or Xades-XL.", "Test firma XADES",
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
Esempio n. 28
0
        public void RunInternallyDetachedSignature()
        {
            FirmaXadesNet.XadesService xadesService = new XadesService();
            SignatureParameters        parametros   = new SignatureParameters();

            string ficheroXml = Path.Combine(rootDirectory, @"xsdBOE-A-2011-13169_ex_XAdES_Internally_detached.xml");

            XmlDocument documento = new XmlDocument();

            documento.Load(ficheroXml);

            parametros.SignatureDestination = new SignatureXPathExpression();
            parametros.SignatureDestination.Namespaces.Add("enidoc", "http://administracionelectronica.gob.es/ENI/XSD/v1.0/documento-e");
            parametros.SignatureDestination.Namespaces.Add("enidocmeta", "http://administracionelectronica.gob.es/ENI/XSD/v1.0/documento-e/metadatos");
            parametros.SignatureDestination.Namespaces.Add("enids", "http://administracionelectronica.gob.es/ENI/XSD/v1.0/firma");
            parametros.SignatureDestination.Namespaces.Add("enifile", "http://administracionelectronica.gob.es/ENI/XSD/v1.0/documento-e/contenido");
            parametros.SignatureDestination.XPathExpression = "enidoc:documento/enids:firmas/enids:firma/enids:ContenidoFirma/enids:FirmaConCertificado";
            parametros.SignaturePackaging = SignaturePackaging.INTERNALLY_DETACHED;
            parametros.ElementIdToSign    = "CONTENT-12ef114d-ac6c-4da3-8caf-50379ed13698";
            parametros.InputMimeType      = "text/xml";

            FirmaXadesNet.Signature.SignatureDocument documentoFirma;

            using (parametros.Signer = new Signer(_signCertificate))
            {
                using (FileStream fs = new FileStream(ficheroXml, FileMode.Open))
                {
                    documentoFirma = xadesService.Sign(fs, parametros);
                }
            }

            ValidateDocument(documentoFirma.Document.OuterXml);
        }
Esempio n. 29
0
        /// <summary>
        /// Firma un documento XML
        /// </summary>
        /// <param name="xml">docuemento XML</param>
        /// <param name="data_p12">llave criptografica del usuario</param>
        /// <param name="clave">clave de la llave criptografica</param>
        /// <returns></returns>
        public static string getXMLFirmadoWeb(string xml, byte[] data_p12, string clave)
        {
            XadesService        xadesService = new XadesService();
            SignatureParameters parametros   = new SignatureParameters();

            // Política de firma de factura-e 3.1
            parametros.SignaturePolicyInfo = new SignaturePolicyInfo();
            parametros.SignaturePolicyInfo.PolicyIdentifier = "https://tribunet.hacienda.go.cr/docs/esquemas/2016/v4.2/ResolucionComprobantesElectronicosDGT-R-48-2016_4.2.pdf";
            parametros.SignaturePolicyInfo.PolicyHash       = "Ohixl6upD6av8N7pEvDABhEL6hM=";
            parametros.SignaturePackaging  = SignaturePackaging.ENVELOPED;
            parametros.DataFormat          = new DataFormat();
            parametros.DataFormat.MimeType = "text/xml";
            parametros.SignerRole          = new SignerRole();
            parametros.SignerRole.ClaimedRoles.Add("emisor");

            //selecciona el certificado del archivop12
            var selectedCertificate = GetSelectedCertificate(data_p12, clave);

            using (parametros.Signer = new Signer(selectedCertificate))
            {
                // convert string to stream
                byte[] byteArray = Encoding.UTF8.GetBytes(xml);
                //byte[] byteArray = Encoding.ASCII.GetBytes(contents);
                MemoryStream stream = new MemoryStream(byteArray);

                var docFirmado = xadesService.Sign(stream, parametros);
                return(docFirmado.Document.InnerXml);
            }
        }
Esempio n. 30
0
        private static SignatureDocument Firmar(XDocument docXML, String p12, String password)
        {
            XadesService        xadesService = new XadesService( );
            SignatureParameters parametros   = new SignatureParameters( );

            // Política de firma de factura-e 3.1
            parametros.SignaturePolicyInfo = new SignaturePolicyInfo( );
            parametros.SignaturePolicyInfo.PolicyIdentifier = "https://www.hacienda.go.cr/ATV/ComprobanteElectronico/docs/esquemas/2016/v4/Resolucion%20Comprobantes%20Electronicos%20%20DGT-R-48-2016.pdf";
            parametros.SignaturePolicyInfo.PolicyHash       = "V8lVVNGDCPen6VELRD1Ja8HARFk=";
            parametros.SignaturePackaging  = SignaturePackaging.ENVELOPED;
            parametros.DataFormat          = new DataFormat( );
            parametros.DataFormat.MimeType = "text/xml";
            parametros.SignerRole          = new SignerRole( );
            parametros.SignerRole.ClaimedRoles.Add("emisor");
            parametros.Signer = new Signer(new X509Certificate2(p12, password));


            Stream stream = new MemoryStream( );

            docXML.Save(stream);
            // Rewind the stream ready to read from it elsewhere
            stream.Position = 0;

            return(xadesService.Sign(stream, parametros));
        }
Esempio n. 31
0
        /// <param name="signedData"></param>
        /// <returns></returns>
        public virtual CmsSignedData ExtendCMSSignedData(CmsSignedData signedData, Document
                                                         originalData, SignatureParameters parameters)
        {
            SignerInformationStore   signerStore = signedData.GetSignerInfos();
            List <SignerInformation> siArray     = new List <SignerInformation>();
            //Iterator<SignerInformation> infos = signerStore.GetSigners().Iterator();
            IEnumerator infos = signerStore.GetSigners().GetEnumerator();

            while (infos.MoveNext())
            {
                SignerInformation si = (SignerInformation)infos.Current;
                try
                {
                    siArray.Add(ExtendCMSSignature(signedData, si, parameters, originalData));
                }
                catch (IOException)
                {
                    //LOG.Error("Exception when extending signature");
                    siArray.Add(si);
                }
            }
            SignerInformationStore newSignerStore = new SignerInformationStore(siArray);

            return(CmsSignedData.ReplaceSigners(signedData, newSignerStore));
        }
Esempio n. 32
0
 private Attribute MakeSignerAttrAttribute(SignatureParameters parameters)
 {
     DerOctetString[] roles = new DerOctetString[1];
     roles[0] = new DerOctetString(Sharpen.Runtime.GetBytesForString(parameters.ClaimedSignerRole));
     return(new Attribute(PkcsObjectIdentifiers.IdAAEtsSignerAttr, new DerSet(new SignerAttribute
                                                                                  (new DerSequence(roles)))));
 }
Esempio n. 33
0
        /// <summary>
        /// Método para crear el atributo que contiene la información sobre la politica de firma
        /// </summary>
        /// <param name="parameters"></param>
        /// <returns></returns>
        private BcCms.Attribute MakeSignaturePolicyAttribute(SignatureParameters parameters)
        {
            SignaturePolicyIdentifier sigPolicy = new SignaturePolicyIdentifier(new SignaturePolicyId(new DerObjectIdentifier
                                                                                                          (parameters.SignaturePolicyInfo.PolicyIdentifier), new OtherHashAlgAndValue(new AlgorithmIdentifier(parameters.SignaturePolicyInfo.PolicyDigestAlgorithm.Oid),
                                                                                                                                                                                      new DerOctetString(System.Convert.FromBase64String(parameters.SignaturePolicyInfo.PolicyHash)))));

            return(new BcCms.Attribute(PkcsObjectIdentifiers.IdAAEtsSigPolicyID, new DerSet(sigPolicy)));
        }
Esempio n. 34
0
        private SignatureExtension GetExtensionProfile(SignatureParameters parameters)
        {
            //jbonilla
            SignatureFormat signFormat = parameters.SignatureFormat;
            if (signFormat.Equals(SignatureFormat.XAdES_BES) || signFormat.Equals(SignatureFormat
                .XAdES_EPES))
            {
                return null;
            }
            else if (signFormat.Equals(SignatureFormat.XAdES_T))
            {
                XAdESProfileT extensionT = new XAdESProfileT();
                extensionT.SetTspSource(TspSource);
                return extensionT;

            }
            else if (signFormat.Equals(SignatureFormat.XAdES_C))
            {
                XAdESProfileC extensionC = new XAdESProfileC();
                extensionC.SetTspSource(TspSource);
                extensionC.SetCertificateVerifier(Verifier);
                return extensionC;
            }
            else if (signFormat.Equals(SignatureFormat.XAdES_X))
            {
                XAdESProfileX extensionX = new XAdESProfileX();
                extensionX.SetTspSource(TspSource);
                extensionX.SetCertificateVerifier(Verifier);
                return extensionX;
            }
            else if (signFormat.Equals(SignatureFormat.XAdES_XL))
            {
                XAdESProfileXL extensionXL = new XAdESProfileXL();
                extensionXL.SetTspSource(TspSource);
                extensionXL.SetCertificateVerifier(Verifier);
                return extensionXL;
            }
            //                else
            //                {
            //                    if (signFormat.Equals(SignatureFormat.XAdES_A))
            //                    {
            //                        throw new NotImplementedException();
            //                        //XAdESProfileA extensionA = new XAdESProfileA();
            //                        //extensionA.SetTspSource(tspSource);
            //                        //extensionA.SetCertificateVerifier(certificateVerifier);
            //                        //return extensionA;
            //                    }
            //                }
            //            }
            //        }
            //    }
            //}
            throw new ArgumentException("Unsupported signature format " + parameters.SignatureFormat);
        }
		public SignatureAlgorithmsExtension (TlsBuffer incoming)
		{
			var length = incoming.ReadInt16 ();
			if ((length % 2) != 0)
				throw new TlsException (AlertDescription.DecodeError);

			SignatureParameters = new SignatureParameters ();

			var count = length >> 1;
			for (int i = 0; i < count; i++) {
				SignatureParameters.SignatureAndHashAlgorithms.Add (new SignatureAndHashAlgorithm (incoming));
			}
 		}
Esempio n. 36
0
		/// <exception cref="System.IO.IOException"></exception>
		protected internal override SignerInformation ExtendCMSSignature(CmsSignedData cmsSignedData
			, SignerInformation si, SignatureParameters parameters, Document originalDocument
			)
		{
			si = base.ExtendCMSSignature(cmsSignedData, si, parameters, originalDocument);
			CAdESSignature signature = new CAdESSignature(cmsSignedData, si);
			//IDictionary<DerObjectIdentifier, Attribute> unsignedAttrHash = si.UnsignedAttributes.ToDictionary();
            IDictionary unsignedAttrHash = si.UnsignedAttributes.ToDictionary();
			Attribute archiveTimeStamp = GetTimeStampAttribute(CAdESProfileA.id_aa_ets_archiveTimestampV2
				, GetSignatureTsa(), digestAlgorithm, signature.GetArchiveTimestampData(0, originalDocument
				));
			//unsignedAttrHash.Put(CAdESProfileA.id_aa_ets_archiveTimestampV2, archiveTimeStamp);
            unsignedAttrHash.Add(CAdESProfileA.id_aa_ets_archiveTimestampV2, archiveTimeStamp);
			SignerInformation newsi = SignerInformation.ReplaceUnsignedAttributes(si, new AttributeTable
				(unsignedAttrHash));
			return newsi;
		}
Esempio n. 37
0
 /// <summary>Because some information are stored in the profile, a profile is not Thread-safe.
 /// 	</summary>
 /// <remarks>
 /// Because some information are stored in the profile, a profile is not Thread-safe. The software must create one
 /// for each request.
 /// </remarks>
 /// <returns>A new instance of signatureProfile corresponding to the parameters.</returns>
 private CAdESProfileBES GetSigningProfile(SignatureParameters parameters)
 {
     //jbonilla    	
     SignatureFormat signFormat = parameters.SignatureFormat;
     if (signFormat.Equals(SignatureFormat.CAdES_BES))
     {
         return new CAdESProfileBES();
     }
     else
     {
         if (signFormat.Equals(SignatureFormat.CAdES_EPES))
         {
             return new CAdESProfileEPES();
         }
     }
     return new CAdESProfileEPES();
 }
Esempio n. 38
0
 private XAdESProfileBES GetSigningProfile(SignatureParameters parameters)
 {
     //jbonilla
     SignatureFormat signFormat = parameters.SignatureFormat;
     if (signFormat.Equals(SignatureFormat.XAdES_BES))
     {
         return new XAdESProfileBES();
     }
     //else
     //{
     //    if (signFormat.Equals(SignatureFormat.XAdES_EPES))
     //    {
     //        return new XAdESProfileEPES();
     //    }
     //}
     //TODO jbonilla EPES?
     return new XAdESProfileBES();
 }
Esempio n. 39
0
        private void AddSignedSignatureProperties(SignedSignatureProperties signedSignatureProperties,
            SignedDataObjectProperties signedDataObjectProperties,
            UnsignedSignatureProperties unsignedSignatureProperties,
            SignatureParameters parameters
            )
        {
            XmlDocument xmlDocument;
            Cert cert;
            SystemX509.X509Certificate2 x509Cert;

            x509Cert = DotNetUtilities.ToX509Certificate2(parameters.SigningCertificate);

            xmlDocument = new XmlDocument();

            cert = new Cert();
            cert.IssuerSerial.X509IssuerName = x509Cert.IssuerName.Name;
            cert.IssuerSerial.X509SerialNumber = x509Cert.SerialNumber;
            cert.CertDigest.DigestMethod.Algorithm = SignedXml.XmlDsigSHA1Url;
            cert.CertDigest.DigestValue = x509Cert.GetCertHash();
            signedSignatureProperties.SigningCertificate.CertCollection.Add(cert);

            signedSignatureProperties.SigningTime = parameters.SigningDate;

            signedSignatureProperties.SignaturePolicyIdentifier.SignaturePolicyImplied = true;

            DataObjectFormat newDataObjectFormat = new DataObjectFormat();

            //TODO jbonilla - Replace Description with text parameter
            newDataObjectFormat.Description = "Generado con 'intisign'";
            newDataObjectFormat.MimeType = "text/xml";
            newDataObjectFormat.ObjectReferenceAttribute = "#xml_ref_id";
            signedDataObjectProperties.DataObjectFormatCollection.Add(newDataObjectFormat);
        }
Esempio n. 40
0
        private void AddCertificateInfoToSignature(XadesSignedXml xadesSignedXml, SignatureParameters parameters)
        {
            var key = parameters.SigningCertificate.GetPublicKey();

            if (key is RsaKeyParameters)
            {
                RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider();
                RSAParameters RSAKeyInfo = new RSAParameters();

                //Set RSAKeyInfo to the public key values. 
                RSAKeyInfo.Modulus = ((RsaKeyParameters)key).Modulus.ToByteArray();
                RSAKeyInfo.Exponent = ((RsaKeyParameters)key).Exponent.ToByteArray();

                rsaKey.ImportParameters(RSAKeyInfo);

                xadesSignedXml.SigningKey = rsaKey;

                KeyInfo keyInfo = new KeyInfo();

                // ETSI TS 103 171 V2.1.1
                // 6.2.1 Placement of the signing certificate
                // "b) In order to facilitate path-building, generators should include in the same ds:KeyInfo/X509Data element as 
                // in note a) all certificates not available to verifiers that can be used during path building."
                //keyInfo.AddClause(new KeyInfoX509Data(this.certificate));
                {
                    KeyInfoX509Data x509Data = new KeyInfoX509Data();
                    foreach (X509Certificate cert in parameters.CertificateChain)
                    {
                        x509Data.AddCertificate(DotNetUtilities.ToX509Certificate2(cert));
                        //TODO jbonilla validar más de uno?
                        //break;
                    }
                    keyInfo.AddClause(x509Data);
                }

                keyInfo.AddClause(new RSAKeyValue(rsaKey));

                xadesSignedXml.KeyInfo = keyInfo;
            }
            else
            {
                throw new ArgumentException("Only allowed RsaKeyParameters", "key");
            }
        }
Esempio n. 41
0
        protected internal virtual Stream GetToBeSignedStream(Document document, SignatureParameters
             parameters)
        {
            XmlDocument envelopedSignatureXmlDocument;
            XadesSignedXml xadesSignedXml;

            envelopedSignatureXmlDocument = XmlUtils.ToXmlDocument(document);
            xadesSignedXml = CreateFromXmlDocument(envelopedSignatureXmlDocument);

            string uid = ComputeDeterministicId(parameters);
            string signatureId = "sigId-" + uid;
            string signedId = "xades-" + uid;

            xadesSignedXml.Signature.Id = signatureId;

            XadesObject xadesObject = new XadesObject();
            //xadesObject.Id = "XadesObject";
            xadesObject.QualifyingProperties.SignedProperties.Id = signedId;
            xadesObject.QualifyingProperties.Target = "#" + signatureId;

            this.AddSignedSignatureProperties(
                xadesObject.QualifyingProperties.SignedProperties.SignedSignatureProperties,
                xadesObject.QualifyingProperties.SignedProperties.SignedDataObjectProperties,
                xadesObject.QualifyingProperties.UnsignedProperties.UnsignedSignatureProperties,
                parameters);

            xadesSignedXml.AddXadesObject(xadesObject);

            return xadesSignedXml.PreComputeSignature();
        }
Esempio n. 42
0
 /// <exception cref="System.IO.IOException"></exception>
 public virtual EU.Europa.EC.Markt.Dss.Digest Digest(Document document, SignatureParameters
      parameters)
 {
     Stream input = ToBeSigned(document, parameters);
     byte[] data = Streams.ReadAll(input);
     byte[] digestValue = DigestUtilities.CalculateDigest(
         parameters.DigestAlgorithm.GetName(), data);
     return new EU.Europa.EC.Markt.Dss.Digest(parameters.DigestAlgorithm, digestValue);
 }
Esempio n. 43
0
 /// <exception cref="System.IO.IOException"></exception>
 public virtual Document ExtendDocument(Document document, Document originalDocument
     , SignatureParameters parameters)
 {
     throw new NotImplementedException();
     //SignatureExtension extension = GetExtensionProfile(parameters);
     //if (extension != null)
     //{
     //    return extension.ExtendSignatures(document, originalDocument, parameters);
     //}
     //else
     //{
     //    return document;
     //}
 }
Esempio n. 44
0
		private Attribute MakeSignerAttrAttribute(SignatureParameters parameters)
		{
			DerOctetString[] roles = new DerOctetString[1];
			roles[0] = new DerOctetString(Sharpen.Runtime.GetBytesForString(parameters.ClaimedSignerRole));
			return new Attribute(PkcsObjectIdentifiers.IdAAEtsSignerAttr, new DerSet(new SignerAttribute
				(new DerSequence(roles))));
		}
Esempio n. 45
0
		/// <summary>Return the table of unsigned properties.</summary>
		/// <remarks>Return the table of unsigned properties.</remarks>
		/// <param name="parameters"></param>
		/// <returns></returns>
		//public virtual IDictionary<DerObjectIdentifier, Asn1Encodable> GetUnsignedAttributes
        public virtual IDictionary GetUnsignedAttributes
			(SignatureParameters parameters)
		{
			return new Dictionary<DerObjectIdentifier, Asn1Encodable>();
		}
Esempio n. 46
0
        /// <exception cref="System.IO.IOException"></exception>
        public virtual Stream ToBeSigned(Document document, SignatureParameters parameters
            )
        {
            if (parameters.SignaturePackaging != SignaturePackaging.ENVELOPING && parameters
                .SignaturePackaging != SignaturePackaging.DETACHED)
            {
                throw new ArgumentException("Unsupported signature packaging " + parameters.SignaturePackaging);
            }
            //jbonilla - No aplica para C#
            //SignatureInterceptorProvider provider = new SignatureInterceptorProvider();
            //Security.AddProvider(provider);
            //string jsAlgorithm = parameters.GetSignatureAlgorithm().GetJavaSignatureAlgorithm
            //    (parameters.GetDigestAlgorithm());
            //PreComputedContentSigner contentSigner = new PreComputedContentSigner(jsAlgorithm
            //    );
            PreComputedSigner signer = new PreComputedSigner();
            //CmsSignedDataGenerator generator = CreateCMSSignedDataGenerator(contentSigner, digestCalculatorProvider
            //    , parameters, GetSigningProfile(parameters), false, null);
            CmsSignedDataGenerator generator = CreateCMSSignedDataGenerator
                (signer, parameters, GetSigningProfile(parameters), false, null);

            byte[] toBeSigned = Streams.ReadAll(document.OpenStream());
            CmsProcessableByteArray content = new CmsProcessableByteArray(toBeSigned);
            try
            {
                bool includeContent = true;
                if (parameters.SignaturePackaging == SignaturePackaging.DETACHED)
                {
                    includeContent = false;
                }
                CmsSignedData signed = generator.Generate(content, includeContent);

                //jbonilla - El ISigner devuelve el mismo hash sin firmar para permitir
                //la generación de la firma por un medio externo, como un token.
                /*return new ByteArrayInputStream(contentSigner.GetByteOutputStream().ToByteArray());*/
                return new MemoryStream(signer.CurrentSignature());
            }
            catch (CmsException e)
            {
                throw new IOException("CmsException", e);
            }
        }
Esempio n. 47
0
        /// <summary><inheritDoc></inheritDoc></summary>
        /// <exception cref="System.IO.IOException"></exception>
        public virtual Document SignDocument(Document document, SignatureParameters parameters
            , byte[] signatureValue)
        {
            if (parameters.SignaturePackaging != SignaturePackaging.ENVELOPING && parameters
                .SignaturePackaging != SignaturePackaging.DETACHED)
            {
                throw new ArgumentException("Unsupported signature packaging " + parameters.SignaturePackaging);
            }
            try
            {
                //jbonilla - No aplica para C#
                //string jsAlgorithm = parameters.GetSignatureAlgorithm().GetJavaSignatureAlgorithm
                //    (parameters.GetDigestAlgorithm());
                //PreComputedContentSigner cs = new PreComputedContentSigner(jsAlgorithm, signatureValue
                //    );
                PreComputedSigner s = new PreComputedSigner(signatureValue);

                //DigestCalculatorProvider digestCalculatorProvider = new BcDigestCalculatorProvider
                //    ();
                //CMSSignedDataGenerator generator = CreateCMSSignedDataGenerator(cs, digestCalculatorProvider
                //    , parameters, GetSigningProfile(parameters), true, null);
                CmsSignedDataGenerator generator = CreateCMSSignedDataGenerator(s, parameters
                    , GetSigningProfile(parameters), true, null);
                byte[] toBeSigned = Streams.ReadAll(document.OpenStream());
                CmsProcessableByteArray content = new CmsProcessableByteArray(toBeSigned);
                bool includeContent = true;
                if (parameters.SignaturePackaging == SignaturePackaging.DETACHED)
                {
                    includeContent = false;
                }
                CmsSignedData data = generator.Generate(content, includeContent);
                Document signedDocument = new CMSSignedDocument(data);
                CAdESSignatureExtension extension = GetExtensionProfile(parameters);
                if (extension != null)
                {
                    signedDocument = extension.ExtendSignatures(new CMSSignedDocument(data), document
                        , parameters);
                }
                return signedDocument;
            }
            catch (CmsException e)
            {
                throw new RuntimeException(e);
            }
        }
Esempio n. 48
0
        /// <summary>Add a signature to the already CMS signed data document.</summary>
        /// <remarks>Add a signature to the already CMS signed data document.</remarks>
        /// <param name="_signedDocument"></param>
        /// <param name="parameters"></param>
        /// <param name="signatureValue"></param>
        /// <returns></returns>
        /// <exception cref="System.IO.IOException">System.IO.IOException</exception>
        public virtual Document AddASignatureToDocument(Document _signedDocument, SignatureParameters
             parameters, byte[] signatureValue)
        {
            if (parameters.SignaturePackaging != SignaturePackaging.ENVELOPING)
            {
                throw new ArgumentException("Unsupported signature packaging " + parameters.SignaturePackaging);
            }
            try
            {
                CmsSignedData originalSignedData = null;
                using (var stream = _signedDocument.OpenStream())
                {
                    originalSignedData = new CmsSignedData(stream);
                }

                //jbonilla - No aplica para C#
                //string jsAlgorithm = parameters.GetSignatureAlgorithm().GetJavaSignatureAlgorithm
                //    (parameters.GetDigestAlgorithm());
                //PreComputedContentSigner cs = new PreComputedContentSigner(jsAlgorithm, signatureValue
                //    );
                PreComputedSigner s = new PreComputedSigner(signatureValue);
                //DigestCalculatorProvider digestCalculatorProvider = new BcDigestCalculatorProvider
                //    ();
                //CMSSignedDataGenerator generator = CreateCMSSignedDataGenerator(cs, digestCalculatorProvider
                //    , parameters, GetSigningProfile(parameters), true, originalSignedData);
                CmsSignedDataGenerator generator = CreateCMSSignedDataGenerator(s, parameters
                    , GetSigningProfile(parameters), true, originalSignedData);

                //if (originalSignedData == null || originalSignedData.SignedContent.GetContent
                //    () == null)                
                if (originalSignedData == null || originalSignedData.SignedContent == null)
                {
                    throw new RuntimeException("Cannot retrieve orignal content");
                }
                //byte[] octetString = (byte[])originalSignedData.SignedContent.GetContent();
                //CmsProcessableByteArray content = new CmsProcessableByteArray(octetString);
                CmsProcessable content = originalSignedData.SignedContent;
                CmsSignedData data = generator.Generate(content, true);
                Document signedDocument = new CMSSignedDocument(data);
                CAdESSignatureExtension extension = GetExtensionProfile(parameters);
                if (extension != null)
                {
                    signedDocument = extension.ExtendSignatures(new CMSSignedDocument(data), null, parameters);
                }
                return signedDocument;
            }
            catch (CmsException e)
            {
                throw new RuntimeException(e);
            }
        }
Esempio n. 49
0
        private CAdESSignatureExtension GetExtensionProfile(SignatureParameters parameters
            )
        {
            //jbonilla    	
            SignatureFormat signFormat = parameters.SignatureFormat;
            if (signFormat.Equals(SignatureFormat.CAdES_BES) || signFormat.Equals(SignatureFormat
                .CAdES_EPES))
            {
                return null;
            }
            else if (signFormat.Equals(SignatureFormat.CAdES_T))
            {
                CAdESProfileT extensionT = new CAdESProfileT();
                extensionT.SetSignatureTsa(TspSource);
                return extensionT;
            }
            else if (signFormat.Equals(SignatureFormat.CAdES_C))
            {
                CAdESProfileC extensionC = new CAdESProfileC();
                extensionC.SetSignatureTsa(TspSource);
                extensionC.SetCertificateVerifier(Verifier);
                return extensionC;
            }
            else if (signFormat.Equals(SignatureFormat.CAdES_X))
            {
                CAdESProfileX extensionX = new CAdESProfileX();
                extensionX.SetSignatureTsa(TspSource);
                extensionX.SetExtendedValidationType(1);
                extensionX.SetCertificateVerifier(Verifier);
                return extensionX;
            }
            else if (signFormat.Equals(SignatureFormat.CAdES_XL))
            {
                CAdESProfileXL extensionXL = new CAdESProfileXL();
                extensionXL.SetSignatureTsa(TspSource);
                extensionXL.SetExtendedValidationType(1);
                extensionXL.SetCertificateVerifier(Verifier);
                return extensionXL;
            }
            else if (signFormat.Equals(SignatureFormat.CAdES_A))
            {
                CAdESProfileA extensionA = new CAdESProfileA();
                extensionA.SetSignatureTsa(TspSource);
                extensionA.SetCertificateVerifier(Verifier);
                extensionA.SetExtendedValidationType(1);
                return extensionA;
            }

            throw new ArgumentException("Unsupported signature format " + parameters.SignatureFormat);
        }
Esempio n. 50
0
        internal virtual Document SignDocument(Document document, SignatureParameters parameters
            , byte[] signatureValue)
        {
            XmlDocument envelopedSignatureXmlDocument;
            XadesSignedXml xadesSignedXml;

            envelopedSignatureXmlDocument = XmlUtils.ToXmlDocument(document);
            xadesSignedXml = CreateFromXmlDocument(envelopedSignatureXmlDocument);

            AddCertificateInfoToSignature(xadesSignedXml, parameters);

            string uid = ComputeDeterministicId(parameters);
            string signatureId = "sigId-" + uid;
            string signedId = "xades-" + uid;
            string signatureValueId = "sigValueId-" + uid;

            xadesSignedXml.Signature.Id = signatureId;

            XadesObject xadesObject = new XadesObject();
            //xadesObject.Id = "XadesObject";
            xadesObject.QualifyingProperties.SignedProperties.Id = signedId;
            xadesObject.QualifyingProperties.Target = "#" + signatureId;

            this.AddSignedSignatureProperties(
                xadesObject.QualifyingProperties.SignedProperties.SignedSignatureProperties,
                xadesObject.QualifyingProperties.SignedProperties.SignedDataObjectProperties,
                xadesObject.QualifyingProperties.UnsignedProperties.UnsignedSignatureProperties,
                parameters);

            xadesSignedXml.AddXadesObject(xadesObject);

            xadesSignedXml.ComputeExternalSignature(signatureValue);

            xadesSignedXml.SignatureValueId = signatureValueId;

            return XmlUtils.ToDocument(envelopedSignatureXmlDocument, xadesSignedXml);
        }
Esempio n. 51
0
		private Attribute MakeSigningTimeAttribute(SignatureParameters parameters)
		{
			return new Attribute(PkcsObjectIdentifiers.Pkcs9AtSigningTime, new DerSet(new 
				BcX509.Time(parameters.SigningDate)));
		}
Esempio n. 52
0
 /// <exception cref="System.IO.IOException"></exception>
 public virtual EU.Europa.EC.Markt.Dss.Digest Digest(Document document, SignatureParameters
      parameters)
 {
     byte[] digestValue = null;
     try
     {
         digestValue = DigestUtilities.CalculateDigest
             (parameters.DigestAlgorithm.GetName(),
             Streams.ReadAll(ToBeSigned(document, parameters)));
         return new EU.Europa.EC.Markt.Dss.Digest(parameters.DigestAlgorithm, digestValue
             );
     }
     catch (NoSuchAlgorithmException e)
     {
         throw new RuntimeException(e);
     }
 }
Esempio n. 53
0
        //internal virtual IDictionary<DerObjectIdentifier, Asn1Encodable> GetSignedAttributes
		internal virtual IDictionary GetSignedAttributes
			(SignatureParameters parameters)
		{
            //IDictionary<DerObjectIdentifier, Asn1Encodable> signedAttrs = new Dictionary<DerObjectIdentifier            
            IDictionary signedAttrs = new Dictionary<DerObjectIdentifier
                , Asn1Encodable>();
			Attribute signingCertificateReference = MakeSigningCertificateAttribute(parameters
				);
			signedAttrs.Add((DerObjectIdentifier)signingCertificateReference.AttrType, 
				signingCertificateReference);
			if (!padesUsage)
			{
				signedAttrs.Add(PkcsObjectIdentifiers.Pkcs9AtSigningTime, MakeSigningTimeAttribute
					(parameters));
			}
			if (!padesUsage && parameters.ClaimedSignerRole != null)
			{
				signedAttrs.Add(PkcsObjectIdentifiers.IdAAEtsSignerAttr, MakeSignerAttrAttribute
					(parameters));
			}
			return signedAttrs;
		}
Esempio n. 54
0
 /// <exception cref="System.IO.IOException"></exception>
 public virtual Document SignDocument(Document document, SignatureParameters parameters
     , byte[] signatureValue)
 {
     XAdESProfileBES profile = GetSigningProfile(parameters);
     Document signedDoc = profile.SignDocument(document, parameters, signatureValue);
     SignatureExtension extension = GetExtensionProfile(parameters);
     if (extension != null)
     {
         if (parameters.SignaturePackaging == SignaturePackaging.ENVELOPED)
         {
             string signatureId = "sigId-" + profile.ComputeDeterministicId(parameters);
             return extension.ExtendSignature(signatureId, signedDoc, document, parameters);
         }
         else
         {
             return extension.ExtendSignatures(signedDoc, document, parameters);
         }
     }
     else
     {
         return signedDoc;
     }
 }
		static SignatureInstrumentParameters Create (
			TestContext ctx, InstrumentationCategory category, SignatureInstrumentType type,
			SignatureAndHashAlgorithm algorithm, CipherSuiteCode cipher)
		{
			var parameters = CreateParameters (category, type, algorithm.Hash, algorithm.Signature, cipher);

			parameters.ClientCertificate = ResourceManager.MonkeyCertificate;
			parameters.RequireClientCertificate = true;

			var signatureParameters = new SignatureParameters ();
			signatureParameters.Add (algorithm);

			switch (type) {
			case SignatureInstrumentType.ClientSignatureAlgorithmAndCipher:
				parameters.ClientSignatureParameters = signatureParameters;
				parameters.ClientCiphers = new CipherSuiteCode[] { cipher };
				break;

			case SignatureInstrumentType.ServerSignatureAlgorithmAndCipher:
				parameters.ServerSignatureAlgorithm = algorithm;
				parameters.ServerCiphers = new CipherSuiteCode[] { cipher };
				break;

			default:
				ctx.AssertFail ("Unsupported signature instrument: '{0}'.", type);
				break;
			}

			return parameters;
		}
		public SignatureAlgorithmsExtension (SignatureParameters parameters)
		{
			SignatureParameters = parameters;
		}
Esempio n. 57
0
 /// <exception cref="System.IO.IOException"></exception>
 public virtual Stream ToBeSigned(Document document, SignatureParameters parameters
     )
 {
     return GetSigningProfile(parameters).GetToBeSignedStream(document, parameters);
 }
Esempio n. 58
0
 /// <exception cref="System.IO.IOException"></exception>
 public virtual Document ExtendDocument(Document document, Document originalDocument
     , SignatureParameters parameters)
 {
     CAdESSignatureExtension extension = GetExtensionProfile(parameters);
     if (extension != null)
     {
         return extension.ExtendSignatures(document, originalDocument, parameters);
     }
     else
     {
         LOG.Info("No extension for " + parameters.SignatureFormat);
     }
     return document;
 }