} // End Function GetX509Field

        // http://unitstep.net/blog/2008/10/27/extracting-x509-extensions-from-a-csr-using-the-bouncy-castle-apis/
        // https://github.com/puppetlabs/jvm-ssl-utils/blob/master/src/java/com/puppetlabs/ssl_utils/ExtensionsUtils.java
        // Gets the X509 Extensions contained in a CSR (Certificate Signing Request).
        // @param certificateSigningRequest the CSR.
        // @return the X509 Extensions in the request.
        // @throws CertificateException if the extensions could not be found.
        private static Org.BouncyCastle.Asn1.X509.X509Extensions GetX509ExtensionsFromCsr(
            Org.BouncyCastle.Asn1.Pkcs.CertificationRequestInfo certificationRequestInfo
            )
        {
            // Org.BouncyCastle.Pkcs.Pkcs10CertificationRequest certificateSigningRequest
            //Org.BouncyCastle.Asn1.Pkcs.CertificationRequestInfo certificationRequestInfo = certificateSigningRequest.GetCertificationRequestInfo();

            Org.BouncyCastle.Asn1.Asn1Set attributesAsn1Set = certificationRequestInfo.Attributes;

            // The `Extension Request` attribute is contained within an ASN.1 Set,
            // usually as the first element.
            Org.BouncyCastle.Asn1.X509.X509Extensions certificateRequestExtensions = null;

            for (int i = 0; i < attributesAsn1Set.Count; ++i)
            {
                // There should be only only one attribute in the set. (that is, only
                // the `Extension Request`, but loop through to find it properly)
                Org.BouncyCastle.Asn1.Asn1Encodable derEncodable = attributesAsn1Set[i];

                if (derEncodable is Org.BouncyCastle.Asn1.X509.X509Extensions)
                {
                    certificateRequestExtensions = (Org.BouncyCastle.Asn1.X509.X509Extensions)derEncodable;
                    break;
                }
                else if (derEncodable is Org.BouncyCastle.Asn1.DerSequence)
                {
                    Org.BouncyCastle.Asn1.DerSequence sequence = (Org.BouncyCastle.Asn1.DerSequence)attributesAsn1Set[i];

                    Org.BouncyCastle.Asn1.Cms.Attribute attribute =
                        new Org.BouncyCastle.Asn1.Cms.Attribute(sequence);

                    // Check if the `Extension Request` attribute is present.
                    if (attribute.AttrType.Equals(
                            Org.BouncyCastle.Asn1.Pkcs.PkcsObjectIdentifiers.Pkcs9AtExtensionRequest)
                        )
                    {
                        Org.BouncyCastle.Asn1.Asn1Set attributeValues = attribute.AttrValues;

                        // The X509Extensions are contained as a value of the ASN.1 Set.
                        // Assume that it is the first value of the set.
                        if (attributeValues.Count >= 1)
                        {
                            certificateRequestExtensions = Org.BouncyCastle.Asn1.X509.X509Extensions.GetInstance(
                                attributeValues[0]
                                );
                            // No need to search any more.
                            break;
                        } // End if (attributeValues.Count >= 1)
                    }
                }         // End else if (derEncodable is Org.BouncyCastle.Asn1.DerSequence)
            }             // Next i

            if (null == certificateRequestExtensions)
            {
                throw new Org.BouncyCastle.Security.Certificates.CertificateException(
                          "Could not obtain X509 Extensions from the CSR");
            } // End if (null == certificateRequestExtensions)

            return(certificateRequestExtensions);
        } // End Function
        /// <summary>
        /// Get extensions
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        internal static X509Extensions GetX509Extensions(this CertificationRequestInfo info)
        {
            if (info == null)
            {
                throw new ArgumentNullException(nameof(info));
            }
            var attributesAsn1Set = info.Attributes;

            for (var i = 0; i < attributesAsn1Set.Count; ++i)
            {
                var derEncodable = attributesAsn1Set[i];
                if (derEncodable is DerSequence sequence)
                {
                    var attribute = new Org.BouncyCastle.Asn1.Cms.Attribute(sequence);
                    if (attribute.AttrType.Equals(PkcsObjectIdentifiers.Pkcs9AtExtensionRequest))
                    {
                        var attributeValues = attribute.AttrValues;
                        if (attributeValues.Count >= 1)
                        {
                            return(X509Extensions.GetInstance(attributeValues[0]));
                        }
                    }
                }
            }
            return(null);
        }
Exemple #3
0
        Org.BouncyCastle.Asn1.Cms.Attribute ToBcAttribute(CryptographicAttributeObject obj)
        {
            var encodables = obj.Values.Cast <AsnEncodedData>().Select(d => Asn1Object.FromByteArray(d.RawData)).ToArray();
            var derSet     = new DerSet(encodables);

            var attr = new Org.BouncyCastle.Asn1.Cms.Attribute(new DerObjectIdentifier(obj.Oid.Value), derSet);

            return(attr);
        }
Exemple #4
0
        //  Sign the message with the private key of the signer.
        static public byte[] SignMsg(Byte[] msg, X509Certificate2 signerCert, bool detached, bool UsaTSA, string TSAurl, string TSAuser, string TSApass)
        {
            try
            {
                SHA256Managed        hashSha256 = new SHA256Managed();
                byte[]               certHash   = hashSha256.ComputeHash(signerCert.RawData);
                EssCertIDv2          essCert1   = new EssCertIDv2(new Org.BouncyCastle.Asn1.X509.AlgorithmIdentifier("2.16.840.1.101.3.4.2.1"), certHash);
                SigningCertificateV2 scv2       = new SigningCertificateV2(new EssCertIDv2[] { essCert1 });
                Org.BouncyCastle.Asn1.Cms.Attribute CertHAttribute = new Org.BouncyCastle.Asn1.Cms.Attribute(Org.BouncyCastle.Asn1.Pkcs.PkcsObjectIdentifiers.IdAASigningCertificateV2, new DerSet(scv2));
                Asn1EncodableVector v = new Asn1EncodableVector();
                v.Add(CertHAttribute);
                Org.BouncyCastle.Asn1.Cms.AttributeTable AT = new Org.BouncyCastle.Asn1.Cms.AttributeTable(v);
                CmsSignedDataGenWithRsaCsp cms = new CmsSignedDataGenWithRsaCsp();
                var rsa = (RSACryptoServiceProvider)signerCert.PrivateKey;
                Org.BouncyCastle.X509.X509Certificate certCopy = DotNetUtilities.FromX509Certificate(signerCert);
                cms.MyAddSigner(rsa, certCopy, "1.2.840.113549.1.1.1", "2.16.840.1.101.3.4.2.1", AT, null);
                ArrayList certList = new ArrayList();
                certList.Add(certCopy);
                Org.BouncyCastle.X509.Store.X509CollectionStoreParameters PP = new Org.BouncyCastle.X509.Store.X509CollectionStoreParameters(certList);
                Org.BouncyCastle.X509.Store.IX509Store st1 = Org.BouncyCastle.X509.Store.X509StoreFactory.Create("CERTIFICATE/COLLECTION", PP);
                cms.AddCertificates(st1);
                CmsProcessableByteArray file    = new CmsProcessableByteArray(msg); //CmsProcessableFile(File);
                CmsSignedData           Firmato = cms.Generate(file, false);        //se settato a true, il secondo argomento integra l'intero file

                byte[] bb = Firmato.GetEncoded();

                if (UsaTSA)
                {
                    CmsSignedData          sd      = new CmsSignedData(bb);
                    SignerInformationStore signers = sd.GetSignerInfos();
                    byte[]            signature    = null;
                    SignerInformation signer       = null;
                    foreach (SignerInformation signer_ in signers.GetSigners())
                    {
                        signer = signer_;
                        break;
                    }

                    signature = signer.GetSignature();
                    Org.BouncyCastle.Asn1.Cms.AttributeTable at = new Org.BouncyCastle.Asn1.Cms.AttributeTable(GetTimestamp(signature, TSAurl, TSAuser, TSApass));
                    signer = SignerInformation.ReplaceUnsignedAttributes(signer, at);
                    IList signerInfos = new ArrayList();
                    signerInfos.Add(signer);
                    sd = CmsSignedData.ReplaceSigners(sd, new SignerInformationStore(signerInfos));
                    bb = sd.GetEncoded();
                }
                return(bb);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                return(null);
            }
        }
Exemple #5
0
        private byte[] TimestampAuthorityResponse(EstEIDReader estEidReader, byte[] signedPkcs)
        {
            ArrayList newSigners = new ArrayList();

            CmsSignedData sd = new CmsSignedData(signedPkcs);

            foreach (SignerInformation si in sd.GetSignerInfos().GetSigners())
            {
                // possible TSA URLs
                //string TsaServerUrl = "http://www.edelweb.fr/cgi-bin/service-tsp";
                //string TsaServerUrl = "http://dse200.ncipher.com/TSS/HttpTspServer";

                byte[] signedDigest  = si.GetSignature();
                byte[] timeStampHash = ComputeHash(estEidReader, signedDigest);

                string TsaServerUrl = stamp.Url;
                string TsaUser      = stamp.User;
                string TsaPassword  = stamp.Password;
                string error        = string.Empty;

                byte[] timeStampToken = X509Utils.GetTimestampToken(TsaServerUrl,
                                                                    TsaUser,
                                                                    TsaPassword,
                                                                    timeStampHash,
                                                                    ref error);

                if (timeStampToken == null)
                {
                    throw new Exception(Resources.TSA_ERROR + error);
                }

                Hashtable  ht     = new Hashtable();
                Asn1Object derObj = new Asn1InputStream(timeStampToken).ReadObject();
                DerSet     derSet = new DerSet(derObj);

                Org.BouncyCastle.Asn1.Cms.Attribute unsignAtt = new Org.BouncyCastle.Asn1.Cms.Attribute(
                    new DerObjectIdentifier(X509Utils.ID_TIME_STAMP_TOKEN), derSet);

                ht.Add(X509Utils.ID_TIME_STAMP_TOKEN, unsignAtt);

                Org.BouncyCastle.Asn1.Cms.AttributeTable unsignedAtts = new Org.BouncyCastle.Asn1.Cms.AttributeTable(ht);

                newSigners.Add(SignerInformation.ReplaceUnsignedAttributes(si, unsignedAtts));
            }

            SignerInformationStore newSignerInformationStore = new SignerInformationStore(newSigners);

            CmsSignedData newSd = CmsSignedData.ReplaceSigners(sd, newSignerInformationStore);

            // Encode the CMS/PKCS #7 message
            return(newSd.GetEncoded());
        }
Exemple #6
0
        public static byte[] FirmaFileBouncy(byte[] data, X509Certificate2 cert)
        {
            try
            {
                SHA256Managed        hashSha256 = new SHA256Managed();
                byte[]               certHash   = hashSha256.ComputeHash(cert.RawData);
                EssCertIDv2          essCert1   = new EssCertIDv2(new Org.BouncyCastle.Asn1.X509.AlgorithmIdentifier("2.16.840.1.101.3.4.2.1"), certHash);
                SigningCertificateV2 scv2       = new SigningCertificateV2(new EssCertIDv2[] { essCert1 });
                Org.BouncyCastle.Asn1.Cms.Attribute CertHAttribute = new Org.BouncyCastle.Asn1.Cms.Attribute(Org.BouncyCastle.Asn1.Pkcs.PkcsObjectIdentifiers.IdAASigningCertificateV2, new DerSet(scv2));
                Asn1EncodableVector v = new Asn1EncodableVector();
                v.Add(CertHAttribute);
                Org.BouncyCastle.Asn1.Cms.AttributeTable AT = new Org.BouncyCastle.Asn1.Cms.AttributeTable(v);

                CmsSignedDataGenWithRsaCsp cms = new CmsSignedDataGenWithRsaCsp();

                var rsa = (RSACryptoServiceProvider)cert.PrivateKey;
                Org.BouncyCastle.X509.X509Certificate certCopy = DotNetUtilities.FromX509Certificate(cert);
                cms.MyAddSigner(rsa, certCopy, "1.2.840.113549.1.1.1", "2.16.840.1.101.3.4.2.1", AT, null);
                ArrayList certList = new ArrayList();
                certList.Add(certCopy);
                Org.BouncyCastle.X509.Store.X509CollectionStoreParameters PP = new Org.BouncyCastle.X509.Store.X509CollectionStoreParameters(certList);
                Org.BouncyCastle.X509.Store.IX509Store st1 = Org.BouncyCastle.X509.Store.X509StoreFactory.Create("CERTIFICATE/COLLECTION", PP);
                cms.AddCertificates(st1);
                //mi ricavo il file da firmare
                CmsSignedData Firmato = cms.Generate(new CmsProcessableByteArray(data), false);

                CmsSigner cmsSigner = new CmsSigner(cert);
                cmsSigner.IncludeOption = X509IncludeOption.EndCertOnly;

                System.Security.Cryptography.Pkcs.ContentInfo contentInfo = new System.Security.Cryptography.Pkcs.ContentInfo(Firmato.GetEncoded());
                SignedCms signedCms = new SignedCms();
                signedCms.Decode(Firmato.GetEncoded());
                byte[] ret = signedCms.Encode();
                return(ret);
            }
            catch
            {
                return(null);
            }
        }
        private static void getAdditionalInfos(byte[] contents, string subFilter, out string digestAlgOid, out byte[] messageDigest, out bool isEpes)
        {
            Org.BouncyCastle.Cms.CmsSignedData signedData = new Org.BouncyCastle.Cms.CmsSignedData(
                Org.BouncyCastle.Asn1.Cms.ContentInfo.GetInstance((
                                                                      new Org.BouncyCastle.Asn1.Asn1InputStream(contents)).ReadObject()));

            Org.BouncyCastle.Cms.SignerInformationStore sigInfStore = signedData.GetSignerInfos();

            System.Collections.IEnumerator signers = sigInfStore.GetSigners().GetEnumerator();
            signers.Reset();
            signers.MoveNext();
            Org.BouncyCastle.Cms.SignerInformation signerInfo = (Org.BouncyCastle.Cms.SignerInformation)signers.Current;

            messageDigest = null;
            digestAlgOid  = signerInfo.DigestAlgOid;
            isEpes        = false;
            if (subFilter.ToLower() == "adbe.pkcs7.sha1")
            {
                digestAlgOid  = "1.3.14.3.2.26";
                messageDigest = ((Org.BouncyCastle.Asn1.DerOctetString)Org.BouncyCastle.Asn1.Cms.SignedData.GetInstance(signedData.ContentInfo.Content).EncapContentInfo.Content).GetOctets();
            }
            else
            {
                if (signerInfo.SignedAttributes != null)
                {
                    //messageDigest
                    Org.BouncyCastle.Asn1.Cms.Attribute messageDigestAttr = signerInfo.SignedAttributes[Org.BouncyCastle.Asn1.Pkcs.PkcsObjectIdentifiers.Pkcs9AtMessageDigest];
                    if (messageDigestAttr != null &&
                        messageDigestAttr.AttrValues.Count > 0)
                    {
                        messageDigest = Org.BouncyCastle.Asn1.DerOctetString.GetInstance(messageDigestAttr.AttrValues[0]).GetOctets();
                    }

                    //signature policy
                    isEpes = (signerInfo.SignedAttributes[Org.BouncyCastle.Asn1.Pkcs.PkcsObjectIdentifiers.IdAAEtsSigPolicyID] != null &&
                              signerInfo.SignedAttributes[Org.BouncyCastle.Asn1.Pkcs.PkcsObjectIdentifiers.IdAAEtsSigPolicyID].AttrValues.Count > 0);
                }
            }
        }
Exemple #8
0
        /**
         * Use this constructor if you want to verify a signature using
         * the sub-filter adbe.pkcs7.detached or adbe.pkcs7.sha1.
         * @param contentsKey the /Contents key
         * @param tsp set to true if there's a PAdES LTV time stamp.
         * @param provider the provider or <code>null</code> for the default provider
         */
        public PdfPKCS7(byte[] contentsKey, bool tsp)
        {
            isTsp = tsp;
            Asn1InputStream din = new Asn1InputStream(new MemoryStream(contentsKey));

            //
            // Basic checks to make sure it's a PKCS#7 SignedData Object
            //
            Asn1Object pkcs;

            try {
                pkcs = din.ReadObject();
            }
            catch  {
                throw new ArgumentException(MessageLocalization.GetComposedMessage("can.t.decode.pkcs7signeddata.object"));
            }
            if (!(pkcs is Asn1Sequence))
            {
                throw new ArgumentException(MessageLocalization.GetComposedMessage("not.a.valid.pkcs.7.object.not.a.sequence"));
            }
            Asn1Sequence        signedData = (Asn1Sequence)pkcs;
            DerObjectIdentifier objId      = (DerObjectIdentifier)signedData[0];

            if (!objId.Id.Equals(SecurityIDs.ID_PKCS7_SIGNED_DATA))
            {
                throw new ArgumentException(MessageLocalization.GetComposedMessage("not.a.valid.pkcs.7.object.not.signed.data"));
            }
            Asn1Sequence content = (Asn1Sequence)((Asn1TaggedObject)signedData[1]).GetObject();

            // the positions that we care are:
            //     0 - version
            //     1 - digestAlgorithms
            //     2 - possible ID_PKCS7_DATA
            //     (the certificates and crls are taken out by other means)
            //     last - signerInfos

            // the version
            version = ((DerInteger)content[0]).Value.IntValue;

            // the digestAlgorithms
            digestalgos = new Dictionary <string, object>();
            IEnumerator e = ((Asn1Set)content[1]).GetEnumerator();

            while (e.MoveNext())
            {
                Asn1Sequence        s = (Asn1Sequence)e.Current;
                DerObjectIdentifier o = (DerObjectIdentifier)s[0];
                digestalgos[o.Id] = null;
            }

            // the certificates and crls
            X509CertificateParser cf = new X509CertificateParser();

            certs = new List <X509Certificate>();
            foreach (X509Certificate cc in cf.ReadCertificates(contentsKey))
            {
                certs.Add(cc);
            }
            crls = new List <X509Crl>();

            // the possible ID_PKCS7_DATA
            Asn1Sequence rsaData = (Asn1Sequence)content[2];

            if (rsaData.Count > 1)
            {
                Asn1OctetString rsaDataContent = (Asn1OctetString)((Asn1TaggedObject)rsaData[1]).GetObject();
                RSAdata = rsaDataContent.GetOctets();
            }

            // the signerInfos
            int next = 3;

            while (content[next] is Asn1TaggedObject)
            {
                ++next;
            }
            Asn1Set signerInfos = (Asn1Set)content[next];

            if (signerInfos.Count != 1)
            {
                throw new ArgumentException(MessageLocalization.GetComposedMessage("this.pkcs.7.object.has.multiple.signerinfos.only.one.is.supported.at.this.time"));
            }
            Asn1Sequence signerInfo = (Asn1Sequence)signerInfos[0];

            // the positions that we care are
            //     0 - version
            //     1 - the signing certificate issuer and serial number
            //     2 - the digest algorithm
            //     3 or 4 - digestEncryptionAlgorithm
            //     4 or 5 - encryptedDigest
            signerversion = ((DerInteger)signerInfo[0]).Value.IntValue;
            // Get the signing certificate
            Asn1Sequence issuerAndSerialNumber = (Asn1Sequence)signerInfo[1];

            Org.BouncyCastle.Asn1.X509.X509Name issuer = Org.BouncyCastle.Asn1.X509.X509Name.GetInstance(issuerAndSerialNumber[0]);
            BigInteger serialNumber = ((DerInteger)issuerAndSerialNumber[1]).Value;

            foreach (X509Certificate cert in certs)
            {
                if (issuer.Equivalent(cert.IssuerDN) && serialNumber.Equals(cert.SerialNumber))
                {
                    signCert = cert;
                    break;
                }
            }
            if (signCert == null)
            {
                throw new ArgumentException(MessageLocalization.GetComposedMessage("can.t.find.signing.certificate.with.serial.1",
                                                                                   issuer.ToString() + " / " + serialNumber.ToString(16)));
            }
            CalcSignCertificateChain();
            digestAlgorithmOid = ((DerObjectIdentifier)((Asn1Sequence)signerInfo[2])[0]).Id;
            next = 3;
            if (signerInfo[next] is Asn1TaggedObject)
            {
                Asn1TaggedObject tagsig = (Asn1TaggedObject)signerInfo[next];
                Asn1Set          sseq   = Asn1Set.GetInstance(tagsig, false);
                sigAttr = sseq.GetEncoded(Asn1Encodable.Der);

                for (int k = 0; k < sseq.Count; ++k)
                {
                    Asn1Sequence seq2 = (Asn1Sequence)sseq[k];
                    if (((DerObjectIdentifier)seq2[0]).Id.Equals(SecurityIDs.ID_MESSAGE_DIGEST))
                    {
                        Asn1Set sset = (Asn1Set)seq2[1];
                        digestAttr = ((DerOctetString)sset[0]).GetOctets();
                    }
                    else if (((DerObjectIdentifier)seq2[0]).Id.Equals(SecurityIDs.ID_ADBE_REVOCATION))
                    {
                        Asn1Set      setout = (Asn1Set)seq2[1];
                        Asn1Sequence seqout = (Asn1Sequence)setout[0];
                        for (int j = 0; j < seqout.Count; ++j)
                        {
                            Asn1TaggedObject tg = (Asn1TaggedObject)seqout[j];
                            if (tg.TagNo == 1)
                            {
                                Asn1Sequence seqin = (Asn1Sequence)tg.GetObject();
                                FindOcsp(seqin);
                            }
                            if (tg.TagNo == 0)
                            {
                                Asn1Sequence seqin = (Asn1Sequence)tg.GetObject();
                                FindCRL(seqin);
                            }
                        }
                    }
                }
                if (digestAttr == null)
                {
                    throw new ArgumentException(MessageLocalization.GetComposedMessage("authenticated.attribute.is.missing.the.digest"));
                }
                ++next;
            }
            digestEncryptionAlgorithmOid = ((DerObjectIdentifier)((Asn1Sequence)signerInfo[next++])[0]).Id;
            digest = ((Asn1OctetString)signerInfo[next++]).GetOctets();
            if (next < signerInfo.Count && (signerInfo[next] is DerTaggedObject))
            {
                Asn1TaggedObject taggedObject = (Asn1TaggedObject)signerInfo[next];
                Asn1Set          unat         = Asn1Set.GetInstance(taggedObject, false);
                Org.BouncyCastle.Asn1.Cms.AttributeTable attble = new Org.BouncyCastle.Asn1.Cms.AttributeTable(unat);
                Org.BouncyCastle.Asn1.Cms.Attribute      ts     = attble[PkcsObjectIdentifiers.IdAASignatureTimeStampToken];
                if (ts != null && ts.AttrValues.Count > 0)
                {
                    Asn1Set      attributeValues = ts.AttrValues;
                    Asn1Sequence tokenSequence   = Asn1Sequence.GetInstance(attributeValues[0]);
                    Org.BouncyCastle.Asn1.Cms.ContentInfo contentInfo = Org.BouncyCastle.Asn1.Cms.ContentInfo.GetInstance(tokenSequence);
                    this.timeStampToken = new TimeStampToken(contentInfo);
                }
            }
            if (isTsp)
            {
                Org.BouncyCastle.Asn1.Cms.ContentInfo contentInfoTsp = Org.BouncyCastle.Asn1.Cms.ContentInfo.GetInstance(signedData);
                this.timeStampToken = new TimeStampToken(contentInfoTsp);
                TimeStampTokenInfo info   = timeStampToken.TimeStampInfo;
                String             algOID = info.MessageImprintAlgOid;
                messageDigest = DigestUtilities.GetDigest(algOID);
            }
            else
            {
                if (RSAdata != null || digestAttr != null)
                {
                    messageDigest = GetHashClass();
                    encContDigest = GetHashClass();
                }
                sig = SignerUtilities.GetSigner(GetDigestAlgorithm());
                sig.Init(false, signCert.GetPublicKey());
            }
        }
        private CmsSignedData GenerateTimestamp(
            TimeStampRequest request,
            BigInteger serialNumber,
            DateTime generalizedTime)
        {
            var messageImprint = new MessageImprint(
                new AlgorithmIdentifier(
                    new DerObjectIdentifier(request.MessageImprintAlgOid)), request.GetMessageImprintDigest());
            DerInteger nonce = request.Nonce == null ? null : new DerInteger(request.Nonce);

            var tstInfo = new TstInfo(
                new DerObjectIdentifier(_options.Policy.Value),
                messageImprint,
                new DerInteger(serialNumber),
                new DerGeneralizedTime(generalizedTime),
                _options.Accuracy,
                DerBoolean.False,
                nonce,
                tsa: null,
                extensions: null);

            var content          = new CmsProcessableByteArray(tstInfo.GetEncoded());
            var signedAttributes = new Asn1EncodableVector();
            var certificateBytes = new Lazy <byte[]>(() => Certificate.GetEncoded());

            if (_options.SigningCertificateUsage.HasFlag(SigningCertificateUsage.V1))
            {
                byte[] hash = _options.SigningCertificateV1Hash ?? DigestUtilities.CalculateDigest("SHA-1", certificateBytes.Value);
                var    signingCertificate = new SigningCertificate(new EssCertID(hash));
                var    attributeValue     = new DerSet(signingCertificate);
                var    attribute          = new BcAttribute(PkcsObjectIdentifiers.IdAASigningCertificate, attributeValue);

                signedAttributes.Add(attribute);
            }

            if (_options.SigningCertificateUsage.HasFlag(SigningCertificateUsage.V2))
            {
                byte[] hash = DigestUtilities.CalculateDigest("SHA-256", certificateBytes.Value);
                var    signingCertificateV2 = new SigningCertificateV2(new EssCertIDv2(hash));
                var    attributeValue       = new DerSet(signingCertificateV2);
                var    attribute            = new BcAttribute(PkcsObjectIdentifiers.IdAASigningCertificateV2, attributeValue);

                signedAttributes.Add(attribute);
            }

            var generator = new CmsSignedDataGenerator();

            if (_options.ReturnSigningCertificate)
            {
                var certificates = X509StoreFactory.Create(
                    "Certificate/Collection",
                    new X509CollectionStoreParameters(new[] { Certificate }));

                generator.AddCertificates(certificates);
            }

            generator.AddSigner(
                _keyPair.Private,
                Certificate,
                _options.SignatureHashAlgorithm.Value,
                new BcAttributeTable(signedAttributes),
                new BcAttributeTable(DerSet.Empty));

            CmsSignedData signedCms = generator.Generate(
                PkcsObjectIdentifiers.IdCTTstInfo.Id,
                content,
                encapsulate: true);

            return(signedCms);
        }
Exemple #10
0
        public byte[] FirmaFileBouncy(string NomeFile, X509Certificate2 cert, bool GiaFirmato, bool UsaTSA, string TSAurl, string TSAuser, string TSApass, out string RisFirma)
        {
            try
            {
                SHA256Managed        hashSha256 = new SHA256Managed();
                byte[]               certHash   = hashSha256.ComputeHash(cert.RawData);
                EssCertIDv2          essCert1   = new EssCertIDv2(new Org.BouncyCastle.Asn1.X509.AlgorithmIdentifier("2.16.840.1.101.3.4.2.1"), certHash);
                SigningCertificateV2 scv2       = new SigningCertificateV2(new EssCertIDv2[] { essCert1 });
                Org.BouncyCastle.Asn1.Cms.Attribute CertHAttribute = new Org.BouncyCastle.Asn1.Cms.Attribute(Org.BouncyCastle.Asn1.Pkcs.PkcsObjectIdentifiers.IdAASigningCertificateV2, new DerSet(scv2));
                Asn1EncodableVector v = new Asn1EncodableVector();
                v.Add(CertHAttribute);
                Org.BouncyCastle.Asn1.Cms.AttributeTable AT = new Org.BouncyCastle.Asn1.Cms.AttributeTable(v);
                CmsSignedDataGenWithRsaCsp cms = new CmsSignedDataGenWithRsaCsp();
                var rsa = (RSACryptoServiceProvider)cert.PrivateKey;
                Org.BouncyCastle.X509.X509Certificate certCopy = DotNetUtilities.FromX509Certificate(cert);
                cms.MyAddSigner(rsa, certCopy, "1.2.840.113549.1.1.1", "2.16.840.1.101.3.4.2.1", AT, null);
                ArrayList certList = new ArrayList();
                certList.Add(certCopy);
                Org.BouncyCastle.X509.Store.X509CollectionStoreParameters PP = new Org.BouncyCastle.X509.Store.X509CollectionStoreParameters(certList);
                Org.BouncyCastle.X509.Store.IX509Store st1 = Org.BouncyCastle.X509.Store.X509StoreFactory.Create("CERTIFICATE/COLLECTION", PP);
                cms.AddCertificates(st1);
                //mi ricavo il file da firmare
                FileInfo FileDaAprire = new FileInfo(NomeFile);

                /*CmsSignedData Firmato;
                 * if (GiaFirmato) {
                 *      CmsSignedData signedData = new CmsSignedData(File.ReadAllBytes(NomeFile));
                 *      if (signedData!=null){
                 *              SignerInformationStore signers = signedData.GetSignerInfos();
                 *              certList.Add(signers.GetSigners());
                 *              //MessageBox.Show(signedData.ContentInfo.GetEncoded().Length.ToString());
                 *              //signedData.ContentInfo.GetEncoded();
                 *      }
                 *      certList.Insert(0,certCopy);
                 *      CmsProcessableByteArray file = new CmsProcessableByteArray(signedData.ContentInfo.GetEncoded());
                 *      Firmato = cms.Generate(file, true);
                 * } else {
                 *      certList.Add(certCopy);
                 *      CmsProcessableFile file = new CmsProcessableFile(FileDaAprire);
                 *      Firmato = cms.Generate(file, true);
                 * }
                 */
                CmsProcessableFile file    = new CmsProcessableFile(FileDaAprire);
                CmsSignedData      Firmato = cms.Generate(file, true);
                byte[]             Encoded = Firmato.GetEncoded();

                if (UsaTSA)
                {
                    CmsSignedData          sd      = new CmsSignedData(Encoded);
                    SignerInformationStore signers = sd.GetSignerInfos();
                    byte[]            signature    = null;
                    SignerInformation signer       = null;
                    foreach (SignerInformation signer_ in signers.GetSigners())
                    {
                        signer = signer_;
                        break;
                    }

                    signature = signer.GetSignature();
                    Org.BouncyCastle.Asn1.Cms.AttributeTable at = new Org.BouncyCastle.Asn1.Cms.AttributeTable(GetTimestamp(signature, TSAurl, TSAuser, TSApass));
                    signer = SignerInformation.ReplaceUnsignedAttributes(signer, at);
                    IList signerInfos = new ArrayList();
                    signerInfos.Add(signer);
                    sd      = CmsSignedData.ReplaceSigners(sd, new SignerInformationStore(signerInfos));
                    Encoded = sd.GetEncoded();
                }
                RisFirma = "";
                return(Encoded);
            }
            catch (Exception ex)
            {
                RisFirma = ex.ToString();
                return(null);
            }
        }