summary refs log tree commit diff
path: root/crypto/src/pkix/PkixCertPathValidatorUtilities.cs
blob: 731f8dfe0b65cb5d358eea080a506cf6d019675e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;

using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Asn1.IsisMtt;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities;
using Org.BouncyCastle.Utilities.Collections;
using Org.BouncyCastle.Utilities.Date;
using Org.BouncyCastle.X509;
using Org.BouncyCastle.X509.Extension;
using Org.BouncyCastle.X509.Store;

namespace Org.BouncyCastle.Pkix
{
	/// <summary>
	/// Summary description for PkixCertPathValidatorUtilities.
	/// </summary>
	internal static class PkixCertPathValidatorUtilities
	{
		private static readonly PkixCrlUtilities CrlUtilities = new PkixCrlUtilities();

		internal static readonly string ANY_POLICY = "2.5.29.32.0";

		internal static readonly string CRL_NUMBER = X509Extensions.CrlNumber.Id;

		/// <summary>
		/// key usage bits
		/// </summary>
		internal static readonly int KEY_CERT_SIGN = 5;
		internal static readonly int CRL_SIGN = 6;

		//internal static readonly string[] crlReasons = new string[]
		//{
		//	"unspecified",
		//	"keyCompromise",
		//	"cACompromise",
		//	"affiliationChanged",
		//	"superseded",
		//	"cessationOfOperation",
		//	"certificateHold",
		//	"unknown",
		//	"removeFromCRL",
		//	"privilegeWithdrawn",
		//	"aACompromise"
		//};

		/// <summary>
		/// Search the given Set of TrustAnchor's for one that is the
		/// issuer of the given X509 certificate.
		/// </summary>
		/// <param name="cert">the X509 certificate</param>
		/// <param name="trustAnchors">a Set of TrustAnchor's</param>
		/// <returns>the <code>TrustAnchor</code> object if found or
		/// <code>null</code> if not.
		/// </returns>
		/// @exception
		internal static TrustAnchor FindTrustAnchor(
			X509Certificate	cert,
			ISet			trustAnchors)
		{
			IEnumerator iter = trustAnchors.GetEnumerator();
			TrustAnchor trust = null;
			AsymmetricKeyParameter trustPublicKey = null;
			Exception invalidKeyEx = null;

			X509CertStoreSelector certSelectX509 = new X509CertStoreSelector();

			try
			{
				certSelectX509.Subject = GetIssuerPrincipal(cert);
			}
			catch (IOException ex)
			{
				throw new Exception("Cannot set subject search criteria for trust anchor.", ex);
			}

			while (iter.MoveNext() && trust == null)
			{
				trust = (TrustAnchor) iter.Current;
				if (trust.TrustedCert != null)
				{
					if (certSelectX509.Match(trust.TrustedCert))
					{
						trustPublicKey = trust.TrustedCert.GetPublicKey();
					}
					else
					{
						trust = null;
					}
				}
				else if (trust.CAName != null && trust.CAPublicKey != null)
				{
					try
					{
						X509Name certIssuer = GetIssuerPrincipal(cert);
						X509Name caName = new X509Name(trust.CAName);

						if (certIssuer.Equivalent(caName, true))
						{
							trustPublicKey = trust.CAPublicKey;
						}
						else
						{
							trust = null;
						}
					}
					catch (InvalidParameterException)
					{
						trust = null;
					}
				}
				else
				{
					trust = null;
				}

				if (trustPublicKey != null)
				{
					try
					{
						cert.Verify(trustPublicKey);
					}
					catch (Exception ex)
					{
						invalidKeyEx = ex;
						trust = null;
					}
				}
			}

			if (trust == null && invalidKeyEx != null)
			{
				throw new Exception("TrustAnchor found but certificate validation failed.", invalidKeyEx);
			}

			return trust;
		}

        internal static bool IsIssuerTrustAnchor(
            X509Certificate cert,
            ISet trustAnchors)
        {
            try
            {
                return FindTrustAnchor(cert, trustAnchors) != null;
            }
            catch (Exception)
            {
                return false;
            }
        }

		internal static void AddAdditionalStoresFromAltNames(
			X509Certificate	cert,
			PkixParameters	pkixParams)
		{
			// if in the IssuerAltName extension an URI
			// is given, add an additinal X.509 store
			if (cert.GetIssuerAlternativeNames() != null)
			{
				IEnumerator it = cert.GetIssuerAlternativeNames().GetEnumerator();
				while (it.MoveNext())
				{
					// look for URI
					IList list = (IList)it.Current;
					//if (list[0].Equals(new Integer(GeneralName.UniformResourceIdentifier)))
					if (list[0].Equals(GeneralName.UniformResourceIdentifier))
					{
						// found
						string temp = (string)list[1];
						AddAdditionalStoreFromLocation(temp, pkixParams);
					}
				}
			}
		}

		internal static DateTime GetValidDate(PkixParameters paramsPKIX)
		{
			DateTimeObject validDate = paramsPKIX.Date;

			if (validDate == null)
				return DateTime.UtcNow;

			return validDate.Value;
		}

		/// <summary>
		/// Returns the issuer of an attribute certificate or certificate.
		/// </summary>
		/// <param name="obj">The attribute certificate or certificate.</param>
		/// <returns>The issuer as <code>X500Principal</code>.</returns>
		internal static X509Name GetIssuerPrincipal(object obj)
		{
			if (obj is X509Certificate cert)
				return cert.IssuerDN;
			if (obj is X509V2AttributeCertificate attrCert)
				return attrCert.Issuer.GetPrincipals()[0];
			throw new InvalidOperationException();
		}

		internal static X509Name GetIssuerPrincipal(X509V2AttributeCertificate attrCert)
		{
			return attrCert.Issuer.GetPrincipals()[0];
		}

		internal static X509Name GetIssuerPrincipal(X509Certificate cert)
		{
			return cert.IssuerDN;
		}

		internal static bool IsSelfIssued(
			X509Certificate cert)
		{
			return cert.SubjectDN.Equivalent(cert.IssuerDN, true);
		}

		internal static AlgorithmIdentifier GetAlgorithmIdentifier(
			AsymmetricKeyParameter key)
		{
			try
			{
				SubjectPublicKeyInfo info = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(key);

				return info.AlgorithmID;
			}
			catch (Exception e)
			{
				throw new PkixCertPathValidatorException("Subject public key cannot be decoded.", e);
			}
		}

		internal static bool IsAnyPolicy(
			ISet policySet)
		{
			return policySet == null || policySet.Contains(ANY_POLICY) || policySet.Count == 0;
		}

		internal static void AddAdditionalStoreFromLocation(
			string			location,
			PkixParameters	pkixParams)
		{
			if (pkixParams.IsAdditionalLocationsEnabled)
			{
				try
				{
					if (Platform.StartsWith(location, "ldap://"))
					{
						// ldap://directory.d-trust.net/CN=D-TRUST
						// Qualified CA 2003 1:PN,O=D-Trust GmbH,C=DE
						// skip "ldap://"
						location = location.Substring(7);
						// after first / baseDN starts
						string url;//, baseDN;
						int slashPos = location.IndexOf('/');
						if (slashPos != -1)
						{
							url = "ldap://" + location.Substring(0, slashPos);
//							baseDN = location.Substring(slashPos);
						}
						else
						{
							url = "ldap://" + location;
//							baseDN = nsull;
						}

						throw Platform.CreateNotImplementedException("LDAP cert/CRL stores");

						// use all purpose parameters
						//X509LDAPCertStoreParameters ldapParams = new X509LDAPCertStoreParameters.Builder(
						//                                url, baseDN).build();
						//pkixParams.AddAdditionalStore(X509Store.getInstance(
						//    "CERTIFICATE/LDAP", ldapParams));
						//pkixParams.AddAdditionalStore(X509Store.getInstance(
						//    "CRL/LDAP", ldapParams));
						//pkixParams.AddAdditionalStore(X509Store.getInstance(
						//    "ATTRIBUTECERTIFICATE/LDAP", ldapParams));
						//pkixParams.AddAdditionalStore(X509Store.getInstance(
						//    "CERTIFICATEPAIR/LDAP", ldapParams));
					}
				}
				catch (Exception)
				{
					// cannot happen
					throw new Exception("Exception adding X.509 stores.");
				}
			}
		}

		private static BigInteger GetSerialNumber(
			object cert)
		{
			if (cert is X509Certificate)
			{
				return ((X509Certificate)cert).SerialNumber;
			}
			else
			{
				return ((X509V2AttributeCertificate)cert).SerialNumber;
			}
		}

		//
		// policy checking
		//

		internal static ISet GetQualifierSet(Asn1Sequence qualifiers)
		{
			ISet pq = new HashSet();

			if (qualifiers == null)
				return pq;

			foreach (Asn1Encodable ae in qualifiers)
			{
				try
				{
					pq.Add(PolicyQualifierInfo.GetInstance(Asn1Object.FromByteArray(ae.GetEncoded())));
					//pq.Add(PolicyQualifierInfo.GetInstance(ae.ToAsn1Object()));
				}
				catch (IOException ex)
				{
					throw new PkixCertPathValidatorException("Policy qualifier info cannot be decoded.", ex);
				}
			}

			return pq;
		}

		internal static PkixPolicyNode RemovePolicyNode(PkixPolicyNode validPolicyTree,
			IList<PkixPolicyNode>[] policyNodes, PkixPolicyNode _node)
		{
			PkixPolicyNode _parent = _node.Parent;

			if (validPolicyTree == null)
			{
				return null;
			}

			if (_parent == null)
			{
				for (int j = 0; j < policyNodes.Length; j++)
				{
					policyNodes[j] = new List<PkixPolicyNode>();
				}

				return null;
			}
			else
			{
				_parent.RemoveChild(_node);
				RemovePolicyNodeRecurse(policyNodes, _node);

				return validPolicyTree;
			}
		}

		private static void RemovePolicyNodeRecurse(IList<PkixPolicyNode>[] policyNodes, PkixPolicyNode _node)
		{
			policyNodes[_node.Depth].Remove(_node);

			if (_node.HasChildren)
			{
				foreach (PkixPolicyNode _child in _node.Children)
				{
					RemovePolicyNodeRecurse(policyNodes, _child);
				}
			}
		}

		internal static void PrepareNextCertB1(
			int i,
			IList[] policyNodes,
			string id_p,
			IDictionary m_idp,
			X509Certificate cert)
		{
			bool idp_found = false;
			IEnumerator nodes_i = policyNodes[i].GetEnumerator();
			while (nodes_i.MoveNext())
			{
				PkixPolicyNode node = (PkixPolicyNode)nodes_i.Current;
				if (node.ValidPolicy.Equals(id_p))
				{
					idp_found = true;
					node.ExpectedPolicies = (ISet)m_idp[id_p];
					break;
				}
			}

			if (!idp_found)
			{
				nodes_i = policyNodes[i].GetEnumerator();
				while (nodes_i.MoveNext())
				{
					PkixPolicyNode node = (PkixPolicyNode)nodes_i.Current;
					if (ANY_POLICY.Equals(node.ValidPolicy))
					{
						ISet pq = null;
						Asn1Sequence policies = null;
						try
						{
							policies = DerSequence.GetInstance(GetExtensionValue(cert, X509Extensions.CertificatePolicies));
						}
						catch (Exception e)
						{
							throw new Exception("Certificate policies cannot be decoded.", e);
						}

						IEnumerator enm = policies.GetEnumerator();
						while (enm.MoveNext())
						{
							PolicyInformation pinfo = null;

							try
							{
								pinfo = PolicyInformation.GetInstance(enm.Current);
							}
							catch (Exception ex)
							{
								throw new Exception("Policy information cannot be decoded.", ex);
							}

							if (ANY_POLICY.Equals(pinfo.PolicyIdentifier.Id))
							{
								try
								{
									pq = GetQualifierSet(pinfo.PolicyQualifiers);
								}
								catch (PkixCertPathValidatorException ex)
								{
									throw new PkixCertPathValidatorException(
										"Policy qualifier info set could not be built.", ex);
								}
								break;
							}
						}
						bool ci = false;
						ISet critExtOids = cert.GetCriticalExtensionOids();
						if (critExtOids != null)
						{
							ci = critExtOids.Contains(X509Extensions.CertificatePolicies.Id);
						}

						PkixPolicyNode p_node = node.Parent;
						if (ANY_POLICY.Equals(p_node.ValidPolicy))
						{
							PkixPolicyNode c_node = new PkixPolicyNode(new List<PkixPolicyNode>(), i, (ISet)m_idp[id_p],
								p_node, pq, id_p, ci);
							p_node.AddChild(c_node);
							policyNodes[i].Add(c_node);
						}
						break;
					}
				}
			}
		}

		internal static PkixPolicyNode PrepareNextCertB2(int i, IList<PkixPolicyNode>[] policyNodes, string id_p,
			PkixPolicyNode validPolicyTree)
		{
			int pos = 0;

			// Copy to avoid RemoveAt calls interfering with enumeration
            foreach (var node in new List<PkixPolicyNode>(policyNodes[i]))
			{
				if (!node.ValidPolicy.Equals(id_p))
                {
					++pos;
					continue;
                }

				node.Parent.RemoveChild(node);

				policyNodes[i].RemoveAt(pos);

				for (int k = i - 1; k >= 0; k--)
				{
					var nodes = policyNodes[k];

					for (int l = 0; l < nodes.Count; l++)
					{
						var node2 = nodes[l];
						if (!node2.HasChildren)
						{
							validPolicyTree = RemovePolicyNode(validPolicyTree, policyNodes, node2);
							if (validPolicyTree == null)
								break;
						}
					}
				}
			}
			return validPolicyTree;
		}

		internal static void GetCertStatus(
			DateTime validDate,
			X509Crl crl,
			object cert,
			CertStatus certStatus)
		{
			X509Crl bcCRL;

			try
			{
				bcCRL = new X509Crl(CertificateList.GetInstance((Asn1Sequence)Asn1Sequence.FromByteArray(crl.GetEncoded())));
			}
			catch (Exception exception)
			{
				throw new Exception("X509Crl could not be created.", exception);
			}

			X509CrlEntry crl_entry = (X509CrlEntry)bcCRL.GetRevokedCertificate(GetSerialNumber(cert));

			if (crl_entry == null)
				return;

			X509Name issuer = GetIssuerPrincipal(cert);

			if (!issuer.Equivalent(crl_entry.GetCertificateIssuer(), true)
				&& !issuer.Equivalent(crl.IssuerDN, true))
            {
                return;
            }

            int reasonCodeValue = CrlReason.Unspecified;

            if (crl_entry.HasExtensions)
            {
                try
                {
                    Asn1Object extValue = GetExtensionValue(crl_entry, X509Extensions.ReasonCode);
                    DerEnumerated reasonCode = DerEnumerated.GetInstance(extValue);
                    if (null != reasonCode)
                    {
                        reasonCodeValue = reasonCode.IntValueExact;
                    }
                }
                catch (Exception e)
                {
                    throw new Exception("Reason code CRL entry extension could not be decoded.", e);
                }
            }

            DateTime revocationDate = crl_entry.RevocationDate;
            if (validDate.Ticks < revocationDate.Ticks)
            {
                switch (reasonCodeValue)
                {
                case CrlReason.Unspecified:
                case CrlReason.KeyCompromise:
                case CrlReason.CACompromise:
                case CrlReason.AACompromise:
                    break;
                default:
                    return;
                }
            }

            // (i) or (j)
            certStatus.Status = reasonCodeValue;
            certStatus.RevocationDate = new DateTimeObject(revocationDate);
        }

		/**
		* Return the next working key inheriting DSA parameters if necessary.
		* <p>
		* This methods inherits DSA parameters from the indexed certificate or
		* previous certificates in the certificate chain to the returned
		* <code>PublicKey</code>. The list is searched upwards, meaning the end
		* certificate is at position 0 and previous certificates are following.
		* </p>
		* <p>
		* If the indexed certificate does not contain a DSA key this method simply
		* returns the public key. If the DSA key already contains DSA parameters
		* the key is also only returned.
		* </p>
		*
		* @param certs The certification path.
		* @param index The index of the certificate which contains the public key
		*            which should be extended with DSA parameters.
		* @return The public key of the certificate in list position
		*         <code>index</code> extended with DSA parameters if applicable.
		* @throws Exception if DSA parameters cannot be inherited.
		*/
		internal static AsymmetricKeyParameter GetNextWorkingKey(
			IList	certs,
			int		index)
		{
			//Only X509Certificate
			X509Certificate cert = (X509Certificate)certs[index];

			AsymmetricKeyParameter pubKey = cert.GetPublicKey();

			if (!(pubKey is DsaPublicKeyParameters))
				return pubKey;

			DsaPublicKeyParameters dsaPubKey = (DsaPublicKeyParameters)pubKey;

			if (dsaPubKey.Parameters != null)
				return dsaPubKey;

			for (int i = index + 1; i < certs.Count; i++)
			{
				X509Certificate parentCert = (X509Certificate)certs[i];
				pubKey = parentCert.GetPublicKey();

				if (!(pubKey is DsaPublicKeyParameters))
				{
					throw new PkixCertPathValidatorException(
						"DSA parameters cannot be inherited from previous certificate.");
				}

				DsaPublicKeyParameters prevDSAPubKey = (DsaPublicKeyParameters)pubKey;

				if (prevDSAPubKey.Parameters == null)
					continue;

				DsaParameters dsaParams = prevDSAPubKey.Parameters;

				try
				{
					return new DsaPublicKeyParameters(dsaPubKey.Y, dsaParams);
				}
				catch (Exception exception)
				{
					throw new Exception(exception.Message);
				}
			}

			throw new PkixCertPathValidatorException("DSA parameters cannot be inherited from previous certificate.");
		}

		internal static DateTime GetValidCertDateFromValidityModel(
			PkixParameters	paramsPkix,
			PkixCertPath	certPath,
			int				index)
		{
			if (paramsPkix.ValidityModel != PkixParameters.ChainValidityModel)
			{
				return GetValidDate(paramsPkix);
			}

			// if end cert use given signing/encryption/... time
			if (index <= 0)
			{
				return GetValidDate(paramsPkix);
				// else use time when previous cert was created
			}

			if (index - 1 == 0)
			{
				DerGeneralizedTime dateOfCertgen = null;
				try
				{
					X509Certificate cert = (X509Certificate)certPath.Certificates[index - 1];
					Asn1OctetString extVal = cert.GetExtensionValue(
						IsisMttObjectIdentifiers.IdIsisMttATDateOfCertGen);
					dateOfCertgen = DerGeneralizedTime.GetInstance(extVal);
				}
				catch (ArgumentException)
				{
					throw new Exception(
						"Date of cert gen extension could not be read.");
				}
				if (dateOfCertgen != null)
				{
					try
					{
						return dateOfCertgen.ToDateTime();
					}
					catch (ArgumentException e)
					{
						throw new Exception(
							"Date from date of cert gen extension could not be parsed.",
							e);
					}
				}
			}

			return ((X509Certificate)certPath.Certificates[index - 1]).NotBefore;
		}

		/// <summary>
		/// Return a Collection of all certificates found
		/// in the stores that are matching the certSelector criteria.
		/// </summary>
		/// <param name="certSelector">an <see cref="ISelector{T}"/> object that will be used to select
		/// the certificates.</param>
		/// <param name="certStores">a List containing only IStore objects. These
		/// are used to search for certificates.</param>
		/// <returns>a Collection of all found <see cref="X509Certificate"/> objects.
		/// May be empty but never <code>null</code>.</returns>
		/// <exception cref="Exception"></exception>
		internal static List<X509Certificate> FindCertificates(ISelector<X509Certificate> certSelector,
			IList<IStore<X509Certificate>> certStores)
		{
			var result = new List<X509Certificate>();
			CollectionUtilities.CollectMatches(result, certSelector, certStores);
			return result;
		}

		/**
		* Add the CRL issuers from the cRLIssuer field of the distribution point or
		* from the certificate if not given to the issuer criterion of the
		* <code>selector</code>.
		* <p>
		* The <code>issuerPrincipals</code> are a collection with a single
		* <code>X500Principal</code> for <code>X509Certificate</code>s. For
		* {@link X509AttributeCertificate}s the issuer may contain more than one
		* <code>X500Principal</code>.
		* </p>
		*
		* @param dp The distribution point.
		* @param issuerPrincipals The issuers of the certificate or attribute
		*            certificate which contains the distribution point.
		* @param selector The CRL selector.
		* @param pkixParams The PKIX parameters containing the cert stores.
		* @throws Exception if an exception occurs while processing.
		* @throws ClassCastException if <code>issuerPrincipals</code> does not
		* contain only <code>X500Principal</code>s.
		*/
		internal static void GetCrlIssuersFromDistributionPoint(
			DistributionPoint		dp,
			ICollection				issuerPrincipals,
			X509CrlStoreSelector	selector,
			PkixParameters			pkixParams)
		{
            IList issuers = Platform.CreateArrayList();
			// indirect CRL
			if (dp.CrlIssuer != null)
			{
				GeneralName[] genNames = dp.CrlIssuer.GetNames();
				// look for a DN
				for (int j = 0; j < genNames.Length; j++)
				{
					if (genNames[j].TagNo == GeneralName.DirectoryName)
					{
						try
						{
							issuers.Add(X509Name.GetInstance(genNames[j].Name.ToAsn1Object()));
						}
						catch (IOException e)
						{
							throw new Exception(
								"CRL issuer information from distribution point cannot be decoded.",
								e);
						}
					}
				}
			}
			else
			{
				/*
				 * certificate issuer is CRL issuer, distributionPoint field MUST be
				 * present.
				 */
				if (dp.DistributionPointName == null)
				{
					throw new Exception(
						"CRL issuer is omitted from distribution point but no distributionPoint field present.");
				}

				// add and check issuer principals
				for (IEnumerator it = issuerPrincipals.GetEnumerator(); it.MoveNext(); )
				{
					issuers.Add((X509Name)it.Current);
				}
			}
			// TODO: is not found although this should correctly add the rel name. selector of Sun is buggy here or PKI test case is invalid
			// distributionPoint
			//        if (dp.getDistributionPoint() != null)
			//        {
			//            // look for nameRelativeToCRLIssuer
			//            if (dp.getDistributionPoint().getType() == DistributionPointName.NAME_RELATIVE_TO_CRL_ISSUER)
			//            {
			//                // append fragment to issuer, only one
			//                // issuer can be there, if this is given
			//                if (issuers.size() != 1)
			//                {
			//                    throw new AnnotatedException(
			//                        "nameRelativeToCRLIssuer field is given but more than one CRL issuer is given.");
			//                }
			//                DEREncodable relName = dp.getDistributionPoint().getName();
			//                Iterator it = issuers.iterator();
			//                List issuersTemp = new ArrayList(issuers.size());
			//                while (it.hasNext())
			//                {
			//                    Enumeration e = null;
			//                    try
			//                    {
			//                        e = ASN1Sequence.getInstance(
			//                            new ASN1InputStream(((X500Principal) it.next())
			//                                .getEncoded()).readObject()).getObjects();
			//                    }
			//                    catch (IOException ex)
			//                    {
			//                        throw new AnnotatedException(
			//                            "Cannot decode CRL issuer information.", ex);
			//                    }
			//                    ASN1EncodableVector v = new ASN1EncodableVector();
			//                    while (e.hasMoreElements())
			//                    {
			//                        v.add((DEREncodable) e.nextElement());
			//                    }
			//                    v.add(relName);
			//                    issuersTemp.add(new X500Principal(new DERSequence(v)
			//                        .getDEREncoded()));
			//                }
			//                issuers.clear();
			//                issuers.addAll(issuersTemp);
			//            }
			//        }

			selector.Issuers = issuers;
		}

		/**
		 * Fetches complete CRLs according to RFC 3280.
		 *
		 * @param dp The distribution point for which the complete CRL
		 * @param cert The <code>X509Certificate</code> or
		 *            {@link org.bouncycastle.x509.X509AttributeCertificate} for
		 *            which the CRL should be searched.
		 * @param currentDate The date for which the delta CRLs must be valid.
		 * @param paramsPKIX The extended PKIX parameters.
		 * @return A <code>Set</code> of <code>X509CRL</code>s with complete
		 *         CRLs.
		 * @throws Exception if an exception occurs while picking the CRLs
		 *             or no CRLs are found.
		 */
		internal static ISet<X509Crl> GetCompleteCrls(DistributionPoint dp, object certObj, DateTime currentDate,
			PkixParameters paramsPKIX)
		{
			var certObjIssuer = GetIssuerPrincipal(certObj);

			X509CrlStoreSelector crlselect = new X509CrlStoreSelector();
			try
			{
				ISet issuers = new HashSet();
				issuers.Add(certObjIssuer);

				GetCrlIssuersFromDistributionPoint(dp, issuers, crlselect, paramsPKIX);
			}
			catch (Exception e)
			{
				throw new Exception("Could not get issuer information from distribution point.", e);
			}

            {
				if (certObj is X509Certificate cert)
				{
					crlselect.CertificateChecking = cert;
				}
				else if (certObj is X509V2AttributeCertificate attrCert)
				{
					crlselect.AttrCertChecking = attrCert;
				}
			}

			crlselect.CompleteCrlEnabled = true;

			ISet<X509Crl> crls = CrlUtilities.FindCrls(crlselect, paramsPKIX, currentDate);
			if (crls.Count < 1)
				throw new Exception("No CRLs found for issuer \"" + certObjIssuer + "\"");

			return crls;
		}

		/**
		 * Fetches delta CRLs according to RFC 3280 section 5.2.4.
		 *
		 * @param currentDate The date for which the delta CRLs must be valid.
		 * @param paramsPKIX The extended PKIX parameters.
		 * @param completeCRL The complete CRL the delta CRL is for.
		 * @return A <code>Set</code> of <code>X509CRL</code>s with delta CRLs.
		 * @throws Exception if an exception occurs while picking the delta
		 *             CRLs.
		 */
		internal static ISet<X509Crl> GetDeltaCrls(
			DateTime		currentDate,
			PkixParameters	paramsPKIX,
			X509Crl			completeCRL)
		{
			X509CrlStoreSelector deltaSelect = new X509CrlStoreSelector();

			// 5.2.4 (a)
			try
			{
                IList deltaSelectIssuer = Platform.CreateArrayList();
				deltaSelectIssuer.Add(completeCRL.IssuerDN);
				deltaSelect.Issuers = deltaSelectIssuer;
			}
			catch (IOException e)
			{
				throw new Exception("Cannot extract issuer from CRL.", e);
			}

			BigInteger completeCRLNumber = null;
			try
			{
				Asn1Object asn1Object = GetExtensionValue(completeCRL, X509Extensions.CrlNumber);
				if (asn1Object != null)
				{
					completeCRLNumber = CrlNumber.GetInstance(asn1Object).PositiveValue;
				}
			}
			catch (Exception e)
			{
				throw new Exception(
					"CRL number extension could not be extracted from CRL.", e);
			}

			// 5.2.4 (b)
			byte[] idp = null;

			try
			{
				Asn1Object obj = GetExtensionValue(completeCRL, X509Extensions.IssuingDistributionPoint);
				if (obj != null)
				{
					idp = obj.GetDerEncoded();
				}
			}
			catch (Exception e)
			{
				throw new Exception(
					"Issuing distribution point extension value could not be read.",
					e);
			}

			// 5.2.4 (d)

			deltaSelect.MinCrlNumber = (completeCRLNumber == null)
				?	null
				:	completeCRLNumber.Add(BigInteger.One);

			deltaSelect.IssuingDistributionPoint = idp;
			deltaSelect.IssuingDistributionPointEnabled = true;

			// 5.2.4 (c)
			deltaSelect.MaxBaseCrlNumber = completeCRLNumber;

			// find delta CRLs
			ISet<X509Crl> temp = CrlUtilities.FindCrls(deltaSelect, paramsPKIX, currentDate);

			var result = new HashSet<X509Crl>();

			foreach (X509Crl crl in temp)
			{
				if (isDeltaCrl(crl))
				{
					result.Add(crl);
				}
			}

			return result;
		}

		private static bool isDeltaCrl(
			X509Crl crl)
		{
			ISet critical = crl.GetCriticalExtensionOids();

			return critical.Contains(X509Extensions.DeltaCrlIndicator.Id);
		}

		internal static void AddAdditionalStoresFromCrlDistributionPoint(
			CrlDistPoint	crldp,
			PkixParameters	pkixParams)
		{
			if (crldp != null)
			{
				DistributionPoint[] dps = null;
				try
				{
					dps = crldp.GetDistributionPoints();
				}
				catch (Exception e)
				{
					throw new Exception(
						"Distribution points could not be read.", e);
				}
				for (int i = 0; i < dps.Length; i++)
				{
					DistributionPointName dpn = dps[i].DistributionPointName;
					// look for URIs in fullName
					if (dpn != null)
					{
						if (dpn.PointType == DistributionPointName.FullName)
						{
							GeneralName[] genNames = GeneralNames.GetInstance(
								dpn.Name).GetNames();
							// look for an URI
							for (int j = 0; j < genNames.Length; j++)
							{
								if (genNames[j].TagNo == GeneralName.UniformResourceIdentifier)
								{
									string location = DerIA5String.GetInstance(genNames[j].Name).GetString();
									AddAdditionalStoreFromLocation(location, pkixParams);
								}
							}
						}
					}
				}
			}
		}

		internal static bool ProcessCertD1i(int index, IList<PkixPolicyNode>[] policyNodes, DerObjectIdentifier	pOid,
			ISet pq)
		{
			foreach (var node in policyNodes[index - 1])
			{
				if (node.ExpectedPolicies.Contains(pOid.Id))
				{
					var childExpectedPolicies = new HashSet();
					childExpectedPolicies.Add(pOid.Id);

                    var child = new PkixPolicyNode(new List<PkixPolicyNode>(), index, childExpectedPolicies, node, pq,
						pOid.Id, false);
					node.AddChild(child);
					policyNodes[index].Add(child);

					return true;
				}
			}

			return false;
		}

		internal static void ProcessCertD1ii(int index, IList<PkixPolicyNode>[] policyNodes,
			DerObjectIdentifier _poid, ISet _pq)
		{
			foreach (var _node in policyNodes[index - 1])
			{
				if (ANY_POLICY.Equals(_node.ValidPolicy))
				{
					ISet _childExpectedPolicies = new HashSet();
					_childExpectedPolicies.Add(_poid.Id);

                    var _child = new PkixPolicyNode(new List<PkixPolicyNode>(), index, _childExpectedPolicies, _node,
						_pq, _poid.Id, false);
					_node.AddChild(_child);
					policyNodes[index].Add(_child);

					return;
				}
			}
		}

		/**
		* Find the issuer certificates of a given certificate.
		*
		* @param cert
		*            The certificate for which an issuer should be found.
		* @param pkixParams
		* @return A <code>Collection</code> object containing the issuer
		*         <code>X509Certificate</code>s. Never <code>null</code>.
		*
		* @exception Exception
		*                if an error occurs.
		*/
		internal static HashSet<X509Certificate> FindIssuerCerts(
			X509Certificate			cert,
			PkixBuilderParameters	pkixParams)
		{
			X509CertStoreSelector certSelector = new X509CertStoreSelector();
			try
			{
				certSelector.Subject = cert.IssuerDN;
			}
			catch (IOException ex)
			{
				throw new Exception(
					"Subject criteria for certificate selector to find issuer certificate could not be set.", ex);
			}

			var certs = new HashSet<X509Certificate>();
			try
			{
				CollectionUtilities.CollectMatches(certs, certSelector, pkixParams.GetStoresCert());
			}
			catch (Exception e)
			{
				throw new Exception("Issuer certificate cannot be searched.", e);
			}

			return certs;
		}

		/// <summary>
		/// Extract the value of the given extension, if it exists.
		/// </summary>
		/// <param name="ext">The extension object.</param>
		/// <param name="oid">The object identifier to obtain.</param>
		/// <returns>Asn1Object</returns>
		/// <exception cref="Exception">if the extension cannot be read.</exception>
		internal static Asn1Object GetExtensionValue(
			IX509Extension		ext,
			DerObjectIdentifier	oid)
		{
			Asn1OctetString bytes = ext.GetExtensionValue(oid);

			if (bytes == null)
				return null;

			return X509ExtensionUtilities.FromExtensionValue(bytes);
		}
	}
}