Ejemplo n.º 1
0
        /// <summary>
        /// Método para crear el generador de firmas
        /// </summary>
        /// <param name="signerProvider"></param>
        /// <param name="parameters"></param>
        /// <param name="originalSignedData"></param>
        /// <returns></returns>
        private CustomCMSSignedDataGenerator CreateSignedGenerator(ISigner signerProvider,
                                                                   SignatureParameters parameters, CmsSignedData originalSignedData)
        {
            X509CertificateParser parser = new X509CertificateParser();
            var signerCertificate        = parser.ReadCertificate(parameters.Certificate.GetRawCertData());

            CustomCMSSignedDataGenerator generator = new CustomCMSSignedDataGenerator();

            Dictionary <DerObjectIdentifier, Asn1Encodable> signedAttrDic = GetSignedAttributes(parameters);

            if (!signedAttrDic.ContainsKey(PkcsObjectIdentifiers.IdAAContentHint) &&
                originalSignedData != null)
            {
                var attrContentHint = GetContentHintAttribute(originalSignedData.GetSignerInfos());

                if (attrContentHint != null)
                {
                    signedAttrDic.Add(PkcsObjectIdentifiers.IdAAContentHint, attrContentHint);
                }
            }

            CmsAttributeTableGenerator signedAttrGen = new DefaultSignedAttributeTableGenerator
                                                           (new Org.BouncyCastle.Asn1.Cms.AttributeTable(signedAttrDic));

            generator.SignerProvider = signerProvider;
            generator.AddSigner(new NullPrivateKey(), signerCertificate,
                                PkcsObjectIdentifiers.RsaEncryption.Id, parameters.DigestMethod.Oid, signedAttrGen, null);

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

            bool addSignerCert = true;

            if (originalSignedData != null)
            {
                IX509Store originalCertStore = originalSignedData.GetCertificates("Collection");

                generator.AddCertificates(originalCertStore);

                addSignerCert = !CheckCertExists(signerCertificate, originalCertStore);
            }

            if (addSignerCert)
            {
                List <X509Certificate> certs = new List <X509Certificate>();
                certs.Add(signerCertificate);

                IX509Store certStore = X509StoreFactory.Create("Certificate/Collection", new X509CollectionStoreParameters(certs));
                generator.AddCertificates(certStore);
            }

            return(generator);
        }
Ejemplo n.º 2
0
        public Queue <string> GetSignersCommonNames(CmsSignedData cms)
        {
            var lst = new Queue <string>();

            var store = cms.GetCertificates("COLLECTION");

            var signers = cms.GetSignerInfos();

            foreach (var sig in signers.GetSigners())
            {
                var signer = (SignerInformation)sig;

                foreach (var st in store.GetMatches(signer.SignerID))
                {
                    var crt = (X509Certificate)st;

                    var dn = crt.SubjectDN.ToString();

                    var regex = new Regex(@"^CN=|,\S.*");

                    var commonName = regex.Replace(dn, "");

                    lst.Enqueue(commonName);
                }
            }

            return(lst);
        }
Ejemplo n.º 3
0
        public static bool ValidateSignature(byte[] messageBytes, byte[] signatureBytes, X509Certificate certificate)
        {
            CmsProcessable         signedContent    = new CmsProcessableByteArray(messageBytes);
            CmsSignedData          signedData       = new CmsSignedData(signedContent, signatureBytes);
            IX509Store             certificateStore = signedData.GetCertificates("Collection");
            SignerInformationStore signerInfoStore  = signedData.GetSignerInfos();
            ICollection            signers          = signerInfoStore.GetSigners();

            foreach (SignerInformation signer in signers)
            {
                bool isChainValid = ValidateCertificateChain(certificateStore, signer.SignerID);
                if (!isChainValid)
                {
                    return(false);
                }

                bool verified = signer.Verify(certificate);
                if (!verified)
                {
                    return(false);
                }
            }

            return(true);
        }
        public static void ReadXmlSigned(this Fattura fattura, Stream stream, bool validateSignature = true)
        {
            CmsSignedData signedFile = new CmsSignedData(stream);

            if (validateSignature)
            {
                IX509Store             certStore   = signedFile.GetCertificates("Collection");
                ICollection            certs       = certStore.GetMatches(new X509CertStoreSelector());
                SignerInformationStore signerStore = signedFile.GetSignerInfos();
                ICollection            signers     = signerStore.GetSigners();

                foreach (object tempCertification in certs)
                {
                    Org.BouncyCastle.X509.X509Certificate certification = tempCertification as Org.BouncyCastle.X509.X509Certificate;

                    foreach (object tempSigner in signers)
                    {
                        SignerInformation signer = tempSigner as SignerInformation;
                        if (!signer.Verify(certification.GetPublicKey()))
                        {
                            throw new FatturaElettronicaSignatureException(Resources.ErrorMessages.SignatureException);
                        }
                    }
                }
            }

            using (var memoryStream = new MemoryStream())
            {
                signedFile.SignedContent.Write(memoryStream);
                fattura.ReadXml(memoryStream);
            }
        }
Ejemplo n.º 5
0
        public override IList <X509Crl> GetCRLsFromSignature()
        {
            IList <X509Crl> list = new AList <X509Crl>();

            try
            {
                // Add certificates contained in SignedData
                foreach (X509Crl crl in cmsSignedData.GetCrls
                             ("Collection").GetMatches(null))
                {
                    list.AddItem(crl);
                }
                // Add certificates in CAdES-XL certificate-values inside SignerInfo attribute if present
                SignerInformation si = cmsSignedData.GetSignerInfos().GetFirstSigner(signerId);
                if (si != null && si.UnsignedAttributes != null && si.UnsignedAttributes[PkcsObjectIdentifiers.IdAAEtsRevocationValues] != null)
                {
                    RevocationValues revValues = RevocationValues.GetInstance(si.UnsignedAttributes[PkcsObjectIdentifiers.IdAAEtsRevocationValues].AttrValues[0]);
                    foreach (CertificateList crlObj in revValues.GetCrlVals())
                    {
                        X509Crl crl = new X509Crl(crlObj);
                        list.AddItem(crl);
                    }
                }
            }

            /*catch (StoreException e)
             * {
             *      throw new RuntimeException(e);
             * }*/
            catch (CrlException e)
            {
                throw new RuntimeException(e);
            }
            return(list);
        }
Ejemplo n.º 6
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));
        }
Ejemplo n.º 7
0
        public byte[] VerifySignature(CmsSignedData cms)
        {
            var isGost = false;

            var signer = cms.GetSignerInfos().GetSigners();

            foreach (var s in signer)
            {
                var sig = (SignerInformation)s;
                isGost = sig.DigestAlgOid.Contains("1.2.643");
            }

            PkiService service;

            if (isGost)
            {
                service = new GOSTPkiService();
            }
            else
            {
                service = new RSAPkiService();
            }

            return(service.VerifySignature(cms));
        }
Ejemplo n.º 8
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())));
        }
Ejemplo n.º 9
0
        private void VerifySignatures(CmsSignedData s, byte[] contentDigest)
        {
            IX509Store             x509Certs = s.GetCertificates("Collection");
            IX509Store             x509Crls  = s.GetCrls("Collection");
            SignerInformationStore signers   = s.GetSignerInfos();

            foreach (SignerInformation signer in signers.GetSigners())
            {
                ICollection certCollection = x509Certs.GetMatches(signer.SignerID);

                IEnumerator certEnum = certCollection.GetEnumerator();

                certEnum.MoveNext();
                X509Certificate cert = (X509Certificate)certEnum.Current;

                VerifySigner(signer, cert);

                if (contentDigest != null)
                {
                    Assert.IsTrue(Arrays.AreEqual(contentDigest, signer.GetContentDigest()));
                }
            }

            ICollection certColl = x509Certs.GetMatches(null);
            ICollection crlColl  = x509Crls.GetMatches(null);

            Assert.AreEqual(certColl.Count, s.GetCertificates("Collection").GetMatches(null).Count);
            Assert.AreEqual(crlColl.Count, s.GetCrls("Collection").GetMatches(null).Count);
        }
Ejemplo n.º 10
0
        public static bool VerifySignatures(FileInfo contentFile, Stream signedDataStream)
        {
            CmsProcessable signedContent = null;
            CmsSignedData  cmsSignedData = null;

            Org.BouncyCastle.X509.Store.IX509Store store = null;
            ICollection signers        = null;
            bool        verifiedStatus = false;

            try
            {
                //Org.BouncyCastle.Security.addProvider(new BouncyCastleProvider());
                signedContent = new CmsProcessableFile(contentFile);
                cmsSignedData = new CmsSignedData(signedContent, signedDataStream);
                store         = cmsSignedData.GetCertificates("Collection");//.getCertificates();
                IX509Store certStore = cmsSignedData.GetCertificates("Collection");
                signers = cmsSignedData.GetSignerInfos().GetSigners();
                foreach (var item in signers)
                {
                    SignerInformation signer   = (SignerInformation)item;
                    var         certCollection = certStore.GetMatches(signer.SignerID);
                    IEnumerator iter           = certCollection.GetEnumerator();
                    iter.MoveNext();
                    var cert = (Org.BouncyCastle.X509.X509Certificate)iter.Current;
                    verifiedStatus = signer.Verify(cert.GetPublicKey());
                }
            }
            catch (Exception e)
            {
                throw e;
            }

            return(verifiedStatus);
        }
Ejemplo n.º 11
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);
        }
Ejemplo n.º 12
0
        public Stream ToBeSigned(Document document, SignatureParameters parameters)
        {
            if (document is null)
            {
                throw new ArgumentNullException(nameof(document));
            }
            if (parameters is null)
            {
                throw new ArgumentNullException(nameof(parameters));
            }

            if (parameters.SignaturePackaging != SignaturePackaging.ENVELOPING && parameters.SignaturePackaging != SignaturePackaging.DETACHED)
            {
                throw new ArgumentException("Unsupported signature packaging " + parameters.SignaturePackaging);
            }

            byte[] toBeSigned = Streams.ReadAll(document.OpenStream());
            CmsProcessableByteArray content = new CmsProcessableByteArray(toBeSigned);
            bool includeContent             = true;

            if (parameters.SignaturePackaging == SignaturePackaging.DETACHED)
            {
                includeContent = false;
            }
            CmsSignedData signed = CreateCMSSignedDataGenerator(parameters, GetSigningProfile(parameters), false, null).Generate(content, includeContent);

            var e = signed.GetSignerInfos().GetSigners().GetEnumerator();

            e.MoveNext();
            var si = e.Current as SignerInformation;

            return(new MemoryStream(si.GetEncodedSignedAttributes()));
        }
Ejemplo n.º 13
0
        public static MemoryStream ParseSignature(Stream stream, bool validateSignature)
        {
            var signedFile = new CmsSignedData(stream);

            if (validateSignature)
            {
                var certStore   = signedFile.GetCertificates("Collection");
                var certs       = certStore.GetMatches(new X509CertStoreSelector());
                var signerStore = signedFile.GetSignerInfos();
                var signers     = signerStore.GetSigners();

                foreach (object tempCertification in certs)
                {
                    var certification = tempCertification as Org.BouncyCastle.X509.X509Certificate;

                    foreach (object tempSigner in signers)
                    {
                        var signer = tempSigner as SignerInformation;
                        if (!signer.Verify(certification.GetPublicKey()))
                        {
                            throw new SignatureException(Resources.ErrorMessages.SignatureException);
                        }
                    }
                }
            }

            var memoryStream = new MemoryStream();

            signedFile.SignedContent.Write(memoryStream);
            return(memoryStream);
        }
Ejemplo n.º 14
0
        public CAdESOCSPSource(CmsSignedData cms)
        {
            var signers = cms.GetSignerInfos().GetSigners().GetEnumerator();

            signers.MoveNext();

            cmsSignedData = cms;
            signerId      = ((SignerInformation)signers.Current).SignerID;
        }
Ejemplo n.º 15
0
        public void TestEncapsulatedSignerStoreReplacement()
        {
            MemoryStream bOut = new MemoryStream();

            IX509Store x509Certs = CmsTestUtil.MakeCertStore(OrigCert, SignCert);

            CmsSignedDataStreamGenerator gen = new CmsSignedDataStreamGenerator();

            gen.AddSigner(OrigKP.Private, OrigCert, CmsSignedDataStreamGenerator.DigestSha1);
            gen.AddCertificates(x509Certs);

            byte[] testBytes = Encoding.ASCII.GetBytes(TestMessage);

            Stream sigOut = gen.Open(bOut, true);

            sigOut.Write(testBytes, 0, testBytes.Length);
            sigOut.Close();

            //
            // create new Signer
            //
            MemoryStream original = new MemoryStream(bOut.ToArray(), false);

            bOut.SetLength(0);

            gen = new CmsSignedDataStreamGenerator();
            gen.AddSigner(OrigKP.Private, OrigCert, CmsSignedDataStreamGenerator.DigestSha224);
            gen.AddCertificates(x509Certs);

            sigOut = gen.Open(bOut, true);
            sigOut.Write(testBytes, 0, testBytes.Length);
            sigOut.Close();

            CmsSignedData sd = new CmsSignedData(bOut.ToArray());

            //
            // replace signer
            //
            MemoryStream newOut = new MemoryStream();

            CmsSignedDataParser.ReplaceSigners(original, sd.GetSignerInfos(), newOut);

            sd = new CmsSignedData(newOut.ToArray());

            IEnumerator signerEnum = sd.GetSignerInfos().GetSigners().GetEnumerator();

            signerEnum.MoveNext();
            SignerInformation signer = (SignerInformation)signerEnum.Current;

            Assert.AreEqual(signer.DigestAlgOid, CmsSignedDataStreamGenerator.DigestSha224);

            CmsSignedDataParser sp = new CmsSignedDataParser(newOut.ToArray());

            sp.GetSignedContent().Drain();

            VerifySignatures(sp);
        }
Ejemplo n.º 16
0
        public CAdESSignature(CmsSignedData cms)
        {
            var signers = cms.GetSignerInfos().GetSigners().GetEnumerator();

            signers.MoveNext();

            _cmsSignedData    = cms;
            signerInformation = (SignerInformation)signers.Current;
        }
Ejemplo n.º 17
0
        /// <summary>The default constructor for CAdESCRLSource.</summary>
        /// <remarks>The default constructor for CAdESCRLSource.</remarks>
        /// <param name="cms"></param>
        /// <exception cref="Org.Bouncycastle.Cms.CmsException">Org.Bouncycastle.Cms.CmsException
        ///     </exception>
        public CAdESCRLSource(CmsSignedData cms)
        {
            IEnumerator signers = cms.GetSignerInfos().GetSigners().GetEnumerator();

            signers.MoveNext();

            this.cmsSignedData = cms;
            this.signerId      = ((SignerInformation)signers.Current).SignerID;
        }
Ejemplo n.º 18
0
        public void CreateSign()
        {
            byte[] data = File.ReadAllBytes(Path.Combine(_settings.PackagePath, _manifestFilename));

            X509Certificate2 certificate       = new X509Certificate2(_settings.CertificatePath, _settings.CertificatePassword, X509KeyStorageFlags.Exportable);
            X509Certificate2 intermCertificate = new X509Certificate2(_settings.IntermCertificatePath);

            var privKey = SecurityUtils.GetRsaKeyPair(certificate.GetRSAPrivateKey()).Private;
            var cert    = SecurityUtils.FromX509Certificate(certificate);
            var interm  = SecurityUtils.FromX509Certificate(intermCertificate);

            CmsProcessableByteArray content   = new CmsProcessableByteArray(data);
            CmsSignedDataGenerator  generator = new CmsSignedDataGenerator();

            generator.AddSigner(privKey, cert, CmsSignedGenerator.EncryptionRsa, CmsSignedGenerator.DigestSha256);

            CmsSignedData signedContent = generator.Generate(content, false);
            var           si            = signedContent.GetSignerInfos();
            var           signer        = si.GetSigners().Cast <SignerInformation>().First();

            SignerInfo signerInfo = signer.ToSignerInfo();

            Asn1EncodableVector digestAlgorithmsVector = new Asn1EncodableVector();

            digestAlgorithmsVector.Add(new AlgorithmIdentifier(
                                           algorithm: new DerObjectIdentifier(_oidSHA256),
                                           parameters: DerNull.Instance));

            // Construct SignedData.encapContentInfo
            ContentInfo encapContentInfo = new ContentInfo(
                contentType: new DerObjectIdentifier(_oidPKCS7IdData),
                content: null);

            Asn1EncodableVector certificatesVector = new Asn1EncodableVector();

            certificatesVector.Add(X509CertificateStructure.GetInstance(Asn1Object.FromByteArray(cert.GetEncoded())));
            certificatesVector.Add(X509CertificateStructure.GetInstance(Asn1Object.FromByteArray(interm.GetEncoded())));

            // Construct SignedData.signerInfos
            Asn1EncodableVector signerInfosVector = new Asn1EncodableVector();

            signerInfosVector.Add(signerInfo.ToAsn1Object());

            // Construct SignedData
            SignedData signedData = new SignedData(
                digestAlgorithms: new DerSet(digestAlgorithmsVector),
                contentInfo: encapContentInfo,
                certificates: new BerSet(certificatesVector),
                crls: null,
                signerInfos: new DerSet(signerInfosVector));

            ContentInfo contentInfo = new ContentInfo(
                contentType: new DerObjectIdentifier(_oidPKCS7IdSignedData),
                content: signedData);

            File.WriteAllBytes(Path.Combine(_settings.PackagePath, _signatureFilename), contentInfo.GetDerEncoded());
        }
Ejemplo n.º 19
0
        public void TestSha1WithRsaEncapsulatedSubjectKeyID()
        {
            MemoryStream bOut = new MemoryStream();

            IX509Store x509Certs = CmsTestUtil.MakeCertStore(OrigCert, SignCert);

            CmsSignedDataStreamGenerator gen = new CmsSignedDataStreamGenerator();

            gen.AddSigner(OrigKP.Private,
                          CmsTestUtil.CreateSubjectKeyId(OrigCert.GetPublicKey()).GetKeyIdentifier(),
                          CmsSignedDataStreamGenerator.DigestSha1);
            gen.AddCertificates(x509Certs);

            byte[] testBytes = Encoding.ASCII.GetBytes(TestMessage);

            Stream sigOut = gen.Open(bOut, true);

            sigOut.Write(testBytes, 0, testBytes.Length);
            sigOut.Close();

            CmsSignedDataParser sp = new CmsSignedDataParser(bOut.ToArray());

            sp.GetSignedContent().Drain();

            VerifySignatures(sp);

            byte[] contentDigest = (byte[])gen.GetGeneratedDigests()[CmsSignedGenerator.DigestSha1];

            ArrayList signers = new ArrayList(sp.GetSignerInfos().GetSigners());

            AttributeTable table = ((SignerInformation)signers[0]).SignedAttributes;

            Asn1.Cms.Attribute hash = table[CmsAttributes.MessageDigest];

            Assert.IsTrue(Arrays.AreEqual(contentDigest, ((Asn1OctetString)hash.AttrValues[0]).GetOctets()));

            //
            // try using existing signer
            //
            gen = new CmsSignedDataStreamGenerator();
            gen.AddSigners(sp.GetSignerInfos());
//			gen.AddCertificatesAndCRLs(sp.GetCertificatesAndCrls("Collection", "BC"));
            gen.AddCertificates(sp.GetCertificates("Collection"));

            bOut.SetLength(0);

            sigOut = gen.Open(bOut, true);
            sigOut.Write(testBytes, 0, testBytes.Length);
            sigOut.Close();

            CmsSignedData sd = new CmsSignedData(new CmsProcessableByteArray(testBytes), bOut.ToArray());

            Assert.AreEqual(1, sd.GetSignerInfos().GetSigners().Count);

            VerifyEncodedData(bOut);
        }
Ejemplo n.º 20
0
        /// <summary>The default constructor for CAdESCertificateSource.</summary>
        /// <remarks>The default constructor for CAdESCertificateSource.</remarks>
        /// <param name="encodedCMS"></param>
        /// <exception cref="Org.Bouncycastle.Cms.CmsException">Org.Bouncycastle.Cms.CmsException
        ///     </exception>
        public CAdESCertificateSource(CmsSignedData cms)
        {
            IEnumerator signers = cms.GetSignerInfos().GetSigners().GetEnumerator();

            signers.MoveNext();

            this.cmsSignedData = cms;
            this.signerId      = ((SignerInformation)signers.Current).SignerID;
            this.onlyExtended  = false;
        }
        public TimeStampToken(
            CmsSignedData signedData)
        {
            this.tsToken = signedData;

            if (!this.tsToken.SignedContentTypeOid.Equals(PkcsObjectIdentifiers.IdCTTstInfo.Id))
            {
                throw new TspValidationException("ContentInfo object not for a time stamp.");
            }

            ICollection signers = tsToken.GetSignerInfos().GetSigners();

            if (signers.Count != 1)
            {
                throw new ArgumentException("Time-stamp token signed by "
                                            + signers.Count
                                            + " signers, but it must contain just the TSA signature.");
            }


            IEnumerator signerEnum = signers.GetEnumerator();

            signerEnum.MoveNext();
            tsaSignerInfo = (SignerInformation)signerEnum.Current;

            try
            {
                CmsProcessable content = tsToken.SignedContent;
                MemoryStream   bOut    = new MemoryStream();

                content.Write(bOut);

                this.tstInfo = new TimeStampTokenInfo(
                    TstInfo.GetInstance(
                        Asn1Object.FromByteArray(bOut.ToArray())));

                Asn1.Cms.Attribute attr = tsaSignerInfo.SignedAttributes[
                    PkcsObjectIdentifiers.IdAASigningCertificate];

                if (attr == null)
                {
                    throw new TspValidationException(
                              "no signing certificate attribute found, time stamp invalid.");
                }

                SigningCertificate signCert = SigningCertificate.GetInstance(
                    attr.AttrValues[0]);

                this.certID = EssCertID.GetInstance(signCert.GetCerts()[0]);
            }
            catch (CmsException e)
            {
                throw new TspException(e.Message, e.InnerException);
            }
        }
Ejemplo n.º 22
0
        private void ReadSignersInfo()
        {
            _nodes = new List <SignerInfoNode>();

            foreach (var signer in _signedData.GetSignerInfos().GetSigners())
            {
                SignerInfoNode node = new SignerInfoNode((SignerInformation)signer, this);

                _nodes.Add(node);
            }
        }
Ejemplo n.º 23
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);
            }
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Retrieves the signatures found in the document
        /// </summary>
        /// <returns>
        /// a list of IAdvancedSignatures for validation purposes
        /// </returns>
        private IList <IAdvancedSignature> GetSignatures(CmsSignedData cmsSignedData)
        {
            var signatures = new List <IAdvancedSignature>();

            foreach (object o in cmsSignedData.GetSignerInfos().GetSigners())
            {
                SignerInformation i    = (SignerInformation)o;
                CAdESSignature    info = new CAdESSignature(cmsSignedData, i);
                signatures.Add(info);
            }
            return(signatures);
        }
        private static byte[] GetRepositoryCountersignatureSignatureValue(SignedCms signedCms)
        {
            var cmsSignedData     = new CmsSignedData(signedCms.Encode());
            var signerInfoStore   = cmsSignedData.GetSignerInfos();
            var primarySignerInfo = GetFirstSignerInfo(signerInfoStore);

            signerInfoStore = primarySignerInfo.GetCounterSignatures();

            var counterSignerInfo = GetFirstSignerInfo(signerInfoStore);

            return(counterSignerInfo.GetSignature());
        }
Ejemplo n.º 26
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());
        }
Ejemplo n.º 27
0
        public override IList <X509Certificate> GetCertificates()
        {
            IList <X509Certificate> list = new AList <X509Certificate>();

            try
            {
                if (!onlyExtended)
                {
                    LOG.Info(cmsSignedData.GetCertificates("Collection").GetMatches(null).Count + " certificate in collection"
                             );
                    //foreach (X509CertificateHolder ch in (ICollection<X509CertificateHolder>)cmsSignedData
                    foreach (X509Certificate ch in cmsSignedData
                             .GetCertificates("Collection").GetMatches(null))
                    {
                        //X509Certificate c = new X509CertificateObject(ch.ToASN1Structure());
                        X509Certificate c = ch;
                        LOG.Info("Certificate for subject " + c.SubjectDN);
                        if (!list.Contains(c))
                        {
                            list.AddItem(c);
                        }
                    }
                }
                // Add certificates in CAdES-XL certificate-values inside SignerInfo attribute if present
                SignerInformation si = cmsSignedData.GetSignerInfos().GetFirstSigner(signerId);
                if (si != null && si.UnsignedAttributes != null && si.UnsignedAttributes[PkcsObjectIdentifiers.IdAAEtsCertValues] != null)
                {
                    DerSequence seq = (DerSequence)si.UnsignedAttributes[PkcsObjectIdentifiers.IdAAEtsCertValues].AttrValues[0];
                    for (int i = 0; i < seq.Count; i++)
                    {
                        X509CertificateStructure cs = X509CertificateStructure.GetInstance(seq[i]);
                        //X509Certificate c = new X509CertificateObject(cs);
                        X509Certificate c = new X509Certificate(cs);
                        if (!list.Contains(c))
                        {
                            list.AddItem(c);
                        }
                    }
                }
            }
            catch (CertificateParsingException e)
            {
                throw new RuntimeException(e);
            }

            /*catch (StoreException e)
             * {
             *      throw new RuntimeException(e);
             * }*/
            return(list);
        }
Ejemplo n.º 28
0
        static void Main(string[] args)
        {
            //if (args.Length > 0)
            //string fullFileName = Path.GetFullPath(args[0]);
            foreach (string fileName in Directory.GetFiles("p7m"))
            {
                FileStream file    = new FileStream(fileName, FileMode.Open);
                bool       isValid = true;
                Console.WriteLine("File to decrypt: " + fileName);
                try
                {
                    CmsSignedData          signedFile  = new CmsSignedData(file);
                    IX509Store             certStore   = signedFile.GetCertificates("Collection");
                    ICollection            certs       = certStore.GetMatches(new X509CertStoreSelector());
                    SignerInformationStore signerStore = signedFile.GetSignerInfos();
                    ICollection            signers     = signerStore.GetSigners();

                    foreach (object tempCertification in certs)
                    {
                        X509Certificate certification = tempCertification as X509Certificate;

                        foreach (object tempSigner in signers)
                        {
                            SignerInformation signer = tempSigner as SignerInformation;
                            if (!signer.Verify(certification.GetPublicKey()))
                            {
                                isValid = false;
                                break;
                            }
                        }
                    }
                    string newFileName = Path.Combine(Directory.CreateDirectory("p7m-extracted").Name, Path.GetFileNameWithoutExtension(fileName));
                    using (var fileStream = new FileStream(newFileName, FileMode.Create, FileAccess.Write))
                    {
                        signedFile.SignedContent.Write(fileStream);
                        Console.WriteLine("File decrypted: " + newFileName);
                    }
                }
                catch (Exception ex)
                {
                    isValid = false;
                }

                Console.WriteLine("File valid: " + isValid);

                ;
            }
            Console.ReadLine();
        }
Ejemplo n.º 29
0
        private static PrimarySignature RemoveUnsignedAttribute(PrimarySignature signature, Func <AttributeTable, AttributeTable> remover)
        {
            var bytes       = signature.GetBytes();
            var signedData  = new CmsSignedData(bytes);
            var signerInfos = signedData.GetSignerInfos();
            var signerInfo  = GetFirstSignerInfo(signerInfos);

            var updatedAttributes  = remover(signerInfo.UnsignedAttributes);
            var updatedSignerInfo  = SignerInformation.ReplaceUnsignedAttributes(signerInfo, updatedAttributes);
            var updatedSignerInfos = new SignerInformationStore(updatedSignerInfo);

            var updatedSignedData = CmsSignedData.ReplaceSigners(signedData, updatedSignerInfos);

            return(PrimarySignature.Load(updatedSignedData.GetEncoded()));
        }
Ejemplo n.º 30
0
        public CAdESCertificateSource(CmsSignedData cms)
        {
            if (cms is null)
            {
                throw new ArgumentNullException(nameof(cms));
            }

            var signers = cms.GetSignerInfos().GetSigners().GetEnumerator();

            signers.MoveNext();

            cmsSignedData = cms;
            signerId      = ((SignerInformation)signers.Current).SignerID;
            onlyExtended  = false;
        }
Ejemplo n.º 31
0
		public void Test4_4()
		{
			byte[] data = GetRfc4134Data("4.4.bin");
			byte[] counterSigCert = GetRfc4134Data("AliceRSASignByCarl.cer");
			CmsSignedData signedData = new CmsSignedData(data);

			VerifySignatures(signedData, sha1);

			VerifySignerInfo4_4(GetFirstSignerInfo(signedData.GetSignerInfos()), counterSigCert);

			CmsSignedDataParser parser = new CmsSignedDataParser(data);

			VerifySignatures(parser);

			VerifySignerInfo4_4(GetFirstSignerInfo(parser.GetSignerInfos()), counterSigCert);
		}
Ejemplo n.º 32
0
		private void VerifySignatures(CmsSignedData s, byte[] contentDigest)
		{
			IX509Store x509Certs = s.GetCertificates("Collection");
			IX509Store x509Crls = s.GetCrls("Collection");
			SignerInformationStore signers = s.GetSignerInfos();

			foreach (SignerInformation signer in signers.GetSigners())
			{
				ICollection certCollection = x509Certs.GetMatches(signer.SignerID);

				IEnumerator certEnum = certCollection.GetEnumerator();

				certEnum.MoveNext();
				X509Certificate cert = (X509Certificate) certEnum.Current;

				VerifySigner(signer, cert);

				if (contentDigest != null)
				{
					Assert.IsTrue(Arrays.AreEqual(contentDigest, signer.GetContentDigest()));
				}
			}

			ICollection certColl = x509Certs.GetMatches(null);
			ICollection crlColl = x509Crls.GetMatches(null);

			Assert.AreEqual(certColl.Count, s.GetCertificates("Collection").GetMatches(null).Count);
			Assert.AreEqual(crlColl.Count, s.GetCrls("Collection").GetMatches(null).Count);
		}