Inheritance: CmsProcessable, CmsReadable
        private void SubjectKeyIDTest(
			IAsymmetricCipherKeyPair	signaturePair,
			X509Certificate			signatureCert,
			string					digestAlgorithm)
        {
            IList certList = new ArrayList();
            IList crlList = new ArrayList();
            CmsProcessable msg = new CmsProcessableByteArray(Encoding.ASCII.GetBytes("Hello World!"));

            certList.Add(signatureCert);
            certList.Add(OrigCert);

            crlList.Add(SignCrl);

            IX509Store x509Certs = X509StoreFactory.Create(
                "Certificate/Collection",
                new X509CollectionStoreParameters(certList));
            IX509Store x509Crls = X509StoreFactory.Create(
                "CRL/Collection",
                new X509CollectionStoreParameters(crlList));

            CmsSignedDataGenerator gen = new CmsSignedDataGenerator();

            gen.AddSigner(signaturePair.Private,
                CmsTestUtil.CreateSubjectKeyId(signatureCert.GetPublicKey()).GetKeyIdentifier(),
                digestAlgorithm);

            gen.AddCertificates(x509Certs);
            gen.AddCrls(x509Crls);

            CmsSignedData s = gen.Generate(msg, true);

            Assert.AreEqual(3, s.Version);

            MemoryStream bIn = new MemoryStream(s.GetEncoded(), false);
            Asn1InputStream aIn = new Asn1InputStream(bIn);

            s = new CmsSignedData(ContentInfo.GetInstance(aIn.ReadObject()));

            x509Certs = s.GetCertificates("Collection");
            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;

                Assert.IsTrue(signer.Verify(cert));
            }

            //
            // check for CRLs
            //
            ArrayList crls = new ArrayList(x509Crls.GetMatches(null));

            Assert.AreEqual(1, crls.Count);

            Assert.IsTrue(crls.Contains(SignCrl));

            //
            // try using existing signer
            //

            gen = new CmsSignedDataGenerator();

            gen.AddSigners(s.GetSignerInfos());

            gen.AddCertificates(s.GetCertificates("Collection"));
            gen.AddCrls(s.GetCrls("Collection"));

            s = gen.Generate(msg, true);

            bIn = new MemoryStream(s.GetEncoded(), false);
            aIn = new Asn1InputStream(bIn);

            s = new CmsSignedData(ContentInfo.GetInstance(aIn.ReadObject()));

            x509Certs = s.GetCertificates("Collection");
            x509Crls = s.GetCrls("Collection");

            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;

                Assert.IsTrue(signer.Verify(cert));
            }

            CheckSignerStoreReplacement(s, signers);
        }
示例#2
1
		private void EncapsulatedTest(
			AsymmetricCipherKeyPair	signaturePair,
			X509Certificate			signatureCert,
			string					digestAlgorithm)
		{
			CmsProcessable msg = new CmsProcessableByteArray(Encoding.ASCII.GetBytes("Hello World!"));

            IX509Store x509Certs = CmsTestUtil.MakeCertStore(signatureCert, OrigCert);
            IX509Store x509Crls = CmsTestUtil.MakeCrlStore(SignCrl);

            CmsSignedDataGenerator gen = new CmsSignedDataGenerator();
			gen.AddSigner(signaturePair.Private, signatureCert, digestAlgorithm);
			gen.AddCertificates(x509Certs);
			gen.AddCrls(x509Crls);

			CmsSignedData s = gen.Generate(msg, true);

			s = new CmsSignedData(ContentInfo.GetInstance(Asn1Object.FromByteArray(s.GetEncoded())));

			x509Certs = s.GetCertificates("Collection");
			x509Crls = s.GetCrls("Collection");

			SignerInformationStore signers = s.GetSignerInfos();
			ICollection c = signers.GetSigners();

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

				IEnumerator certEnum = certCollection.GetEnumerator();

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

                Assert.AreEqual(digestAlgorithm, signer.DigestAlgOid);

				Assert.IsTrue(signer.Verify(cert));
			}

			//
			// check for CRLs
			//
			ArrayList crls = new ArrayList(x509Crls.GetMatches(null));

			Assert.AreEqual(1, crls.Count);

			Assert.IsTrue(crls.Contains(SignCrl));

			//
			// try using existing signer
			//

			gen = new CmsSignedDataGenerator();

			gen.AddSigners(s.GetSignerInfos());

			gen.AddCertificates(s.GetCertificates("Collection"));
			gen.AddCrls(s.GetCrls("Collection"));

			s = gen.Generate(msg, true);

			s = new CmsSignedData(ContentInfo.GetInstance(Asn1Object.FromByteArray(s.GetEncoded())));

			x509Certs = s.GetCertificates("Collection");
			x509Crls = s.GetCrls("Collection");

			signers = s.GetSignerInfos();
			c = signers.GetSigners();

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

				IEnumerator certEnum = certCollection.GetEnumerator();

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

				Assert.IsTrue(signer.Verify(cert));
			}

			CheckSignerStoreReplacement(s, signers);
		}
示例#3
0
        public CmsAuthenticatedData(
            ContentInfo contentInfo)
        {
            this.contentInfo = contentInfo;

            AuthenticatedData authData = AuthenticatedData.GetInstance(contentInfo.Content);

            //
            // read the recipients
            //
            Asn1Set recipientInfos = authData.RecipientInfos;

            this.macAlg = authData.MacAlgorithm;

            //
            // read the authenticated content info
            //
            ContentInfo encInfo  = authData.EncapsulatedContentInfo;
            CmsReadable readable = new CmsProcessableByteArray(
                Asn1OctetString.GetInstance(encInfo.Content).GetOctets());
            CmsSecureReadable secureReadable = new CmsEnvelopedHelper.CmsAuthenticatedSecureReadable(
                this.macAlg, readable);

            //
            // build the RecipientInformationStore
            //
            this.recipientInfoStore = CmsEnvelopedHelper.BuildRecipientInformationStore(
                recipientInfos, secureReadable);

            this.authAttrs   = authData.AuthAttrs;
            this.mac         = authData.Mac.GetOctets();
            this.unauthAttrs = authData.UnauthAttrs;
        }
示例#4
0
        public CmsEnvelopedData(
            ContentInfo contentInfo)
        {
            this.contentInfo = contentInfo;

            EnvelopedData envData = EnvelopedData.GetInstance(contentInfo.Content);

            //
            // read the recipients
            //
            Asn1Set recipientInfos = envData.RecipientInfos;

            //
            // read the encrypted content info
            //
            EncryptedContentInfo encInfo = envData.EncryptedContentInfo;

            this.encAlg = encInfo.ContentEncryptionAlgorithm;
            CmsReadable       readable       = new CmsProcessableByteArray(encInfo.EncryptedContent.GetOctets());
            CmsSecureReadable secureReadable = new CmsEnvelopedHelper.CmsEnvelopedSecureReadable(
                this.encAlg, readable);

            //
            // build the RecipientInformationStore
            //
            this.recipientInfoStore = CmsEnvelopedHelper.BuildRecipientInformationStore(
                recipientInfos, secureReadable);

            this.unprotectedAttributes = envData.UnprotectedAttrs;
        }
		public CmsAuthenticatedData(
			ContentInfo contentInfo)
		{
			this.contentInfo = contentInfo;

			AuthenticatedData authData = AuthenticatedData.GetInstance(contentInfo.Content);

			//
			// read the recipients
			//
			Asn1Set recipientInfos = authData.RecipientInfos;

			this.macAlg = authData.MacAlgorithm;

			//
			// read the authenticated content info
			//
			ContentInfo encInfo = authData.EncapsulatedContentInfo;
			CmsReadable readable = new CmsProcessableByteArray(
				Asn1OctetString.GetInstance(encInfo.Content).GetOctets());
			CmsSecureReadable secureReadable = new CmsEnvelopedHelper.CmsAuthenticatedSecureReadable(
				this.macAlg, readable);

			//
			// build the RecipientInformationStore
			//
			this.recipientInfoStore = CmsEnvelopedHelper.BuildRecipientInformationStore(
				recipientInfos, secureReadable);

			this.authAttrs = authData.AuthAttrs;
			this.mac = authData.Mac.GetOctets();
			this.unauthAttrs = authData.UnauthAttrs;
		}
        public CmsEnvelopedData(
            ContentInfo contentInfo)
        {
            this.contentInfo = contentInfo;

			EnvelopedData envData = EnvelopedData.GetInstance(contentInfo.Content);

			//
			// read the recipients
			//
			Asn1Set recipientInfos = envData.RecipientInfos;

			//
			// read the encrypted content info
			//
			EncryptedContentInfo encInfo = envData.EncryptedContentInfo;
			this.encAlg = encInfo.ContentEncryptionAlgorithm;
			CmsReadable readable = new CmsProcessableByteArray(encInfo.EncryptedContent.GetOctets());
			CmsSecureReadable secureReadable = new CmsEnvelopedHelper.CmsEnvelopedSecureReadable(
				this.encAlg, readable);

			//
			// build the RecipientInformationStore
			//
			this.recipientInfoStore = CmsEnvelopedHelper.BuildRecipientInformationStore(
				recipientInfos, secureReadable);

			this.unprotectedAttributes = envData.UnprotectedAttrs;
        }
示例#7
0
 /// <summary>
 /// Verschlüsselt die Daten mit dem angegebenen Empfänger-Zertifikat
 /// </summary>
 /// <param name="data">Die zu verschlüsselnden Daten</param>
 /// <param name="cert">Das Empfänger-Zertifikat</param>
 /// <returns>Die verschlüsselten Daten</returns>
 public static byte[] EncryptData(byte[] data, X509Certificate cert)
 {
     var gen = new CmsEnvelopedDataGenerator();
     gen.AddKeyTransRecipient(cert);
     var message = new CmsProcessableByteArray(data);
     var envelopedData = gen.Generate(message, PkcsObjectIdentifiers.DesEde3Cbc.Id);
     var encryptedData = envelopedData.GetEncoded();
     return encryptedData;
 }
示例#8
0
 /// <summary>
 /// Signiert die Daten mit dem angegebenen Absender-Zertifikat
 /// </summary>
 /// <param name="data">Die zu signierenden Daten</param>
 /// <param name="privateKey">Der private Schlüssel mit dem signiert werden soll (passend zum Zeritifikat <paramref name="cert"/>)</param>
 /// <param name="cert">Das Absender-Zertifikat</param>
 /// <param name="certs">Die Zertifikate, die zusätzlich im Ergebnis gespeichert werden sollen (z.B. für eine Zertifkatskette)</param>
 /// <returns>Die signierten Daten</returns>
 public static byte[] SignData(byte[] data, AsymmetricKeyParameter privateKey, X509Certificate cert, IEnumerable<X509Certificate> certs = null)
 {
     var gen = new CmsSignedDataGenerator();
     var allCerts = new List<X509Certificate>();
     if (certs != null)
         allCerts.AddRange(certs);
     var storeParams = new X509CollectionStoreParameters(allCerts);
     var certStore = X509StoreFactory.Create("Certificate/Collection", storeParams);
     gen.AddCertificates(certStore);
     gen.AddSigner(privateKey, cert, NistObjectIdentifiers.IdSha256.Id);
     var message = new CmsProcessableByteArray(data);
     var signedData = gen.Generate(message, true);
     return signedData.GetEncoded();
 }
示例#9
0
        public CmsEnvelopedData(ContentInfo contentInfo)
        {
            this.contentInfo = contentInfo;
            EnvelopedData        instance             = EnvelopedData.GetInstance(contentInfo.Content);
            Asn1Set              recipientInfos       = instance.RecipientInfos;
            EncryptedContentInfo encryptedContentInfo = instance.EncryptedContentInfo;

            encAlg = encryptedContentInfo.ContentEncryptionAlgorithm;
            CmsReadable       readable       = new CmsProcessableByteArray(encryptedContentInfo.EncryptedContent.GetOctets());
            CmsSecureReadable secureReadable = new CmsEnvelopedHelper.CmsEnvelopedSecureReadable(encAlg, readable);

            recipientInfoStore    = CmsEnvelopedHelper.BuildRecipientInformationStore(recipientInfos, secureReadable);
            unprotectedAttributes = instance.UnprotectedAttrs;
        }
示例#10
0
        public CmsAuthenticatedData(ContentInfo contentInfo)
        {
            this.contentInfo = contentInfo;
            AuthenticatedData instance       = AuthenticatedData.GetInstance(contentInfo.Content);
            Asn1Set           recipientInfos = instance.RecipientInfos;

            this.macAlg = instance.MacAlgorithm;
            ContentInfo       encapsulatedContentInfo = instance.EncapsulatedContentInfo;
            CmsReadable       readable       = new CmsProcessableByteArray(Asn1OctetString.GetInstance(encapsulatedContentInfo.Content).GetOctets());
            CmsSecureReadable secureReadable = new CmsEnvelopedHelper.CmsAuthenticatedSecureReadable(this.macAlg, readable);

            this.recipientInfoStore = CmsEnvelopedHelper.BuildRecipientInformationStore(recipientInfos, secureReadable);
            this.authAttrs          = instance.AuthAttrs;
            this.mac         = instance.Mac.GetOctets();
            this.unauthAttrs = instance.UnauthAttrs;
        }
        public CmsSigner(System.Security.Cryptography.X509Certificates.X509Certificate2 cert)
        {
            byte[]         data = null;
            CmsProcessable msg  = new Org.BouncyCastle.Cms.CmsProcessableByteArray(data);

            CmsSignedDataGenerator gen = new CmsSignedDataGenerator();
            var sha1Signer             = Org.BouncyCastle.Security.SignerUtilities.GetSigner("SHA1withRSA");

            /*
             * new
             *
             * gen.AddSignerInfoGenerator(new SignerInfoGeneratorBuilder()
             *  .Build(sha1Signer, null);
             */
            // gen.AddCertificates(certs);
            gen.Generate(msg, false);
        }
示例#12
0
        public CmsEnvelopedData(
            ContentInfo contentInfo)
        {
            this.contentInfo = contentInfo;

            try
            {
                EnvelopedData envData = EnvelopedData.GetInstance(contentInfo.Content);

                if (envData.OriginatorInfo != null)
                {
                    originatorInfo = new OriginatorInformation(envData.OriginatorInfo);
                }

                //
                // read the recipients
                //
                Asn1Set recipientInfos = envData.RecipientInfos;

                //
                // read the encrypted content info
                //
                EncryptedContentInfo encInfo = envData.EncryptedContentInfo;
                this.encAlg = encInfo.ContentEncryptionAlgorithm;
                CmsReadable        readable       = new CmsProcessableByteArray(encInfo.EncryptedContent.GetOctets());
                ICmsSecureReadable secureReadable = new CmsEnvelopedHelper.CmsEnvelopedSecureReadable(
                    this.encAlg, readable);

                //
                // build the RecipientInformationStore
                //
                this.recipientInfoStore = CmsEnvelopedHelper.BuildRecipientInformationStore(
                    recipientInfos, this.encAlg, secureReadable);

                this.unprotectedAttributes = envData.UnprotectedAttrs;
            }
            catch (Exception e)
            {
                throw new CmsException("malformed content", e);
            }
        }
        // https://www.bouncycastle.org/docs/pkixdocs1.5on/org/bouncycastle/cms/CMSSignedDataGenerator.html
        private void SignInternal(
            System.Security.Cryptography.X509Certificates.X509Certificate2 certificate
            , byte[] data)
        {
            // https://stackoverflow.com/questions/3240222/get-private-key-from-bouncycastle-x509-certificate-c-sharp
            // Org.BouncyCastle.X509.X509Certificate c = FromX509Certificate(certificate);
            //var algorithm = LumiSoft.Net.X509.DigestAlgorithms.GetDigest(c.SigAlgOid);
            //var signature = new LumiSoft.Net.X509.X509Certificate2Signature(this.m_certificate, algorithm);
            //signature.Sign(data);


            CmsProcessable msg = new Org.BouncyCastle.Cms.CmsProcessableByteArray(data);

            CmsSignedDataGenerator gen = new CmsSignedDataGenerator();

            Org.BouncyCastle.Security.SecureRandom random = new Org.BouncyCastle.Security.SecureRandom();

            Org.BouncyCastle.X509.X509Certificate           c          = FromX509Certificate(certificate);
            Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair issuerKeys = GetKeyPair(certificate.PrivateKey);
            string signatureAlgo = certificate.PrivateKey is RSA ? "SHA1withRSA" : certificate.PrivateKey is DSA ? "SHA1withDSA" : null;

            // var sha1Signer = Org.BouncyCastle.Security.SignerUtilities.GetSigner("SHA1withRSA");



            // https://stackoverflow.com/questions/3240222/get-private-key-from-bouncycastle-x509-certificate-c-sharp

            // https://stackoverflow.com/questions/36712679/bouncy-castles-x509v3certificategenerator-setsignaturealgorithm-marked-obsolete
            Org.BouncyCastle.Crypto.ISignatureFactory signatureFactory =
                new Org.BouncyCastle.Crypto.Operators.Asn1SignatureFactory
                    (signatureAlgo, issuerKeys.Private, random);

            // gen.AddCertificates(certs);
            gen.AddSignerInfoGenerator(new SignerInfoGeneratorBuilder()
                                       .Build(signatureFactory, c)
                                       );

            this.m_signedData = gen.Generate(msg, false);
        }
示例#14
0
文件: Bundler.cs 项目: DM-TOR/nhin-d
        /// <summary>
        /// Create a trust bundle.
        /// </summary>
        public byte[] Create(IResourceProvider bundleResources)
        {
            CmsSignedData s;
            var validMetadata = ValidMetaData(bundleResources.Metadata);

            IList certs = bundleResources.LoadCertificates();
            IX509Store x509Certs = X509StoreFactory.Create("Certificate/Collection", new X509CollectionStoreParameters(certs));
            CmsSignedDataGenerator gen = new CmsSignedDataGenerator();
            gen.AddCertificates(x509Certs);
            
            if (!string.IsNullOrEmpty(validMetadata))
            {
                byte[] metadataBytes = Encoding.ASCII.GetBytes(validMetadata);
                CmsProcessable msg = new CmsProcessableByteArray(metadataBytes);
                s = gen.Generate(CmsSignedGenerator.Data, msg, true);
            }
            else{ 
                s = gen.Generate(CmsSignedGenerator.Data, null, false);
            }
            
            var p7BData = s.GetEncoded();
            return p7BData;
        }
        public static string SignCmsGost2012(string data, string tlsNumber, int pin, byte[] rawCertificate, byte[] key)
        {
            var requestBytes = Encoding.UTF8.GetBytes(data);
            var typedData    = new CmsProcessableByteArray(requestBytes);
            var gen          = new CmsSignedDataGenerator();
            var signerInfoGeneratorBuilder = new SignerInfoGeneratorBuilder();

            var attrs      = GetSigningParameters(tlsNumber, pin);
            var parameters = new DefaultSignedAttributeTableGenerator(attrs);

            signerInfoGeneratorBuilder.WithSignedAttributeGenerator(parameters);

            var factory = new Asn1SignatureFactory(SingingAlgorithm, GetKey(key));

            var bcCertificate = GetBankCertificate(rawCertificate);

            gen.AddSignerInfoGenerator(signerInfoGeneratorBuilder.Build(factory, bcCertificate));
            gen.AddCertificates(MakeCertStore(bcCertificate));

            var signed      = gen.Generate(typedData, false);
            var signedBytes = signed.GetEncoded();

            return(Convert.ToBase64String(signedBytes));
        }
示例#16
0
        public byte[] Sign(byte[] cmsData)
        {
            IList certs = new List<X509Certificate>();

            byte[] signBytes = File.ReadAllBytes(GetFile());
            X509Certificate2 signCert = new X509Certificate2(signBytes, Key, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable);
            certs.Add(DotNetUtilities.FromX509Certificate(signCert));
            IX509Store x509Certs = X509StoreFactory.Create("Certificate/Collection", new X509CollectionStoreParameters(certs));

            CmsSignedDataGenerator gen = new CmsSignedDataGenerator();
            AsymmetricCipherKeyPair pair = DotNetUtilities.GetKeyPair(signCert.PrivateKey);
            X509Certificate bX509Certificate = DotNetUtilities.FromX509Certificate(signCert);
            gen.AddSigner(pair.Private, bX509Certificate, CmsSignedGenerator.DigestSha1);
            gen.AddSigner(pair.Private, bX509Certificate, CmsSignedGenerator.DigestSha256);
            CmsSignedData unsignedData = new CmsSignedData(cmsData);

            
            gen.AddCertificates(x509Certs);
            CmsProcessable msg = new CmsProcessableByteArray(unsignedData.GetEncoded());
            CmsSignedData cmsSignedData = gen.Generate(CmsSignedGenerator.Data, msg, true);
            
            byte[] p7MData = cmsSignedData.GetEncoded();
            return p7MData;
        }
        public void TestWithAttributeCertificate()
        {
            IList certList = new ArrayList();
            CmsProcessable msg = new CmsProcessableByteArray(Encoding.ASCII.GetBytes("Hello World!"));

            certList.Add(SignDsaCert);

            IX509Store x509Certs = X509StoreFactory.Create(
                "Certificate/Collection",
                new X509CollectionStoreParameters(certList));

            CmsSignedDataGenerator gen = new CmsSignedDataGenerator();

            gen.AddSigner(OrigKP.Private, OrigCert, CmsSignedDataGenerator.DigestSha1);

            gen.AddCertificates(x509Certs);

            IX509AttributeCertificate attrCert = CmsTestUtil.GetAttributeCertificate();

            ArrayList attrCerts = new ArrayList();
            attrCerts.Add(attrCert);

            IX509Store store = X509StoreFactory.Create(
                "AttributeCertificate/Collection",
                new X509CollectionStoreParameters(attrCerts));

            gen.AddAttributeCertificates(store);

            CmsSignedData sd = gen.Generate(msg);

            Assert.AreEqual(4, sd.Version);

            store = sd.GetAttributeCertificates("Collection");

            ArrayList coll = new ArrayList(store.GetMatches(null));

            Assert.AreEqual(1, coll.Count);

            Assert.IsTrue(coll.Contains(attrCert));

            //
            // create new certstore
            //
            certList = new ArrayList();
            certList.Add(OrigCert);
            certList.Add(SignCert);

            x509Certs = X509StoreFactory.Create(
                "Certificate/Collection",
                new X509CollectionStoreParameters(certList));

            //
            // replace certs
            //
            sd = CmsSignedData.ReplaceCertificatesAndCrls(sd, x509Certs, null, null);

            VerifySignatures(sd);
        }
        public void TestSignerStoreReplacement()
        {
            IList certList = new ArrayList();
            CmsProcessable msg = new CmsProcessableByteArray(Encoding.ASCII.GetBytes("Hello World!"));

            certList.Add(OrigCert);
            certList.Add(SignCert);

            IX509Store x509Certs = X509StoreFactory.Create(
                "Certificate/Collection",
                new X509CollectionStoreParameters(certList));

            CmsSignedDataGenerator gen = new CmsSignedDataGenerator();

            gen.AddSigner(OrigKP.Private, OrigCert, CmsSignedDataGenerator.DigestSha1);

            gen.AddCertificates(x509Certs);

            CmsSignedData original = gen.Generate(msg, true);

            //
            // create new Signer
            //
            gen = new CmsSignedDataGenerator();

            gen.AddSigner(OrigKP.Private, OrigCert, CmsSignedDataGenerator.DigestSha224);

            gen.AddCertificates(x509Certs);

            CmsSignedData newSD = gen.Generate(msg, true);

            //
            // replace signer
            //
            CmsSignedData sd = CmsSignedData.ReplaceSigners(original, newSD.GetSignerInfos());

            IEnumerator signerEnum = sd.GetSignerInfos().GetSigners().GetEnumerator();
            signerEnum.MoveNext();
            SignerInformation signer = (SignerInformation) signerEnum.Current;

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

            // we use a parser here as it requires the digests to be correct in the digest set, if it
            // isn't we'll get a NullPointerException
            CmsSignedDataParser sp = new CmsSignedDataParser(sd.GetEncoded());

            sp.GetSignedContent().Drain();

            VerifySignatures(sp);
        }
示例#19
0
        private void SignManigestFile(PassGeneratorRequest request, string manifestFileAndPath)
        {
            byte[] dataToSign = File.ReadAllBytes(manifestFileAndPath);

            X509Certificate2 card = GetCertificate(request);
            Org.BouncyCastle.X509.X509Certificate cert = DotNetUtilities.FromX509Certificate(card);
            Org.BouncyCastle.Crypto.AsymmetricKeyParameter privateKey = DotNetUtilities.GetKeyPair(card.PrivateKey).Private;

            X509Certificate2 appleCA = GetAppleCertificate();
            Org.BouncyCastle.X509.X509Certificate appleCert = DotNetUtilities.FromX509Certificate(appleCA);

            ArrayList intermediateCerts = new ArrayList();

            intermediateCerts.Add(appleCert);
            intermediateCerts.Add(cert);

            Org.BouncyCastle.X509.Store.X509CollectionStoreParameters PP = new Org.BouncyCastle.X509.Store.X509CollectionStoreParameters(intermediateCerts);
            Org.BouncyCastle.X509.Store.IX509Store st1 = Org.BouncyCastle.X509.Store.X509StoreFactory.Create("CERTIFICATE/COLLECTION", PP);

            CmsSignedDataGenerator generator = new CmsSignedDataGenerator();

            generator.AddSigner(privateKey, cert, CmsSignedDataGenerator.DigestSha1);
            generator.AddCertificates(st1);

            CmsProcessable content = new CmsProcessableByteArray(dataToSign);
            CmsSignedData signedData = generator.Generate(content, false);

            string outputDirectory = Path.GetDirectoryName(manifestFileAndPath);
            string signatureFileAndPath = Path.Combine(outputDirectory, "signature");

            File.WriteAllBytes(signatureFileAndPath, signedData.GetEncoded());
        }
        public static byte[] PostSign(String digestAlgorithmName,
            byte[] content,
            X509Certificate2[] signerCertificateChain,
            byte[] signature,
            byte[] signedAttributes)
        {
            if (signerCertificateChain == null || signerCertificateChain.Length == 0)
            {
                throw new ArgumentException("La cadena de certificados debe contener al menos una entrada");
            }

            TbsCertificateStructure tbsCertificateStructure;

            //TODO Revisar esta parte del código
            /**
             *
             *  Revisar esta parte del código
             *
             */
            tbsCertificateStructure = TbsCertificateStructure.GetInstance(
                Asn1Object.FromByteArray(
                new Org.BouncyCastle.X509.X509Certificate(
                    X509CertificateStructure.GetInstance(Asn1Object.FromByteArray(signerCertificateChain[0].GetRawCertData()))).GetTbsCertificate()
                    )
                    );

            SignerIdentifier signerIdentifier = new SignerIdentifier(
              new IssuerAndSerialNumber(X509Name.GetInstance(tbsCertificateStructure.Issuer), tbsCertificateStructure.SerialNumber)
               );

            // Algoritmo de huella digital
            AlgorithmIdentifier digestAlgorithmOID;
            digestAlgorithmOID = SigUtils.MakeAlgId(AOAlgorithmID.GetOID(digestAlgorithmName));

            // EncryptionAlgorithm
            AlgorithmIdentifier keyAlgorithmIdentifier;
            keyAlgorithmIdentifier = SigUtils.MakeAlgId(AOAlgorithmID.GetOID("RSA"));

            // Firma PKCS#1 codificada
            Asn1OctetString encodedPKCS1Signature = new DerOctetString(signature);

            // Atributos firmados
            Asn1Set asn1SignedAttributes;
            asn1SignedAttributes = (Asn1Set) Asn1Object.FromByteArray(signedAttributes);

            // SignerInfo
            Asn1EncodableVector signerInfo = new Asn1EncodableVector();
            signerInfo.Add(new SignerInfo(signerIdentifier, digestAlgorithmOID, asn1SignedAttributes, keyAlgorithmIdentifier, encodedPKCS1Signature, null));

            // ContentInfo
            ContentInfo contentInfo;
            if (content != null)
            {
                MemoryStream baos = new MemoryStream();
                CmsProcessable msg = new CmsProcessableByteArray(content);
                msg.Write(baos);

                contentInfo = new ContentInfo(new DerObjectIdentifier(Org.BouncyCastle.Asn1.Pkcs.PkcsObjectIdentifiers.Data.Id), new BerOctetString(baos.ToArray()));
            }
            else
            {
                contentInfo = new ContentInfo(new DerObjectIdentifier(Org.BouncyCastle.Asn1.Pkcs.PkcsObjectIdentifiers.Data.Id), null);
            }

            // Certificados
            List<Asn1Encodable> ce = new List<Asn1Encodable>();
            foreach (X509Certificate2 cert in signerCertificateChain)
            {
                /**
                 *
                 *  Revisar el uso que hacemos de X509CertificateStructure
                 *  ya que puede ser un posible punto de errores
                 *
                 */
                ce.Add(X509CertificateStructure.GetInstance(Asn1Object.FromByteArray(cert.GetRawCertData())));

            }
            Asn1Set certificates = SigUtils.CreateBerSetFromList(ce);

            // Algoritmos de huella digital
            Asn1EncodableVector digestAlgorithms = new Asn1EncodableVector();
            digestAlgorithms.Add(digestAlgorithmOID);

            return new ContentInfo(
               Org.BouncyCastle.Asn1.Pkcs.PkcsObjectIdentifiers.SignedData,
               new SignedData(
                  new DerSet(digestAlgorithms),
                  contentInfo,
                  certificates,
                  null,
                  new DerSet(signerInfo)
               )
            ).GetEncoded("DER");
        }
        private void SignManigestFile(PassGeneratorRequest request)
        {
            X509Certificate2 card = GetCertificate(request);

            if (card == null)
            {
                throw new FileNotFoundException("Certificate could not be found. Please ensure the thumbprint and cert location values are correct.");
            }

            Org.BouncyCastle.X509.X509Certificate cert = DotNetUtilities.FromX509Certificate(card);
            Org.BouncyCastle.Crypto.AsymmetricKeyParameter privateKey = DotNetUtilities.GetKeyPair(card.PrivateKey).Private;

            X509Certificate2 appleCA = GetAppleCertificate(request);
            Org.BouncyCastle.X509.X509Certificate appleCert = DotNetUtilities.FromX509Certificate(appleCA);

            ArrayList intermediateCerts = new ArrayList();

            intermediateCerts.Add(appleCert);
            intermediateCerts.Add(cert);

            Org.BouncyCastle.X509.Store.X509CollectionStoreParameters PP = new Org.BouncyCastle.X509.Store.X509CollectionStoreParameters(intermediateCerts);
            Org.BouncyCastle.X509.Store.IX509Store st1 = Org.BouncyCastle.X509.Store.X509StoreFactory.Create("CERTIFICATE/COLLECTION", PP);

            CmsSignedDataGenerator generator = new CmsSignedDataGenerator();

            generator.AddSigner(privateKey, cert, CmsSignedDataGenerator.DigestSha1);
            generator.AddCertificates(st1);

            CmsProcessable content = new CmsProcessableByteArray(manifestFile);
            CmsSignedData signedData = generator.Generate(content, false);

            signatureFile = signedData.GetEncoded();
        }
示例#22
0
		public void TestDetachedVerification()
		{
			byte[] data = Encoding.ASCII.GetBytes("Hello World!");
			CmsProcessable msg = new CmsProcessableByteArray(data);

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

            CmsSignedDataGenerator gen = new CmsSignedDataGenerator();
			gen.AddSigner(OrigKP.Private, OrigCert, CmsSignedDataGenerator.DigestSha1);
			gen.AddSigner(OrigKP.Private, OrigCert, CmsSignedDataGenerator.DigestMD5);
			gen.AddCertificates(x509Certs);

            CmsSignedData s = gen.Generate(msg);

			IDictionary hashes = new Hashtable();
			hashes.Add(CmsSignedDataGenerator.DigestSha1, DigestUtilities.CalculateDigest("SHA1", data));
            hashes.Add(CmsSignedDataGenerator.DigestMD5, DigestUtilities.CalculateDigest("MD5", data));

			s = new CmsSignedData(hashes, s.GetEncoded());

			VerifySignatures(s, null);
		}
        public void TestCertOrdering2()
        {
            IList certList = new ArrayList();
            CmsProcessable msg = new CmsProcessableByteArray(Encoding.ASCII.GetBytes("Hello World!"));

            certList.Add(SignCert);
            certList.Add(SignDsaCert);
            certList.Add(OrigCert);

            IX509Store x509Certs = X509StoreFactory.Create(
                "Certificate/Collection",
                new X509CollectionStoreParameters(certList));

            CmsSignedDataGenerator gen = new CmsSignedDataGenerator();

            gen.AddSigner(OrigKP.Private, OrigCert, CmsSignedDataGenerator.DigestSha1);

            gen.AddCertificates(x509Certs);

            CmsSignedData sd = gen.Generate(msg, true);

            x509Certs = sd.GetCertificates("Collection");
            ArrayList a = new ArrayList(x509Certs.GetMatches(null));

            Assert.AreEqual(3, a.Count);
            Assert.AreEqual(SignCert, a[0]);
            Assert.AreEqual(SignDsaCert, a[1]);
            Assert.AreEqual(OrigCert, a[2]);
        }
示例#24
0
        /// <exception cref="System.IO.IOException"></exception>
        public virtual Stream ToBeSigned(Document document, SignatureParameters parameters
            )
        {
            if (parameters.SignaturePackaging != SignaturePackaging.ENVELOPING && parameters
                .SignaturePackaging != SignaturePackaging.DETACHED)
            {
                throw new ArgumentException("Unsupported signature packaging " + parameters.SignaturePackaging);
            }
            //jbonilla - No aplica para C#
            //SignatureInterceptorProvider provider = new SignatureInterceptorProvider();
            //Security.AddProvider(provider);
            //string jsAlgorithm = parameters.GetSignatureAlgorithm().GetJavaSignatureAlgorithm
            //    (parameters.GetDigestAlgorithm());
            //PreComputedContentSigner contentSigner = new PreComputedContentSigner(jsAlgorithm
            //    );
            PreComputedSigner signer = new PreComputedSigner();
            //CmsSignedDataGenerator generator = CreateCMSSignedDataGenerator(contentSigner, digestCalculatorProvider
            //    , parameters, GetSigningProfile(parameters), false, null);
            CmsSignedDataGenerator generator = CreateCMSSignedDataGenerator
                (signer, parameters, GetSigningProfile(parameters), false, null);

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

                //jbonilla - El ISigner devuelve el mismo hash sin firmar para permitir
                //la generación de la firma por un medio externo, como un token.
                /*return new ByteArrayInputStream(contentSigner.GetByteOutputStream().ToByteArray());*/
                return new MemoryStream(signer.CurrentSignature());
            }
            catch (CmsException e)
            {
                throw new IOException("CmsException", e);
            }
        }
        public void TestSha1WithRsaAndAttributeTable()
        {
            byte[] testBytes = Encoding.ASCII.GetBytes("Hello world!");

            IList certList = new ArrayList();
            CmsProcessable msg = new CmsProcessableByteArray(testBytes);

            certList.Add(OrigCert);
            certList.Add(SignCert);

            IX509Store x509Certs = X509StoreFactory.Create(
                "Certificate/Collection",
                new X509CollectionStoreParameters(certList));

            CmsSignedDataGenerator gen = new CmsSignedDataGenerator();

            IDigest md = DigestUtilities.GetDigest("SHA1");
            md.BlockUpdate(testBytes, 0, testBytes.Length);
            byte[] hash = DigestUtilities.DoFinal(md);

            Asn1.Cms.Attribute attr = new Asn1.Cms.Attribute(CmsAttributes.MessageDigest,
                new DerSet(new DerOctetString(hash)));

            Asn1EncodableVector v = new Asn1EncodableVector(attr);

            gen.AddSigner(OrigKP.Private, OrigCert, CmsSignedDataGenerator.DigestSha1,
                new AttributeTable(v), null);

            gen.AddCertificates(x509Certs);

            CmsSignedData s = gen.Generate(CmsSignedDataGenerator.Data, null, false);

            //
            // the signature is detached, so need to add msg before passing on
            //
            s = new CmsSignedData(msg, s.GetEncoded());

            //
            // compute expected content digest
            //
            VerifySignatures(s, hash);
        }
        public void TestEncapsulatedCertStoreReplacement()
        {
            IList certList = new ArrayList();
            CmsProcessable msg = new CmsProcessableByteArray(Encoding.ASCII.GetBytes("Hello World!"));

            certList.Add(SignDsaCert);

            IX509Store x509Certs = X509StoreFactory.Create(
                "Certificate/Collection",
                new X509CollectionStoreParameters(certList));

            CmsSignedDataGenerator gen = new CmsSignedDataGenerator();

            gen.AddSigner(OrigKP.Private, OrigCert, CmsSignedDataGenerator.DigestSha1);

            gen.AddCertificates(x509Certs);

            CmsSignedData sd = gen.Generate(msg, true);

            //
            // create new certstore
            //
            certList = new ArrayList();
            certList.Add(OrigCert);
            certList.Add(SignCert);

            x509Certs = X509StoreFactory.Create(
                "Certificate/Collection",
                new X509CollectionStoreParameters(certList));

            //
            // replace certs
            //
            sd = CmsSignedData.ReplaceCertificatesAndCrls(sd, x509Certs, null, null);

            VerifySignatures(sd);
        }
示例#27
0
		private void rsaPssTest(
			string	digestName,
			string	digestOID)
		{
			byte[] msgBytes = Encoding.ASCII.GetBytes("Hello World!");
			CmsProcessable msg = new CmsProcessableByteArray(msgBytes);

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

            CmsSignedDataGenerator gen = new CmsSignedDataGenerator();
			gen.AddSigner(OrigKP.Private, OrigCert, CmsSignedDataGenerator.EncryptionRsaPss, digestOID);
			gen.AddCertificates(x509Certs);

            CmsSignedData s = gen.Generate(CmsSignedDataGenerator.Data, msg, false);

            // compute expected content digest
            byte[] expectedDigest = DigestUtilities.CalculateDigest(digestName, msgBytes);

            VerifySignatures(s, expectedDigest);
		}
示例#28
0
		public void TestSha1WithRsaAndAttributeTable()
		{
			byte[] testBytes = Encoding.ASCII.GetBytes("Hello world!");
			CmsProcessable msg = new CmsProcessableByteArray(testBytes);

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

            byte[] hash = DigestUtilities.CalculateDigest("SHA1", testBytes);

			Asn1.Cms.Attribute attr = new Asn1.Cms.Attribute(CmsAttributes.MessageDigest,
				new DerSet(new DerOctetString(hash)));

			Asn1EncodableVector v = new Asn1EncodableVector(attr);

            CmsSignedDataGenerator gen = new CmsSignedDataGenerator();
            gen.AddSigner(SignKP.Private, SignCert, CmsSignedDataGenerator.DigestSha1,
				new AttributeTable(v), null);
			gen.AddCertificates(x509Certs);

            CmsSignedData s = gen.Generate(CmsSignedDataGenerator.Data, null, false);

            //
			// the signature is detached, so need to add msg before passing on
			//
			s = new CmsSignedData(msg, s.GetEncoded());

			//
			// compute expected content digest
			//
			VerifySignatures(s, hash);
		}
        private void rsaPssTest(
			string	digestName,
			string	digestOID)
        {
            IList certList = new ArrayList();
            byte[] msgBytes = Encoding.ASCII.GetBytes("Hello World!");
            CmsProcessable msg = new CmsProcessableByteArray(msgBytes);

            certList.Add(OrigCert);
            certList.Add(SignCert);

            IX509Store x509Certs = X509StoreFactory.Create(
                "Certificate/Collection",
                new X509CollectionStoreParameters(certList));

            CmsSignedDataGenerator gen = new CmsSignedDataGenerator();

            gen.AddSigner(OrigKP.Private, OrigCert, CmsSignedDataGenerator.EncryptionRsaPss, digestOID);

            gen.AddCertificates(x509Certs);

            CmsSignedData s = gen.Generate(CmsSignedDataGenerator.Data, msg, false);

            //
            // compute expected content digest
            //
            IDigest md = DigestUtilities.GetDigest(digestName);
            md.BlockUpdate(msgBytes, 0, msgBytes.Length);
            byte[] expectedDigest = DigestUtilities.DoFinal(md);

            VerifySignatures(s, expectedDigest);
        }
示例#30
0
		public void TestEncapsulatedCertStoreReplacement()
		{
			CmsProcessable msg = new CmsProcessableByteArray(Encoding.ASCII.GetBytes("Hello World!"));

            IX509Store x509Certs = CmsTestUtil.MakeCertStore(SignDsaCert);

            CmsSignedDataGenerator gen = new CmsSignedDataGenerator();
			gen.AddSigner(OrigKP.Private, OrigCert, CmsSignedDataGenerator.DigestSha1);
			gen.AddCertificates(x509Certs);

            CmsSignedData sd = gen.Generate(msg, true);

			//
			// create new certstore
			//
            x509Certs = CmsTestUtil.MakeCertStore(OrigCert, SignCert);

            //
			// replace certs
			//
			sd = CmsSignedData.ReplaceCertificatesAndCrls(sd, x509Certs, null, null);

			VerifySignatures(sd);
		}
示例#31
0
		public void TestCertOrdering2()
		{
			CmsProcessable msg = new CmsProcessableByteArray(Encoding.ASCII.GetBytes("Hello World!"));

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

            CmsSignedDataGenerator gen = new CmsSignedDataGenerator();
			gen.AddSigner(OrigKP.Private, OrigCert, CmsSignedDataGenerator.DigestSha1);
			gen.AddCertificates(x509Certs);

			CmsSignedData sd = gen.Generate(msg, true);

            x509Certs = sd.GetCertificates("Collection");
            ArrayList a = new ArrayList(x509Certs.GetMatches(null));

            Assert.AreEqual(3, a.Count);
			Assert.AreEqual(SignCert, a[0]);
			Assert.AreEqual(SignDsaCert, a[1]);
			Assert.AreEqual(OrigCert, a[2]);
		}
        public void TestDetachedVerification()
        {
            byte[] data = Encoding.ASCII.GetBytes("Hello World!");
            CmsProcessable msg = new CmsProcessableByteArray(data);

            IList certList = new ArrayList();
            certList.Add(OrigCert);
            certList.Add(SignCert);

            IX509Store x509Certs = X509StoreFactory.Create(
                "Certificate/Collection",
                new X509CollectionStoreParameters(certList));

            CmsSignedDataGenerator gen = new CmsSignedDataGenerator();

            gen.AddSigner(OrigKP.Private, OrigCert, CmsSignedDataGenerator.DigestSha1);

            gen.AddSigner(OrigKP.Private, OrigCert, CmsSignedDataGenerator.DigestMD5);

            gen.AddCertificates(x509Certs);

            CmsSignedData s = gen.Generate(msg);

            IDictionary hashes = new Hashtable();
            hashes.Add(CmsSignedDataGenerator.DigestSha1, CalculateHash("SHA1", data));
            hashes.Add(CmsSignedDataGenerator.DigestMD5, CalculateHash("MD5", data));

            s = new CmsSignedData(hashes, s.GetEncoded());

            VerifySignatures(s, null);
        }
示例#33
0
        /// <summary><inheritDoc></inheritDoc></summary>
        /// <exception cref="System.IO.IOException"></exception>
        public virtual Document SignDocument(Document document, SignatureParameters parameters
            , byte[] signatureValue)
        {
            if (parameters.SignaturePackaging != SignaturePackaging.ENVELOPING && parameters
                .SignaturePackaging != SignaturePackaging.DETACHED)
            {
                throw new ArgumentException("Unsupported signature packaging " + parameters.SignaturePackaging);
            }
            try
            {
                //jbonilla - No aplica para C#
                //string jsAlgorithm = parameters.GetSignatureAlgorithm().GetJavaSignatureAlgorithm
                //    (parameters.GetDigestAlgorithm());
                //PreComputedContentSigner cs = new PreComputedContentSigner(jsAlgorithm, signatureValue
                //    );
                PreComputedSigner s = new PreComputedSigner(signatureValue);

                //DigestCalculatorProvider digestCalculatorProvider = new BcDigestCalculatorProvider
                //    ();
                //CMSSignedDataGenerator generator = CreateCMSSignedDataGenerator(cs, digestCalculatorProvider
                //    , parameters, GetSigningProfile(parameters), true, null);
                CmsSignedDataGenerator generator = CreateCMSSignedDataGenerator(s, parameters
                    , GetSigningProfile(parameters), true, null);
                byte[] toBeSigned = Streams.ReadAll(document.OpenStream());
                CmsProcessableByteArray content = new CmsProcessableByteArray(toBeSigned);
                bool includeContent = true;
                if (parameters.SignaturePackaging == SignaturePackaging.DETACHED)
                {
                    includeContent = false;
                }
                CmsSignedData data = generator.Generate(content, includeContent);
                Document signedDocument = new CMSSignedDocument(data);
                CAdESSignatureExtension extension = GetExtensionProfile(parameters);
                if (extension != null)
                {
                    signedDocument = extension.ExtendSignatures(new CMSSignedDocument(data), document
                        , parameters);
                }
                return signedDocument;
            }
            catch (CmsException e)
            {
                throw new RuntimeException(e);
            }
        }
        public void TestSha1AndMD5WithRsaEncapsulatedRepeated()
        {
            IList certList = new ArrayList();
            CmsProcessable msg = new CmsProcessableByteArray(Encoding.ASCII.GetBytes("Hello World!"));

            certList.Add(OrigCert);
            certList.Add(SignCert);

            IX509Store x509Certs = X509StoreFactory.Create(
                "Certificate/Collection",
                new X509CollectionStoreParameters(certList));

            CmsSignedDataGenerator gen = new CmsSignedDataGenerator();

            gen.AddSigner(OrigKP.Private, OrigCert, CmsSignedDataGenerator.DigestSha1);

            gen.AddSigner(OrigKP.Private, OrigCert, CmsSignedDataGenerator.DigestMD5);

            gen.AddCertificates(x509Certs);

            CmsSignedData s = gen.Generate(msg, true);

            s = new CmsSignedData(ContentInfo.GetInstance(Asn1Object.FromByteArray(s.GetEncoded())));

            x509Certs = s.GetCertificates("Collection");

            SignerInformationStore signers = s.GetSignerInfos();

            Assert.AreEqual(2, signers.Count);

            SignerID sid = null;
            ICollection c = signers.GetSigners();

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

                IEnumerator certEnum = certCollection.GetEnumerator();

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

                sid = signer.SignerID;

                Assert.IsTrue(signer.Verify(cert));

                //
                // check content digest
                //

                byte[] contentDigest = (byte[])gen.GetGeneratedDigests()[signer.DigestAlgOid];

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

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

            c = signers.GetSigners(sid);

            Assert.AreEqual(2, c.Count);

            //
            // try using existing signer
            //

            gen = new CmsSignedDataGenerator();

            gen.AddSigners(s.GetSignerInfos());

            gen.AddCertificates(s.GetCertificates("Collection"));
            gen.AddCrls(s.GetCrls("Collection"));

            s = gen.Generate(msg, true);

            s = new CmsSignedData(ContentInfo.GetInstance(Asn1Object.FromByteArray(s.GetEncoded())));

            x509Certs = s.GetCertificates("Collection");

            signers = s.GetSignerInfos();
            c = signers.GetSigners();

            Assert.AreEqual(2, c.Count);

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

                IEnumerator certEnum = certCollection.GetEnumerator();

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

                Assert.AreEqual(true, signer.Verify(cert));
            }

            CheckSignerStoreReplacement(s, signers);
        }
示例#35
0
        private void SignManigestFile(PassGeneratorRequest request)
        {
            Trace.TraceInformation("Signing the manifest file...");

            X509Certificate2 card = GetCertificate(request);

            if (card == null)
            {
                throw new FileNotFoundException("Certificate could not be found. Please ensure the thumbprint and cert location values are correct.");
            }

            try
            {
                Org.BouncyCastle.X509.X509Certificate cert = DotNetUtilities.FromX509Certificate(card);
                Org.BouncyCastle.Crypto.AsymmetricKeyParameter privateKey = DotNetUtilities.GetKeyPair(card.PrivateKey).Private;

                Trace.TraceInformation("Fetching Apple Certificate for signing..");

                X509Certificate2 appleCA = GetAppleCertificate(request);
                Org.BouncyCastle.X509.X509Certificate appleCert = DotNetUtilities.FromX509Certificate(appleCA);

                Trace.TraceInformation("Constructing the certificate chain..");

                ArrayList intermediateCerts = new ArrayList();

                intermediateCerts.Add(appleCert);
                intermediateCerts.Add(cert);

                Org.BouncyCastle.X509.Store.X509CollectionStoreParameters PP = new Org.BouncyCastle.X509.Store.X509CollectionStoreParameters(intermediateCerts);
                Org.BouncyCastle.X509.Store.IX509Store st1 = Org.BouncyCastle.X509.Store.X509StoreFactory.Create("CERTIFICATE/COLLECTION", PP);

                CmsSignedDataGenerator generator = new CmsSignedDataGenerator();

                generator.AddSigner(privateKey, cert, CmsSignedDataGenerator.DigestSha1);
                generator.AddCertificates(st1);

                Trace.TraceInformation("Processing the signature..");

                CmsProcessable content = new CmsProcessableByteArray(manifestFile);
                CmsSignedData signedData = generator.Generate(content, false);

                signatureFile = signedData.GetEncoded();

                Trace.TraceInformation("The file has been successfully signed!");

            }
            catch (Exception exp)
            {
                Trace.TraceError("Failed to sign the manifest file: [{0}]", exp.Message);
                throw new ManifestSigningException("Failed to sign manifest", exp);
            }
        }
        public void TestSha1WithRsaCounterSignature()
        {
            IList certList = new ArrayList();
            IList crlList = new ArrayList();
            CmsProcessable msg = new CmsProcessableByteArray(Encoding.ASCII.GetBytes("Hello World!"));

            certList.Add(SignCert);
            certList.Add(OrigCert);

            crlList.Add(SignCrl);

            IX509Store x509Certs = X509StoreFactory.Create(
                "Certificate/Collection",
                new X509CollectionStoreParameters(certList));
            IX509Store x509Crls = X509StoreFactory.Create(
                "CRL/Collection",
                new X509CollectionStoreParameters(crlList));

            CmsSignedDataGenerator gen = new CmsSignedDataGenerator();

            gen.AddSigner(SignKP.Private, SignCert, CmsSignedDataGenerator.DigestSha1);

            gen.AddCertificates(x509Certs);
            gen.AddCrls(x509Crls);

            CmsSignedData s = gen.Generate(msg, true);
            SignerInformation origSigner = (SignerInformation) new ArrayList(s.GetSignerInfos().GetSigners())[0];
            SignerInformationStore counterSigners1 = gen.GenerateCounterSigners(origSigner);
            SignerInformationStore counterSigners2 = gen.GenerateCounterSigners(origSigner);

            SignerInformation signer1 = SignerInformation.AddCounterSigners(origSigner, counterSigners1);
            SignerInformation signer2 = SignerInformation.AddCounterSigners(signer1, counterSigners2);

            SignerInformationStore cs = signer2.GetCounterSignatures();
            ICollection csSigners = cs.GetSigners();
            Assert.AreEqual(2, csSigners.Count);

            foreach (SignerInformation cSigner in csSigners)
            {
                ICollection certCollection = x509Certs.GetMatches(cSigner.SignerID);

                IEnumerator certEnum = certCollection.GetEnumerator();

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

                Assert.IsNull(cSigner.SignedAttributes[Asn1.Pkcs.PkcsObjectIdentifiers.Pkcs9AtContentType]);
                Assert.IsTrue(cSigner.Verify(cert));
            }
        }
		private CmsCompressedData GetStdData()
		{
			CmsProcessableByteArray testData = new CmsProcessableByteArray(TEST_DATA);
			CmsCompressedDataGenerator gen = new CmsCompressedDataGenerator();
			return gen.Generate(testData, CmsCompressedDataGenerator.ZLib);
		}