ReadCertificates() public method

public ReadCertificates ( Stream inStream ) : ICollection
inStream Stream
return ICollection
Beispiel #1
0
		public void SetUp ()
		{
			using (var ctx = CreateContext ()) {
				var dataDir = Path.Combine ("..", "..", "TestData", "smime");
				string path;

				CryptographyContext.Register (ctx.GetType ());

				foreach (var filename in CertificateAuthorities) {
					path = Path.Combine (dataDir, filename);
					using (var file = File.OpenRead (path)) {
						if (ctx is DefaultSecureMimeContext) {
							((DefaultSecureMimeContext) ctx).Import (file, true);
						} else {
							var parser = new X509CertificateParser ();
							foreach (X509Certificate certificate in parser.ReadCertificates (file))
								ctx.Import (certificate);
						}
					}
				}

				path = Path.Combine (dataDir, "smime.p12");

				using (var file = File.OpenRead (path))
					ctx.Import (file, "no.secret");
			}
		}
		/// <summary>
		/// Imports the certificate(s) from the specified stream.
		/// </summary>
		/// <remarks>
		/// Imports the certificate(s) from the specified stream.
		/// </remarks>
		/// <param name="stream">The stream to import.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <paramref name="stream"/> is <c>null</c>.
		/// </exception>
		/// <exception cref="System.IO.IOException">
		/// An error occurred reading the stream.
		/// </exception>
		public void Import (Stream stream)
		{
			if (stream == null)
				throw new ArgumentNullException ("stream");

			var parser = new X509CertificateParser ();

			foreach (X509Certificate certificate in parser.ReadCertificates (stream)) {
				if (unique.Add (certificate))
					certs.Add (certificate);
			}
		}
Beispiel #3
0
        private void pkcs7Test()
        {
            Asn1Encodable rootCert = Asn1Object.FromByteArray(CertPathTest.rootCertBin);
            Asn1Encodable rootCrl = Asn1Object.FromByteArray(CertPathTest.rootCrlBin);

            X509CertificateParser certParser = new X509CertificateParser();
            X509CrlParser crlParser = new X509CrlParser();

            SignedData sigData = new SignedData(
                DerSet.Empty,
                new ContentInfo(CmsObjectIdentifiers.Data, null),
                new DerSet(
                    rootCert,
                    new DerTaggedObject(false, 2, Asn1Object.FromByteArray(AttrCertTest.attrCert))),
                new DerSet(rootCrl),
                DerSet.Empty);

            ContentInfo info = new ContentInfo(CmsObjectIdentifiers.SignedData, sigData);

            X509Certificate cert = certParser.ReadCertificate(info.GetEncoded());
            if (cert == null || !AreEqual(cert.GetEncoded(), rootCert.ToAsn1Object().GetEncoded()))
            {
                Fail("PKCS7 cert not read");
            }
            X509Crl crl = crlParser.ReadCrl(info.GetEncoded());
            if (crl == null || !AreEqual(crl.GetEncoded(), rootCrl.ToAsn1Object().GetEncoded()))
            {
                Fail("PKCS7 crl not read");
            }
            ArrayList col = new ArrayList(certParser.ReadCertificates(info.GetEncoded()));
            if (col.Count != 1 || !col.Contains(cert))
            {
                Fail("PKCS7 cert collection not right");
            }
            col = new ArrayList(crlParser.ReadCrls(info.GetEncoded()));
            if (col.Count != 1 || !col.Contains(crl))
            {
                Fail("PKCS7 crl collection not right");
            }

            // data with no certificates or CRLs

            sigData = new SignedData(DerSet.Empty, new ContentInfo(CmsObjectIdentifiers.Data, null), DerSet.Empty, DerSet.Empty, DerSet.Empty);

            info = new ContentInfo(CmsObjectIdentifiers.SignedData, sigData);

            cert = certParser.ReadCertificate(info.GetEncoded());
            if (cert != null)
            {
                Fail("PKCS7 cert present");
            }
            crl = crlParser.ReadCrl(info.GetEncoded());
            if (crl != null)
            {
                Fail("PKCS7 crl present");
            }

            // data with absent certificates and CRLS

            sigData = new SignedData(DerSet.Empty, new ContentInfo(CmsObjectIdentifiers.Data, null), null, null, DerSet.Empty);

            info = new ContentInfo(CmsObjectIdentifiers.SignedData, sigData);

            cert = certParser.ReadCertificate(info.GetEncoded());
            if (cert != null)
            {
                Fail("PKCS7 cert present");
            }
            crl = crlParser.ReadCrl(info.GetEncoded());
            if (crl != null)
            {
                Fail("PKCS7 crl present");
            }

            //
            // sample message
            //
            ICollection certCol = certParser.ReadCertificates(pkcs7CrlProblem);
            ICollection crlCol = crlParser.ReadCrls(pkcs7CrlProblem);

            if (crlCol.Count != 0)
            {
                Fail("wrong number of CRLs: " + crlCol.Count);
            }

            if (certCol.Count != 4)
            {
                Fail("wrong number of Certs: " + certCol.Count);
            }
        }
Beispiel #4
0
 /**
 * Verifies a signature using the sub-filter adbe.pkcs7.detached or
 * adbe.pkcs7.sha1.
 * @param contentsKey the /Contents key
 * @param provider the provider or <code>null</code> for the default provider
 * @throws SecurityException on error
 * @throws CRLException on error
 * @throws InvalidKeyException on error
 * @throws CertificateException on error
 * @throws NoSuchProviderException on error
 * @throws NoSuchAlgorithmException on error
 */    
 public PdfPKCS7(byte[] contentsKey) {
     Asn1InputStream din = new Asn1InputStream(new MemoryStream(contentsKey));
     
     //
     // Basic checks to make sure it's a PKCS#7 SignedData Object
     //
     Asn1Object pkcs;
     
     try {
         pkcs = din.ReadObject();
     }
     catch  {
         throw new ArgumentException("can't decode PKCS7SignedData object");
     }
     if (!(pkcs is Asn1Sequence)) {
         throw new ArgumentException("Not a valid PKCS#7 object - not a sequence");
     }
     Asn1Sequence signedData = (Asn1Sequence)pkcs;
     DerObjectIdentifier objId = (DerObjectIdentifier)signedData[0];
     if (!objId.Id.Equals(ID_PKCS7_SIGNED_DATA))
         throw new ArgumentException("Not a valid PKCS#7 object - not signed data");
     Asn1Sequence content = (Asn1Sequence)((DerTaggedObject)signedData[1]).GetObject();
     // the positions that we care are:
     //     0 - version
     //     1 - digestAlgorithms
     //     2 - possible ID_PKCS7_DATA
     //     (the certificates and crls are taken out by other means)
     //     last - signerInfos
     
     // the version
     version = ((DerInteger)content[0]).Value.IntValue;
     
     // the digestAlgorithms
     digestalgos = new Hashtable();
     IEnumerator e = ((Asn1Set)content[1]).GetEnumerator();
     while (e.MoveNext())
     {
         Asn1Sequence s = (Asn1Sequence)e.Current;
         DerObjectIdentifier o = (DerObjectIdentifier)s[0];
         digestalgos[o.Id] = null;
     }
     
     // the certificates and crls
     X509CertificateParser cf = new X509CertificateParser();
     certs = new ArrayList();
     foreach (X509Certificate cc in cf.ReadCertificates(contentsKey)) {
         certs.Add(cc);
     }
     crls = new ArrayList();
     
     // the possible ID_PKCS7_DATA
     Asn1Sequence rsaData = (Asn1Sequence)content[2];
     if (rsaData.Count > 1) {
         DerOctetString rsaDataContent = (DerOctetString)((DerTaggedObject)rsaData[1]).GetObject();
         RSAdata = rsaDataContent.GetOctets();
     }
     
     // the signerInfos
     int next = 3;
     while (content[next] is DerTaggedObject)
         ++next;
     Asn1Set signerInfos = (Asn1Set)content[next];
     if (signerInfos.Count != 1)
         throw new ArgumentException("This PKCS#7 object has multiple SignerInfos - only one is supported at this time");
     Asn1Sequence signerInfo = (Asn1Sequence)signerInfos[0];
     // the positions that we care are
     //     0 - version
     //     1 - the signing certificate serial number
     //     2 - the digest algorithm
     //     3 or 4 - digestEncryptionAlgorithm
     //     4 or 5 - encryptedDigest
     signerversion = ((DerInteger)signerInfo[0]).Value.IntValue;
     // Get the signing certificate
     Asn1Sequence issuerAndSerialNumber = (Asn1Sequence)signerInfo[1];
     BigInteger serialNumber = ((DerInteger)issuerAndSerialNumber[1]).Value;
     foreach (X509Certificate cert in certs) {                                                            
         if (serialNumber.Equals(cert.SerialNumber)) {
             signCert = cert;                                                                             
             break;                                                                                            
         }                                                                                                
     }
     if (signCert == null) {
         throw new ArgumentException("Can't find signing certificate with serial " + serialNumber.ToString(16));
     }
     CalcSignCertificateChain();
     digestAlgorithm = ((DerObjectIdentifier)((Asn1Sequence)signerInfo[2])[0]).Id;
     next = 3;
     if (signerInfo[next] is Asn1TaggedObject) {
         Asn1TaggedObject tagsig = (Asn1TaggedObject)signerInfo[next];
         Asn1Set sseq = Asn1Set.GetInstance(tagsig, false);
         sigAttr = sseq.GetEncoded(Asn1Encodable.Der);
         
         for (int k = 0; k < sseq.Count; ++k) {
             Asn1Sequence seq2 = (Asn1Sequence)sseq[k];
             if (((DerObjectIdentifier)seq2[0]).Id.Equals(ID_MESSAGE_DIGEST)) {
                 Asn1Set sset = (Asn1Set)seq2[1];
                 digestAttr = ((DerOctetString)sset[0]).GetOctets();
             }
             else if (((DerObjectIdentifier)seq2[0]).Id.Equals(ID_ADBE_REVOCATION)) {
                 Asn1Set setout = (Asn1Set)seq2[1];
                 Asn1Sequence seqout = (Asn1Sequence)setout[0];
                 for (int j = 0; j < seqout.Count; ++j) {
                     Asn1TaggedObject tg = (Asn1TaggedObject)seqout[j];
                     if (tg.TagNo != 1)
                         continue;
                     Asn1Sequence seqin = (Asn1Sequence)tg.GetObject();
                     FindOcsp(seqin);
                 }
             }
         }
         if (digestAttr == null)
             throw new ArgumentException("Authenticated attribute is missing the digest.");
         ++next;
     }
     digestEncryptionAlgorithm = ((DerObjectIdentifier)((Asn1Sequence)signerInfo[next++])[0]).Id;
     digest = ((DerOctetString)signerInfo[next++]).GetOctets();
     if (next < signerInfo.Count && (signerInfo[next] is DerTaggedObject)) {
         DerTaggedObject taggedObject = (DerTaggedObject) signerInfo[next];
         Asn1Set unat = Asn1Set.GetInstance(taggedObject, false);
         Org.BouncyCastle.Asn1.Cms.AttributeTable attble = new Org.BouncyCastle.Asn1.Cms.AttributeTable(unat);
         Org.BouncyCastle.Asn1.Cms.Attribute ts = attble[PkcsObjectIdentifiers.IdAASignatureTimeStampToken];
         if (ts != null) {
             Asn1Set attributeValues = ts.AttrValues;
             Asn1Sequence tokenSequence = Asn1Sequence.GetInstance(attributeValues[0]);
             Org.BouncyCastle.Asn1.Cms.ContentInfo contentInfo = Org.BouncyCastle.Asn1.Cms.ContentInfo.GetInstance(tokenSequence);
             this.timeStampToken = new TimeStampToken(contentInfo);
         }
     }
     if (RSAdata != null || digestAttr != null) {
         messageDigest = GetHashClass();
     }
     sig = SignerUtilities.GetSigner(GetDigestAlgorithm());
     sig.Init(false, signCert.GetPublicKey());
 }
Beispiel #5
0
        /**
        * Verifies a signature using the sub-filter adbe.x509.rsa_sha1.
        * @param contentsKey the /Contents key
        * @param certsKey the /Cert key
        * @param provider the provider or <code>null</code> for the default provider
        */    
        public PdfPKCS7(byte[] contentsKey, byte[] certsKey) {

            X509CertificateParser cf = new X509CertificateParser();
            certs = new ArrayList();
            foreach (X509Certificate cc in cf.ReadCertificates(certsKey)) {
                certs.Add(cc);
            }
            signCerts = certs;
            signCert = (X509Certificate)certs[0];
            crls = new ArrayList();
            Asn1InputStream inp = new Asn1InputStream(new MemoryStream(contentsKey));
            digest = ((DerOctetString)inp.ReadObject()).GetOctets();
            sig = SignerUtilities.GetSigner("SHA1withRSA");
            sig.Init(false, signCert.GetPublicKey());
        }
        /**
         * Use this constructor if you want to verify a signature using
         * the sub-filter adbe.pkcs7.detached or adbe.pkcs7.sha1.
         * @param contentsKey the /Contents key
         * @param tsp set to true if there's a PAdES LTV time stamp.
         * @param provider the provider or <code>null</code> for the default provider
         */
        public PdfPKCS7(byte[] contentsKey, bool tsp)
        {
            isTsp = tsp;
            Asn1InputStream din = new Asn1InputStream(new MemoryStream(contentsKey));

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

            try {
                pkcs = din.ReadObject();
            }
            catch  {
                throw new ArgumentException(MessageLocalization.GetComposedMessage("can.t.decode.pkcs7signeddata.object"));
            }
            if (!(pkcs is Asn1Sequence)) {
                throw new ArgumentException(MessageLocalization.GetComposedMessage("not.a.valid.pkcs.7.object.not.a.sequence"));
            }
            Asn1Sequence signedData = (Asn1Sequence)pkcs;
            DerObjectIdentifier objId = (DerObjectIdentifier)signedData[0];
            if (!objId.Id.Equals(SecurityIDs.ID_PKCS7_SIGNED_DATA))
                throw new ArgumentException(MessageLocalization.GetComposedMessage("not.a.valid.pkcs.7.object.not.signed.data"));
            Asn1Sequence content = (Asn1Sequence)((Asn1TaggedObject)signedData[1]).GetObject();
            // the positions that we care are:
            //     0 - version
            //     1 - digestAlgorithms
            //     2 - possible ID_PKCS7_DATA
            //     (the certificates and crls are taken out by other means)
            //     last - signerInfos

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

            // the digestAlgorithms
            digestalgos = new Dictionary<string,object>();
            IEnumerator e = ((Asn1Set)content[1]).GetEnumerator();
            while (e.MoveNext())
            {
                Asn1Sequence s = (Asn1Sequence)e.Current;
                DerObjectIdentifier o = (DerObjectIdentifier)s[0];
                digestalgos[o.Id] = null;
            }

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

            // the possible ID_PKCS7_DATA
            Asn1Sequence rsaData = (Asn1Sequence)content[2];
            if (rsaData.Count > 1) {
                Asn1OctetString rsaDataContent = (Asn1OctetString)((Asn1TaggedObject)rsaData[1]).GetObject();
                RSAdata = rsaDataContent.GetOctets();
            }

            // the signerInfos
            int next = 3;
            while (content[next] is Asn1TaggedObject)
                ++next;
            Asn1Set signerInfos = (Asn1Set)content[next];
            if (signerInfos.Count != 1)
                throw new ArgumentException(MessageLocalization.GetComposedMessage("this.pkcs.7.object.has.multiple.signerinfos.only.one.is.supported.at.this.time"));
            Asn1Sequence signerInfo = (Asn1Sequence)signerInfos[0];
            // the positions that we care are
            //     0 - version
            //     1 - the signing certificate issuer and serial number
            //     2 - the digest algorithm
            //     3 or 4 - digestEncryptionAlgorithm
            //     4 or 5 - encryptedDigest
            signerversion = ((DerInteger)signerInfo[0]).Value.IntValue;
            // Get the signing certificate
            Asn1Sequence issuerAndSerialNumber = (Asn1Sequence)signerInfo[1];
            Org.BouncyCastle.Asn1.X509.X509Name issuer = Org.BouncyCastle.Asn1.X509.X509Name.GetInstance(issuerAndSerialNumber[0]);
            BigInteger serialNumber = ((DerInteger)issuerAndSerialNumber[1]).Value;
            foreach (X509Certificate cert in certs) {
                if (issuer.Equivalent(cert.IssuerDN) && serialNumber.Equals(cert.SerialNumber)) {
                    signCert = cert;
                    break;
                }
            }
            if (signCert == null) {
                throw new ArgumentException(MessageLocalization.GetComposedMessage("can.t.find.signing.certificate.with.serial.1",
                    issuer.ToString() + " / " + serialNumber.ToString(16)));
            }
            CalcSignCertificateChain();
            digestAlgorithmOid = ((DerObjectIdentifier)((Asn1Sequence)signerInfo[2])[0]).Id;
            next = 3;
            if (signerInfo[next] is Asn1TaggedObject) {
                Asn1TaggedObject tagsig = (Asn1TaggedObject)signerInfo[next];
                Asn1Set sseq = Asn1Set.GetInstance(tagsig, false);
                sigAttr = sseq.GetEncoded(Asn1Encodable.Der);

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

        /**
         * Use this constructor if you want to verify a signature using the sub-filter adbe.x509.rsa_sha1.
         * @param contentsKey the /Contents key
         * @param certsKey the /Cert key
         */
        public PdfPKCS7(byte[] contentsKey, byte[] certsKey) {
            X509CertificateParser cf = new X509CertificateParser();
            certs = new List<X509Certificate>();

            foreach (X509Certificate cc in cf.ReadCertificates(certsKey)) {
                if (signCert != null)
                    signCert = cc;
                certs.Add(cc);
            }

            signCerts = certs;
            crls = new List<X509Crl>();

            Asn1InputStream inp = new Asn1InputStream(new MemoryStream(contentsKey));
            digest = ((Asn1OctetString)inp.ReadObject()).GetOctets();

            sig = SignerUtilities.GetSigner("SHA1withRSA");
            sig.Init(false, signCert.GetPublicKey());

            // setting the oid to SHA1withRSA
            digestAlgorithmOid = "1.2.840.10040.4.3";
            digestEncryptionAlgorithmOid = "1.3.36.3.3.1.2";
        }
Beispiel #8
0
        /// <summary>
        /// Herunterladen des Zertifikats
        /// </summary>
        /// <param name="orderId">ID des Auftrags</param>
        /// <returns>Zertifikat von der OSTC (private Schlüssel fehlt hier!)</returns>
        /// <remarks>Es wird eine Exception ausgelöst, wenn noch kein Schlüssel verfügbar ist.</remarks>
        public async Task<IReadOnlyList<X509Certificate>> DownloadCertificateAsync(string orderId)
        {
            var query = new OstcSchluessel
            {
                Auftragsnummer = orderId,
                ItemElementName = (OstcKeyType)Enum.Parse(typeof(OstcKeyType), Sender.SenderId.Type.ToString()),
                Item = Sender.SenderId.Id,
            };
            var queryData = OstcUtils.Serialize(query, Iso88591);

            ValidateData(queryData, OstcMessageType.KeyData);

            var now = DateTime.Now;
            var message = new TransportRequestType()
            {
                version = SupportedVersionsType.Item11,
                profile = ExtraProfileOstc,
                TransportHeader = CreateRequestHeader(now, OstcDataType.Key, ExtraScenario.RequestWithResponse),
                TransportBody = new TransportRequestBodyType
                {
                    Items = new object[]
                    {
                        new DataType 
                        {
                            Item = new Base64CharSequenceType()
                            {
                                Value = queryData,
                            },
                        },
                    },
                },
            };

            ValidateRequest(message, OstcMessageType.Key);

            var messageData = OstcExtraSerializer.Iso88591.Serialize(message);
            var request = CreateRequest(Network.Requests.KeyRequest);
            using (var requestStream = await Task.Factory.FromAsync(request.BeginGetRequestStream, request.EndGetRequestStream, null))
            {
                requestStream.Write(messageData, 0, messageData.Length);
            }

            using (var response = await Task.Factory.FromAsync(request.BeginGetResponse, request.EndGetResponse, null))
            {
                var serializer = new XmlSerializer(typeof(TransportResponseType));
                var responseData = (TransportResponseType)serializer.Deserialize(response.GetResponseStream());

                var flags = responseData.TransportHeader.GetFlags().ToList();
                if (flags.Any(x => x.weight == ExtraFlagWeight.Error))
                    throw new Ostc2Exception(flags);

                var certData = ((Base64CharSequenceType)((DataType)responseData.TransportBody.Items[0]).Item).Value;

                var parser = new X509CertificateParser();
                var certs = parser.ReadCertificates(certData).Cast<X509Certificate>().ToList();

                return certs;
            }
        }
		/// <summary>
		/// Imports a DER-encoded certificate stream.
		/// </summary>
		/// <remarks>
		/// Imports all of the certificates in the DER-encoded stream.
		/// </remarks>
		/// <param name="stream">The raw certificate(s).</param>
		/// <param name="trusted"><c>true</c> if the certificates are trusted.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <paramref name="stream"/> is <c>null</c>.
		/// </exception>
		public void Import (Stream stream, bool trusted)
		{
			if (stream == null)
				throw new ArgumentNullException ("stream");

			var parser = new X509CertificateParser ();

			foreach (X509Certificate certificate in parser.ReadCertificates (stream)) {
				if (dbase.Find (certificate, X509CertificateRecordFields.Id) != null)
					continue;

				var record = new X509CertificateRecord (certificate);
				record.IsTrusted = trusted;
				dbase.Add (record);
			}
		}
Beispiel #10
0
        public IList LoadCertificates()
        {
            if (!Directory.Exists(_source))
            {
                throw new DirectoryNotFoundException("Directory not found: " + _source);
            }

            List<X509Certificate> certList = new List<X509Certificate>();

            string[] files = Directory.GetFiles(_source);
            List<string> failures = new List<string>();
            foreach (string file in files)
            {
                try
                {
                    if (SkipResource(_ignore, file)) continue;
                    X509CertificateParser certParser = new X509CertificateParser();
                    using (Stream stream = new FileStream(file, FileMode.Open))
                    {
                        var certs = certParser.ReadCertificates(stream);
                        stream.Close();
                        foreach (var cert in certs)
                        {
                            certList.Add(cert as X509Certificate);
                        }
                    }
                }
                catch (Exception e)
                {
                    failures.Add(string.Format("Failed loading file {0}\r\n{1}", file, e.Message));
                }
            }
            if (failures.Count > 0)
            {
                string result = failures.Aggregate((current, f) => current + f + "\r\n");
                throw new Exception(result);
            }
            return certList;
        }
Beispiel #11
0
        /**
        * Verifies a signature using the sub-filter adbe.pkcs7.detached or
        * adbe.pkcs7.sha1.
        * @param contentsKey the /Contents key
        * @param provider the provider or <code>null</code> for the default provider
        * @throws SecurityException on error
        * @throws CRLException on error
        * @throws InvalidKeyException on error
        * @throws CertificateException on error
        * @throws NoSuchProviderException on error
        * @throws NoSuchAlgorithmException on error
        */
        public PdfPKCS7(byte[] contentsKey)
        {
            Asn1InputStream din = new Asn1InputStream(new MemoryStream(contentsKey));

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

            try {
                pkcs = din.ReadObject();
            }
            catch  {
                throw new ArgumentException("can't decode PKCS7SignedData object");
            }
            if (!(pkcs is Asn1Sequence)) {
                throw new ArgumentException("Not a valid PKCS#7 object - not a sequence");
            }
            Asn1Sequence signedData = (Asn1Sequence)pkcs;
            DerObjectIdentifier objId = (DerObjectIdentifier)signedData[0];
            if (!objId.Id.Equals(ID_PKCS7_SIGNED_DATA))
                throw new ArgumentException("Not a valid PKCS#7 object - not signed data");
            Asn1Sequence content = (Asn1Sequence)((DerTaggedObject)signedData[1]).GetObject();
            // the positions that we care are:
            //     0 - version
            //     1 - digestAlgorithms
            //     2 - possible ID_PKCS7_DATA
            //     (the certificates and crls are taken out by other means)
            //     last - signerInfos

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

            // the digestAlgorithms
            digestalgos = new Hashtable();
            IEnumerator e = ((Asn1Set)content[1]).GetEnumerator();
            while (e.MoveNext())
            {
                Asn1Sequence s = (Asn1Sequence)e.Current;
                DerObjectIdentifier o = (DerObjectIdentifier)s[0];
                digestalgos[o.Id] = null;
            }

            // the certificates and crls
            X509CertificateParser cf = new X509CertificateParser();
            certs = new ArrayList();
            foreach (X509Certificate cc in cf.ReadCertificates(contentsKey)) {
                certs.Add(cc);
            }
            crls = new ArrayList();

            // the possible ID_PKCS7_DATA
            Asn1Sequence rsaData = (Asn1Sequence)content[2];
            if (rsaData.Count > 1) {
                DerOctetString rsaDataContent = (DerOctetString)((DerTaggedObject)rsaData[1]).GetObject();
                RSAdata = rsaDataContent.GetOctets();
            }

            // the signerInfos
            int next = 3;
            while (content[next] is DerTaggedObject)
                ++next;
            Asn1Set signerInfos = (Asn1Set)content[next];
            if (signerInfos.Count != 1)
                throw new ArgumentException("This PKCS#7 object has multiple SignerInfos - only one is supported at this time");
            Asn1Sequence signerInfo = (Asn1Sequence)signerInfos[0];
            // the positions that we care are
            //     0 - version
            //     1 - the signing certificate serial number
            //     2 - the digest algorithm
            //     3 or 4 - digestEncryptionAlgorithm
            //     4 or 5 - encryptedDigest
            signerversion = ((DerInteger)signerInfo[0]).Value.IntValue;
            // Get the signing certificate
            Asn1Sequence issuerAndSerialNumber = (Asn1Sequence)signerInfo[1];
            BigInteger serialNumber = ((DerInteger)issuerAndSerialNumber[1]).Value;
            foreach (X509Certificate cert in certs) {
                if (serialNumber.Equals(cert.SerialNumber)) {
                    signCert = cert;
                    break;
                }
            }
            if (signCert == null) {
                throw new ArgumentException("Can't find signing certificate with serial " + serialNumber.ToString(16));
            }
            digestAlgorithm = ((DerObjectIdentifier)((Asn1Sequence)signerInfo[2])[0]).Id;
            next = 3;
            if (signerInfo[next] is Asn1TaggedObject) {
                Asn1TaggedObject tagsig = (Asn1TaggedObject)signerInfo[next];
                Asn1Sequence sseq = (Asn1Sequence)tagsig.GetObject();
                MemoryStream bOut = new MemoryStream();
                Asn1OutputStream dout = new Asn1OutputStream(bOut);
                try {
                    Asn1EncodableVector attribute = new Asn1EncodableVector();
                    for (int k = 0; k < sseq.Count; ++k) {
                        attribute.Add(sseq[k]);
                    }
                    dout.WriteObject(new DerSet(attribute));
                    dout.Close();
                }
                catch (IOException){}
                sigAttr = bOut.ToArray();

                for (int k = 0; k < sseq.Count; ++k) {
                    Asn1Sequence seq2 = (Asn1Sequence)sseq[k];
                    if (((DerObjectIdentifier)seq2[0]).Id.Equals(ID_MESSAGE_DIGEST)) {
                        Asn1Set sset = (Asn1Set)seq2[1];
                        digestAttr = ((DerOctetString)sset[0]).GetOctets();
                        break;
                    }
                }
                if (digestAttr == null)
                    throw new ArgumentException("Authenticated attribute is missing the digest.");
                ++next;
            }
            digestEncryptionAlgorithm = ((DerObjectIdentifier)((Asn1Sequence)signerInfo[next++])[0]).Id;
            digest = ((DerOctetString)signerInfo[next]).GetOctets();
            if (RSAdata != null || digestAttr != null) {
                messageDigest = GetHashClass();
            }
            sig = SignerUtilities.GetSigner(GetDigestAlgorithm());
            sig.Init(false, signCert.GetPublicKey());
        }
Beispiel #12
0
        /// <summary>
        /// Zertifikat von einer URL herunterladen
        /// </summary>
        /// <param name="downloadUrl">Die URL von der das Zertifikat heruntergeladen werden soll</param>
        /// <returns>Zertifikat (mit zusätzlichen Zertifikaten, damit eine vollständige Zertifikat-Kette erstellt werden kann)</returns>
        /// <remarks>
        /// Die URL wird von der Funktion <see cref="QueryOrderStatusAsync"/> zurückgeliefert, wenn der <see cref="OstcOrderStatus"/>
        /// den Wert <see cref="OstcOrderStatus.Successful"/> hat.
        /// </remarks>
        public async Task<IReadOnlyList<X509Certificate>> DownloadCertificateAsync(Uri downloadUrl)
        {
            var request = new RestRequest(downloadUrl);
            var response = await Client.Execute(request);
            var certData = response.RawBytes;
            
            var parser = new X509CertificateParser();
            var certs = parser.ReadCertificates(certData).Cast<X509Certificate>().ToList();

            return certs;
        }