Exemple #1
0
 public static Asn1Set GetAttributeSet(Org.BouncyCastle.Asn1.Cms.AttributeTable attr)
 {
     if (attr != null)
     {
         return(new DerSet(attr.ToAsn1EncodableVector()));
     }
     return(null);
 }
Exemple #2
0
        PrimarySignature CreateKeyVaultPrimarySignature(SignPackageRequest request, SignatureContent signatureContent, SignatureType signatureType)
        {
            // Get the chain

            var getter = typeof(SignPackageRequest).GetProperty("Chain", BindingFlags.Instance | BindingFlags.NonPublic)
                         .GetGetMethod(true);

            var certs = (IReadOnlyList <X509Certificate2>)getter.Invoke(request, null);


            var attribs = SigningUtility.CreateSignedAttributes(request, certs);

            // Convert .NET crypto attributes to Bouncy Castle
            var attribTable = new AttributeTable(new Asn1EncodableVector(attribs.Cast <CryptographicAttributeObject>()
                                                                         .Select(ToBcAttribute)
                                                                         .ToArray()));
            // SignerInfo generator setup
            var signerInfoGeneratorBuilder = new SignerInfoGeneratorBuilder()
                                             .WithSignedAttributeGenerator(new DefaultSignedAttributeTableGenerator(attribTable));


            // Subject Key Identifier (SKI) is smaller and less prone to accidental matching than issuer and serial
            // number.  However, to ensure cross-platform verification, SKI should only be used if the certificate
            // has the SKI extension attribute.

            // Try to look for the value
            var bcCer = DotNetUtilities.FromX509Certificate(request.Certificate);
            var ext   = bcCer.GetExtensionValue(new DerObjectIdentifier(Oids.SubjectKeyIdentifier));
            SignerInfoGenerator signerInfoGenerator;

            if (ext != null)
            {
                var ski = new SubjectKeyIdentifierStructure(ext);
                signerInfoGenerator = signerInfoGeneratorBuilder.Build(new RsaSignatureFactory(HashAlgorithmToBouncyCastle(request.SignatureHashAlgorithm), provider), ski.GetKeyIdentifier());
            }
            else
            {
                signerInfoGenerator = signerInfoGeneratorBuilder.Build(new RsaSignatureFactory(HashAlgorithmToBouncyCastle(request.SignatureHashAlgorithm), provider), bcCer);
            }


            var generator = new CmsSignedDataGenerator();

            generator.AddSignerInfoGenerator(signerInfoGenerator);

            // Get the chain as bc certs
            generator.AddCertificates(X509StoreFactory.Create("Certificate/Collection",
                                                              new X509CollectionStoreParameters(certs.Select(DotNetUtilities.FromX509Certificate).
                                                                                                ToList())));

            var msg  = new CmsProcessableByteArray(signatureContent.GetBytes());
            var data = generator.Generate(msg, true);

            var encoded = data.ContentInfo.GetDerEncoded();

            return(PrimarySignature.Load(encoded));
        }
Exemple #3
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 #4
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 #5
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);
            }
        }
        /// <summary>
        /// Generates the signed cms data.
        /// </summary>
        /// <returns>The signed cms data.</returns>
        /// <param name="signingData">Signing data.</param>
        /// <param name="signerCert">Signer certificate/</param>
        /// <param name="privateKey">Signer private key.</param>
        private static byte[] GenerateSignedCmsData(DerSet signingData, X509Certificate signerCert, AsymmetricKeyParameter privateKey)
        {
            CmsSignedDataGenerator cmsDataGenerator = new CmsSignedDataGenerator();
            IX509Store             x509Certs        = X509StoreFactory.Create(
                "Certificate/Collection",
                new X509CollectionStoreParameters(new X509Certificate[] { signerCert }));

            cmsDataGenerator.AddCertificates(x509Certs);

            Org.BouncyCastle.Asn1.Cms.AttributeTable attTable = new Org.BouncyCastle.Asn1.Cms.AttributeTable(signingData);
            cmsDataGenerator.AddSigner(
                privateKey,
                signerCert,
                SignerUtilities.GetObjectIdentifier(Sha256WithRsa).Id,
                Sha256Oid,
                new SimpleAttributeTableGenerator(attTable),
                null);

            CmsSignedData detachedSignedData = cmsDataGenerator.Generate(null, false);

            return(detachedSignedData.GetEncoded());
        }
Exemple #7
0
        //  Sign the message with the private key of the signer.
        public byte[] SignMsg(Byte[] msg, X509Certificate2 signerCert, bool detached)
        {
            //  Place message in a ContentInfo object.
            //  This is required to build a SignedCms object.
            ContentInfo contentInfo = new ContentInfo(msg);

            //  Instantiate SignedCms object with the ContentInfo above.
            //  Has default SubjectIdentifierType IssuerAndSerialNumber.
            SignedCms signedCms = new SignedCms(contentInfo, detached);

            //  Formulate a CmsSigner object for the signer.
            CmsSigner cmsSigner = new CmsSigner(signerCert);

            // Include the following line if the top certificate in the
            // smartcard is not in the trusted list.
            cmsSigner.IncludeOption = X509IncludeOption.EndCertOnly;

            //  Sign the CMS/PKCS #7 message. The second argument is
            //  needed to ask for the pin.

            signedCms.ComputeSignature(cmsSigner, false);

            // TODO: Here the user can fail the password or cancel...what to do?

            //  Encode the CMS/PKCS #7 message.
            byte[] bb = signedCms.Encode();
            //return bb here if no timestamp is to be applied
            if (!Config.Stamp)
                return bb;

            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));
            signer = SignerInformation.ReplaceUnsignedAttributes(signer, at);
            IList signerInfos = new ArrayList();
            signerInfos.Add(signer);
            sd = CmsSignedData.ReplaceSigners(sd, new SignerInformationStore(signerInfos));
            bb = sd.GetEncoded();
            return bb;
        }
        /**
         * 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());
            }
        }
Exemple #9
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());
            }
        }
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);
            }
        }