summaryrefslogtreecommitdiffstats
path: root/third_party/js/PKI.js/src/CertificateChainValidationEngine.ts
blob: 66d57b035cd7eb0a66e664679c0968eb0692e652 (plain)
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
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
import * as asn1js from "asn1js";
import * as pvtsutils from "pvtsutils";
import * as pvutils from "pvutils";
import { AuthorityKeyIdentifier } from "./AuthorityKeyIdentifier";
import { BasicOCSPResponse } from "./BasicOCSPResponse";
import { Certificate } from "./Certificate";
import { CertificateRevocationList } from "./CertificateRevocationList";
import * as common from "./common";
import * as Helpers from "./Helpers";
import { GeneralName } from "./GeneralName";
import { id_AnyPolicy, id_AuthorityInfoAccess, id_AuthorityKeyIdentifier, id_BasicConstraints, id_CertificatePolicies, id_CRLDistributionPoints, id_FreshestCRL, id_InhibitAnyPolicy, id_KeyUsage, id_NameConstraints, id_PolicyConstraints, id_PolicyMappings, id_SubjectAltName, id_SubjectKeyIdentifier } from "./ObjectIdentifiers";
import { RelativeDistinguishedNames } from "./RelativeDistinguishedNames";
import { GeneralSubtree } from "./GeneralSubtree";
import { EMPTY_STRING } from "./constants";

const TRUSTED_CERTS = "trustedCerts";
const CERTS = "certs";
const CRLS = "crls";
const OCSPS = "ocsps";
const CHECK_DATE = "checkDate";
const FIND_ORIGIN = "findOrigin";
const FIND_ISSUER = "findIssuer";


export enum ChainValidationCode {
  unknown = -1,
  success = 0,
  noRevocation = 11,
  noPath = 60,
  noValidPath = 97,
}

export class ChainValidationError extends Error {

  public static readonly NAME = "ChainValidationError";

  public code: ChainValidationCode;

  constructor(code: ChainValidationCode, message: string) {
    super(message);

    this.name = ChainValidationError.NAME;
    this.code = code;
    this.message = message;
  }

}

export interface CertificateChainValidationEngineVerifyResult {
  result: boolean;
  resultCode: number;
  resultMessage: string;
  error?: Error | ChainValidationError;
  authConstrPolicies?: string[];
  userConstrPolicies?: string[];
  explicitPolicyIndicator?: boolean;
  policyMappings?: string[];
  certificatePath?: Certificate[];
}

export type FindOriginCallback = (certificate: Certificate, validationEngine: CertificateChainValidationEngine) => string;
export type FindIssuerCallback = (certificate: Certificate, validationEngine: CertificateChainValidationEngine, crypto?: common.ICryptoEngine) => Promise<Certificate[]>;

export interface CertificateChainValidationEngineParameters {
  trustedCerts?: Certificate[];
  certs?: Certificate[];
  crls?: CertificateRevocationList[];
  ocsps?: BasicOCSPResponse[];
  checkDate?: Date;
  findOrigin?: FindOriginCallback;
  findIssuer?: FindIssuerCallback;
}
interface CrlAndCertificate {
  crl: CertificateRevocationList;
  certificate: Certificate;
}

interface FindCrlResult {
  status: number;
  statusMessage: string;
  result?: CrlAndCertificate[];
}

export interface CertificateChainValidationEngineVerifyParams {
  initialPolicySet?: string[];
  initialExplicitPolicy?: boolean;
  initialPolicyMappingInhibit?: boolean;
  initialInhibitPolicy?: boolean;
  initialPermittedSubtreesSet?: GeneralSubtree[];
  initialExcludedSubtreesSet?: GeneralSubtree[];
  initialRequiredNameForms?: GeneralSubtree[];
  passedWhenNotRevValues?: boolean;
}

/**
 * Returns `true` if the certificate is in the trusted list, otherwise `false`
 * @param cert A certificate that is expected to be in the trusted list
 * @param trustedList List of trusted certificates
 * @returns
 */
function isTrusted(cert: Certificate, trustedList: Certificate[]): boolean {
  for (let i = 0; i < trustedList.length; i++) {
    if (pvtsutils.BufferSourceConverter.isEqual(cert.tbsView, trustedList[i].tbsView)) {
      return true;
    }
  }

  return false;
}

/**
 * Represents a chain-building engine for {@link Certificate} certificates.
 *
 * @example
 * ```js The following example demonstrates how to verify certificate chain
 * const rootCa = pkijs.Certificate.fromBER(certRaw1);
 * const intermediateCa = pkijs.Certificate.fromBER(certRaw2);
 * const leafCert = pkijs.Certificate.fromBER(certRaw3);
 * const crl1 = pkijs.CertificateRevocationList.fromBER(crlRaw1);
 * const ocsp1 = pkijs.BasicOCSPResponse.fromBER(ocspRaw1);
 *
 * const chainEngine = new pkijs.CertificateChainValidationEngine({
 *   certs: [rootCa, intermediateCa, leafCert],
 *   crls: [crl1],
 *   ocsps: [ocsp1],
 *   checkDate: new Date("2015-07-13"), // optional
 *   trustedCerts: [rootCa],
 * });
 *
 * const chain = await chainEngine.verify();
 * ```
 */
export class CertificateChainValidationEngine {

  /**
   * Array of pre-defined trusted (by user) certificates
   */
  public trustedCerts: Certificate[];
  /**
   * Array with certificate chain. Could be only one end-user certificate in there!
   */
  public certs: Certificate[];
  /**
   * Array of all CRLs for all certificates from certificate chain
   */
  public crls: CertificateRevocationList[];
  /**
   * Array of all OCSP responses
   */
  public ocsps: BasicOCSPResponse[];
  /**
   * The date at which the check would be
   */
  public checkDate: Date;
  /**
   * The date at which the check would be
   */
  public findOrigin: FindOriginCallback;
  /**
   * The date at which the check would be
   */
  public findIssuer: FindIssuerCallback;

  /**
   * Constructor for CertificateChainValidationEngine class
   * @param parameters
   */
  constructor(parameters: CertificateChainValidationEngineParameters = {}) {
    //#region Internal properties of the object
    this.trustedCerts = pvutils.getParametersValue(parameters, TRUSTED_CERTS, this.defaultValues(TRUSTED_CERTS));
    this.certs = pvutils.getParametersValue(parameters, CERTS, this.defaultValues(CERTS));
    this.crls = pvutils.getParametersValue(parameters, CRLS, this.defaultValues(CRLS));
    this.ocsps = pvutils.getParametersValue(parameters, OCSPS, this.defaultValues(OCSPS));
    this.checkDate = pvutils.getParametersValue(parameters, CHECK_DATE, this.defaultValues(CHECK_DATE));
    this.findOrigin = pvutils.getParametersValue(parameters, FIND_ORIGIN, this.defaultValues(FIND_ORIGIN));
    this.findIssuer = pvutils.getParametersValue(parameters, FIND_ISSUER, this.defaultValues(FIND_ISSUER));
    //#endregion
  }

  public static defaultFindOrigin(certificate: Certificate, validationEngine: CertificateChainValidationEngine): string {
    //#region Firstly encode TBS for certificate
    if (certificate.tbsView.byteLength === 0) {
      certificate.tbsView = new Uint8Array(certificate.encodeTBS().toBER());
    }
    //#endregion

    //#region Search in Intermediate Certificates
    for (const localCert of validationEngine.certs) {
      //#region Firstly encode TBS for certificate
      if (localCert.tbsView.byteLength === 0) {
        localCert.tbsView = new Uint8Array(localCert.encodeTBS().toBER());
      }
      //#endregion

      if (pvtsutils.BufferSourceConverter.isEqual(certificate.tbsView, localCert.tbsView))
        return "Intermediate Certificates";
    }
    //#endregion

    //#region Search in Trusted Certificates
    for (const trustedCert of validationEngine.trustedCerts) {
      //#region Firstly encode TBS for certificate
      if (trustedCert.tbsView.byteLength === 0)
        trustedCert.tbsView = new Uint8Array(trustedCert.encodeTBS().toBER());
      //#endregion

      if (pvtsutils.BufferSourceConverter.isEqual(certificate.tbsView, trustedCert.tbsView))
        return "Trusted Certificates";
    }
    //#endregion

    return "Unknown";
  }

  public async defaultFindIssuer(certificate: Certificate, validationEngine: CertificateChainValidationEngine, crypto = common.getCrypto(true)): Promise<Certificate[]> {
    //#region Initial variables
    const result: Certificate[] = [];

    let keyIdentifier: asn1js.OctetString | null = null;
    let authorityCertIssuer: GeneralName[] | null = null;
    let authorityCertSerialNumber: asn1js.Integer | null = null;
    //#endregion

    //#region Speed-up searching in case of self-signed certificates
    if (certificate.subject.isEqual(certificate.issuer)) {
      try {
        const verificationResult = await certificate.verify(undefined, crypto);
        if (verificationResult) {
          return [certificate];
        }
      }
      catch (ex) {
        // nothing
      }
    }
    //#endregion

    //#region Find values to speed-up search
    if (certificate.extensions) {
      for (const extension of certificate.extensions) {
        if (extension.extnID === id_AuthorityKeyIdentifier && extension.parsedValue instanceof AuthorityKeyIdentifier) {
          if (extension.parsedValue.keyIdentifier) {
            keyIdentifier = extension.parsedValue.keyIdentifier;
          } else {
            if (extension.parsedValue.authorityCertIssuer) {
              authorityCertIssuer = extension.parsedValue.authorityCertIssuer;
            }
            if (extension.parsedValue.authorityCertSerialNumber) {
              authorityCertSerialNumber = extension.parsedValue.authorityCertSerialNumber;
            }
          }

          break;
        }
      }
    }
    //#endregion

    // Aux function
    function checkCertificate(possibleIssuer: Certificate): void {
      //#region Firstly search for appropriate extensions
      if (keyIdentifier !== null) {
        if (possibleIssuer.extensions) {
          let extensionFound = false;

          for (const extension of possibleIssuer.extensions) {
            if (extension.extnID === id_SubjectKeyIdentifier && extension.parsedValue) {
              extensionFound = true;

              if (pvtsutils.BufferSourceConverter.isEqual(extension.parsedValue.valueBlock.valueHex, keyIdentifier.valueBlock.valueHexView)) {
                result.push(possibleIssuer);
              }

              break;
            }
          }

          if (extensionFound) {
            return;
          }
        }
      }
      //#endregion

      //#region Now search for authorityCertSerialNumber
      let authorityCertSerialNumberEqual = false;

      if (authorityCertSerialNumber !== null)
        authorityCertSerialNumberEqual = possibleIssuer.serialNumber.isEqual(authorityCertSerialNumber);
      //#endregion

      //#region And at least search for Issuer data
      if (authorityCertIssuer !== null) {
        if (possibleIssuer.subject.isEqual(authorityCertIssuer)) {
          if (authorityCertSerialNumberEqual)
            result.push(possibleIssuer);
        }
      }
      else {
        if (certificate.issuer.isEqual(possibleIssuer.subject))
          result.push(possibleIssuer);
      }
      //#endregion
    }

    // Search in Trusted Certificates
    for (const trustedCert of validationEngine.trustedCerts) {
      checkCertificate(trustedCert);
    }

    // Search in Intermediate Certificates
    for (const intermediateCert of validationEngine.certs) {
      checkCertificate(intermediateCert);
    }

    // Now perform certificate verification checking
    for (let i = 0; i < result.length; i++) {
      try {
        const verificationResult = await certificate.verify(result[i], crypto);
        if (verificationResult === false)
          result.splice(i, 1);
      }
      catch (ex) {
        result.splice(i, 1); // Something wrong, remove the certificate
      }
    }

    return result;
  }

  /**
   * Returns default values for all class members
   * @param memberName String name for a class member
   * @returns Default value
   */
  public defaultValues(memberName: typeof TRUSTED_CERTS): Certificate[];
  public defaultValues(memberName: typeof CERTS): Certificate[];
  public defaultValues(memberName: typeof CRLS): CertificateRevocationList[];
  public defaultValues(memberName: typeof OCSPS): BasicOCSPResponse[];
  public defaultValues(memberName: typeof CHECK_DATE): Date;
  public defaultValues(memberName: typeof FIND_ORIGIN): FindOriginCallback;
  public defaultValues(memberName: typeof FIND_ISSUER): FindIssuerCallback;
  public defaultValues(memberName: string): any {
    switch (memberName) {
      case TRUSTED_CERTS:
        return [];
      case CERTS:
        return [];
      case CRLS:
        return [];
      case OCSPS:
        return [];
      case CHECK_DATE:
        return new Date();
      case FIND_ORIGIN:
        return CertificateChainValidationEngine.defaultFindOrigin;
      case FIND_ISSUER:
        return this.defaultFindIssuer;
      default:
        throw new Error(`Invalid member name for CertificateChainValidationEngine class: ${memberName}`);
    }
  }

  public async sort(passedWhenNotRevValues = false, crypto = common.getCrypto(true)): Promise<Certificate[]> {
    // Initial variables
    const localCerts: Certificate[] = [];

    //#region Building certificate path
    const buildPath = async (certificate: Certificate, crypto: common.ICryptoEngine): Promise<Certificate[][]> => {
      const result: Certificate[][] = [];

      // Aux function checking array for unique elements
      function checkUnique(array: Certificate[]): boolean {
        let unique = true;

        for (let i = 0; i < array.length; i++) {
          for (let j = 0; j < array.length; j++) {
            if (j === i)
              continue;

            if (array[i] === array[j]) {
              unique = false;
              break;
            }
          }

          if (!unique)
            break;
        }

        return unique;
      }

      if (isTrusted(certificate, this.trustedCerts)) {
        return [[certificate]];
      }

      const findIssuerResult = await this.findIssuer(certificate, this, crypto);
      if (findIssuerResult.length === 0) {
        throw new Error("No valid certificate paths found");
      }

      for (let i = 0; i < findIssuerResult.length; i++) {
        if (pvtsutils.BufferSourceConverter.isEqual(findIssuerResult[i].tbsView, certificate.tbsView)) {
          result.push([findIssuerResult[i]]);
          continue;
        }

        const buildPathResult = await buildPath(findIssuerResult[i], crypto);

        for (let j = 0; j < buildPathResult.length; j++) {
          const copy = buildPathResult[j].slice();
          copy.splice(0, 0, findIssuerResult[i]);

          if (checkUnique(copy))
            result.push(copy);
          else
            result.push(buildPathResult[j]);
        }
      }

      return result;
    };
    //#endregion

    //#region Find CRL for specific certificate
    const findCRL = async (certificate: Certificate): Promise<FindCrlResult> => {
      //#region Initial variables
      const issuerCertificates: Certificate[] = [];
      const crls: CertificateRevocationList[] = [];
      const crlsAndCertificates: CrlAndCertificate[] = [];
      //#endregion

      //#region Find all possible CRL issuers
      issuerCertificates.push(...localCerts.filter(element => certificate.issuer.isEqual(element.subject)));
      if (issuerCertificates.length === 0) {
        return {
          status: 1,
          statusMessage: "No certificate's issuers"
        };
      }
      //#endregion

      //#region Find all CRLs for certificate's issuer
      crls.push(...this.crls.filter(o => o.issuer.isEqual(certificate.issuer)));
      if (crls.length === 0) {
        return {
          status: 2,
          statusMessage: "No CRLs for specific certificate issuer"
        };
      }
      //#endregion

      //#region Find specific certificate of issuer for each CRL
      for (let i = 0; i < crls.length; i++) {
        const crl = crls[i];
        //#region Check "nextUpdate" for the CRL
        // The "nextUpdate" is older than CHECK_DATE.
        // Thus we should do have another, updated CRL.
        // Thus the CRL assumed to be invalid.
        if (crl.nextUpdate && crl.nextUpdate.value < this.checkDate) {
          continue;
        }
        //#endregion

        for (let j = 0; j < issuerCertificates.length; j++) {
          try {
            const result = await crls[i].verify({ issuerCertificate: issuerCertificates[j] }, crypto);
            if (result) {
              crlsAndCertificates.push({
                crl: crls[i],
                certificate: issuerCertificates[j]
              });

              break;
            }
          }
          catch (ex) {
            // nothing
          }
        }
      }
      //#endregion

      if (crlsAndCertificates.length) {
        return {
          status: 0,
          statusMessage: EMPTY_STRING,
          result: crlsAndCertificates
        };
      }

      return {
        status: 3,
        statusMessage: "No valid CRLs found"
      };
    };
    //#endregion

    //#region Find OCSP for specific certificate
    const findOCSP = async (certificate: Certificate, issuerCertificate: Certificate): Promise<number> => {
      //#region Get hash algorithm from certificate
      const hashAlgorithm = crypto.getAlgorithmByOID<any>(certificate.signatureAlgorithm.algorithmId);
      if (!hashAlgorithm.name) {
        return 1;
      }
      if (!hashAlgorithm.hash) {
        return 1;
      }
      //#endregion

      //#region Search for OCSP response for the certificate
      for (let i = 0; i < this.ocsps.length; i++) {
        const ocsp = this.ocsps[i];
        const result = await ocsp.getCertificateStatus(certificate, issuerCertificate, crypto);
        if (result.isForCertificate) {
          if (result.status === 0)
            return 0;

          return 1;
        }
      }
      //#endregion

      return 2;
    };
    //#endregion

    //#region Check for certificate to be CA
    async function checkForCA(certificate: Certificate, needToCheckCRL = false) {
      //#region Initial variables
      let isCA = false;
      let mustBeCA = false;
      let keyUsagePresent = false;
      let cRLSign = false;
      //#endregion

      if (certificate.extensions) {
        for (let j = 0; j < certificate.extensions.length; j++) {
          const extension = certificate.extensions[j];
          if (extension.critical && !extension.parsedValue) {
            return {
              result: false,
              resultCode: 6,
              resultMessage: `Unable to parse critical certificate extension: ${extension.extnID}`
            };
          }

          if (extension.extnID === id_KeyUsage) // KeyUsage
          {
            keyUsagePresent = true;

            const view = new Uint8Array(extension.parsedValue.valueBlock.valueHex);

            if ((view[0] & 0x04) === 0x04) // Set flag "keyCertSign"
              mustBeCA = true;

            if ((view[0] & 0x02) === 0x02) // Set flag "cRLSign"
              cRLSign = true;
          }

          if (extension.extnID === id_BasicConstraints) // BasicConstraints
          {
            if ("cA" in extension.parsedValue) {
              if (extension.parsedValue.cA === true)
                isCA = true;
            }
          }
        }

        if ((mustBeCA === true) && (isCA === false)) {
          return {
            result: false,
            resultCode: 3,
            resultMessage: "Unable to build certificate chain - using \"keyCertSign\" flag set without BasicConstraints"
          };
        }

        if ((keyUsagePresent === true) && (isCA === true) && (mustBeCA === false)) {
          return {
            result: false,
            resultCode: 4,
            resultMessage: "Unable to build certificate chain - \"keyCertSign\" flag was not set"
          };
        }

        if ((isCA === true) && (keyUsagePresent === true) && ((needToCheckCRL) && (cRLSign === false))) {
          return {
            result: false,
            resultCode: 5,
            resultMessage: "Unable to build certificate chain - intermediate certificate must have \"cRLSign\" key usage flag"
          };
        }
      }

      if (isCA === false) {
        return {
          result: false,
          resultCode: 7,
          resultMessage: "Unable to build certificate chain - more than one possible end-user certificate"
        };
      }

      return {
        result: true,
        resultCode: 0,
        resultMessage: EMPTY_STRING
      };
    }
    //#endregion

    //#region Basic check for certificate path
    const basicCheck = async (path: Certificate[], checkDate: Date): Promise<{ result: boolean; resultCode?: number; resultMessage?: string; }> => {
      //#region Check that all dates are valid
      for (let i = 0; i < path.length; i++) {
        if ((path[i].notBefore.value > checkDate) ||
          (path[i].notAfter.value < checkDate)) {
          return {
            result: false,
            resultCode: 8,
            resultMessage: "The certificate is either not yet valid or expired"
          };
        }
      }
      //#endregion

      //#region Check certificate name chain

      // We should have at least two certificates: end entity and trusted root
      if (path.length < 2) {
        return {
          result: false,
          resultCode: 9,
          resultMessage: "Too short certificate path"
        };
      }

      for (let i = (path.length - 2); i >= 0; i--) {
        //#region Check that we do not have a "self-signed" certificate
        if (path[i].issuer.isEqual(path[i].subject) === false) {
          if (path[i].issuer.isEqual(path[i + 1].subject) === false) {
            return {
              result: false,
              resultCode: 10,
              resultMessage: "Incorrect name chaining"
            };
          }
        }
        //#endregion
      }
      //#endregion

      //#region Check each certificate (except "trusted root") to be non-revoked
      if ((this.crls.length !== 0) || (this.ocsps.length !== 0)) // If CRLs and OCSPs are empty then we consider all certificates to be valid
      {
        for (let i = 0; i < (path.length - 1); i++) {
          //#region Initial variables
          let ocspResult = 2;
          let crlResult: FindCrlResult = {
            status: 0,
            statusMessage: EMPTY_STRING
          };
          //#endregion

          //#region Check OCSPs first
          if (this.ocsps.length !== 0) {
            ocspResult = await findOCSP(path[i], path[i + 1]);

            switch (ocspResult) {
              case 0:
                continue;
              case 1:
                return {
                  result: false,
                  resultCode: 12,
                  resultMessage: "One of certificates was revoked via OCSP response"
                };
              case 2: // continue to check the certificate with CRL
                break;
              default:
            }
          }
          //#endregion

          //#region Check CRLs
          if (this.crls.length !== 0) {
            crlResult = await findCRL(path[i]);

            if (crlResult.status === 0 && crlResult.result) {
              for (let j = 0; j < crlResult.result.length; j++) {
                //#region Check that the CRL issuer certificate have not been revoked
                const isCertificateRevoked = crlResult.result[j].crl.isCertificateRevoked(path[i]);
                if (isCertificateRevoked) {
                  return {
                    result: false,
                    resultCode: 12,
                    resultMessage: "One of certificates had been revoked"
                  };
                }
                //#endregion

                //#region Check that the CRL issuer certificate is a CA certificate
                const isCertificateCA = await checkForCA(crlResult.result[j].certificate, true);
                if (isCertificateCA.result === false) {
                  return {
                    result: false,
                    resultCode: 13,
                    resultMessage: "CRL issuer certificate is not a CA certificate or does not have crlSign flag"
                  };
                }
                //#endregion
              }
            } else {
              if (passedWhenNotRevValues === false) {
                throw new ChainValidationError(ChainValidationCode.noRevocation, `No revocation values found for one of certificates: ${crlResult.statusMessage}`);
              }
            }
          } else {
            if (ocspResult === 2) {
              return {
                result: false,
                resultCode: 11,
                resultMessage: "No revocation values found for one of certificates"
              };
            }
          }
          //#endregion

          //#region Check we do have links to revocation values inside issuer's certificate
          if ((ocspResult === 2) && (crlResult.status === 2) && passedWhenNotRevValues) {
            const issuerCertificate = path[i + 1];
            let extensionFound = false;

            if (issuerCertificate.extensions) {
              for (const extension of issuerCertificate.extensions) {
                switch (extension.extnID) {
                  case id_CRLDistributionPoints:
                  case id_FreshestCRL:
                  case id_AuthorityInfoAccess:
                    extensionFound = true;
                    break;
                  default:
                }
              }
            }

            if (extensionFound) {
              throw new ChainValidationError(ChainValidationCode.noRevocation, `No revocation values found for one of certificates: ${crlResult.statusMessage}`);
            }
          }
          //#endregion
        }
      }
      //#endregion

      //#region Check each certificate (except "end entity") in the path to be a CA certificate
      for (const [i, cert] of path.entries()) {
        if (!i) {
          // Skip entity certificate
          continue;
        }

        const result = await checkForCA(cert);
        if (!result.result) {
          return {
            result: false,
            resultCode: 14,
            resultMessage: "One of intermediate certificates is not a CA certificate"
          };
        }
      }
      //#endregion

      return {
        result: true
      };
    };
    //#endregion

    //#region Do main work
    //#region Initialize "localCerts" by value of "this.certs" + "this.trustedCerts" arrays
    localCerts.push(...this.trustedCerts);
    localCerts.push(...this.certs);
    //#endregion

    //#region Check all certificates for been unique
    for (let i = 0; i < localCerts.length; i++) {
      for (let j = 0; j < localCerts.length; j++) {
        if (i === j)
          continue;

        if (pvtsutils.BufferSourceConverter.isEqual(localCerts[i].tbsView, localCerts[j].tbsView)) {
          localCerts.splice(j, 1);
          i = 0;
          break;
        }
      }
    }
    //#endregion

    const leafCert = localCerts[localCerts.length - 1];

    //#region Initial variables
    let result;
    const certificatePath = [leafCert]; // The "end entity" certificate must be the least in CERTS array
    //#endregion

    //#region Build path for "end entity" certificate
    result = await buildPath(leafCert, crypto);
    if (result.length === 0) {
      throw new ChainValidationError(ChainValidationCode.noPath, "Unable to find certificate path");
    }
    //#endregion

    //#region Exclude certificate paths not ended with "trusted roots"
    for (let i = 0; i < result.length; i++) {
      let found = false;

      for (let j = 0; j < (result[i]).length; j++) {
        const certificate = (result[i])[j];

        for (let k = 0; k < this.trustedCerts.length; k++) {
          if (pvtsutils.BufferSourceConverter.isEqual(certificate.tbsView, this.trustedCerts[k].tbsView)) {
            found = true;
            break;
          }
        }

        if (found)
          break;
      }

      if (!found) {
        result.splice(i, 1);
        i = 0;
      }
    }

    if (result.length === 0) {
      throw new ChainValidationError(ChainValidationCode.noValidPath, "No valid certificate paths found");
    }
    //#endregion

    //#region Find shortest certificate path (for the moment it is the only criteria)
    let shortestLength = result[0].length;
    let shortestIndex = 0;

    for (let i = 0; i < result.length; i++) {
      if (result[i].length < shortestLength) {
        shortestLength = result[i].length;
        shortestIndex = i;
      }
    }
    //#endregion

    //#region Create certificate path for basic check
    for (let i = 0; i < result[shortestIndex].length; i++)
      certificatePath.push((result[shortestIndex])[i]);
    //#endregion

    //#region Perform basic checking for all certificates in the path
    result = await basicCheck(certificatePath, this.checkDate);
    if (result.result === false)
      throw result;
    //#endregion

    return certificatePath;
    //#endregion
  }

  /**
   * Major verification function for certificate chain.
   * @param parameters
   * @param crypto Crypto engine
   * @returns
   */
  async verify(parameters: CertificateChainValidationEngineVerifyParams = {}, crypto = common.getCrypto(true)): Promise<CertificateChainValidationEngineVerifyResult> {
    //#region Auxiliary functions for name constraints checking
    /**
     * Compare two dNSName values
     * @param name DNS from name
     * @param constraint Constraint for DNS from name
     * @returns Boolean result - valid or invalid the "name" against the "constraint"
     */
    function compareDNSName(name: string, constraint: string): boolean {
      //#region Make a "string preparation" for both name and constrain
      const namePrepared = Helpers.stringPrep(name);
      const constraintPrepared = Helpers.stringPrep(constraint);
      //#endregion

      //#region Make a "splitted" versions of "constraint" and "name"
      const nameSplitted = namePrepared.split(".");
      const constraintSplitted = constraintPrepared.split(".");
      //#endregion

      //#region Length calculation and additional check
      const nameLen = nameSplitted.length;
      const constrLen = constraintSplitted.length;

      if ((nameLen === 0) || (constrLen === 0) || (nameLen < constrLen)) {
        return false;
      }
      //#endregion

      //#region Check that no part of "name" has zero length
      for (let i = 0; i < nameLen; i++) {
        if (nameSplitted[i].length === 0) {
          return false;
        }
      }
      //#endregion

      //#region Check that no part of "constraint" has zero length
      for (let i = 0; i < constrLen; i++) {
        if (constraintSplitted[i].length === 0) {
          if (i === 0) {
            if (constrLen === 1) {
              return false;
            }

            continue;
          }

          return false;
        }
      }
      //#endregion

      //#region Check that "name" has a tail as "constraint"

      for (let i = 0; i < constrLen; i++) {
        if (constraintSplitted[constrLen - 1 - i].length === 0) {
          continue;
        }

        if (nameSplitted[nameLen - 1 - i].localeCompare(constraintSplitted[constrLen - 1 - i]) !== 0) {
          return false;
        }
      }
      //#endregion

      return true;
    }

    /**
     * Compare two rfc822Name values
     * @param name E-mail address from name
     * @param constraint Constraint for e-mail address from name
     * @returns Boolean result - valid or invalid the "name" against the "constraint"
     */
    function compareRFC822Name(name: string, constraint: string): boolean {
      //#region Make a "string preparation" for both name and constrain
      const namePrepared = Helpers.stringPrep(name);
      const constraintPrepared = Helpers.stringPrep(constraint);
      //#endregion

      //#region Make a "splitted" versions of "constraint" and "name"
      const nameSplitted = namePrepared.split("@");
      const constraintSplitted = constraintPrepared.split("@");
      //#endregion

      //#region Splitted array length checking
      if ((nameSplitted.length === 0) || (constraintSplitted.length === 0) || (nameSplitted.length < constraintSplitted.length))
        return false;
      //#endregion

      if (constraintSplitted.length === 1) {
        const result = compareDNSName(nameSplitted[1], constraintSplitted[0]);

        if (result) {
          //#region Make a "splitted" versions of domain name from "constraint" and "name"
          const ns = nameSplitted[1].split(".");
          const cs = constraintSplitted[0].split(".");
          //#endregion

          if (cs[0].length === 0)
            return true;

          return ns.length === cs.length;
        }

        return false;
      }

      return (namePrepared.localeCompare(constraintPrepared) === 0);
    }

    /**
     * Compare two uniformResourceIdentifier values
     * @param name uniformResourceIdentifier from name
     * @param constraint Constraint for uniformResourceIdentifier from name
     * @returns Boolean result - valid or invalid the "name" against the "constraint"
     */
    function compareUniformResourceIdentifier(name: string, constraint: string): boolean {
      //#region Make a "string preparation" for both name and constrain
      let namePrepared = Helpers.stringPrep(name);
      const constraintPrepared = Helpers.stringPrep(constraint);
      //#endregion

      //#region Find out a major URI part to compare with
      const ns = namePrepared.split("/");
      const cs = constraintPrepared.split("/");

      if (cs.length > 1) // Malformed constraint
        return false;

      if (ns.length > 1) // Full URI string
      {
        for (let i = 0; i < ns.length; i++) {
          if ((ns[i].length > 0) && (ns[i].charAt(ns[i].length - 1) !== ":")) {
            const nsPort = ns[i].split(":");
            namePrepared = nsPort[0];
            break;
          }
        }
      }
      //#endregion

      const result = compareDNSName(namePrepared, constraintPrepared);

      if (result) {
        //#region Make a "splitted" versions of "constraint" and "name"
        const nameSplitted = namePrepared.split(".");
        const constraintSplitted = constraintPrepared.split(".");
        //#endregion

        if (constraintSplitted[0].length === 0)
          return true;

        return nameSplitted.length === constraintSplitted.length;
      }

      return false;
    }

    /**
     * Compare two iPAddress values
     * @param name iPAddress from name
     * @param constraint Constraint for iPAddress from name
     * @returns Boolean result - valid or invalid the "name" against the "constraint"
     */
    function compareIPAddress(name: asn1js.OctetString, constraint: asn1js.OctetString): boolean {
      //#region Common variables
      const nameView = name.valueBlock.valueHexView;
      const constraintView = constraint.valueBlock.valueHexView;
      //#endregion

      //#region Work with IPv4 addresses
      if ((nameView.length === 4) && (constraintView.length === 8)) {
        for (let i = 0; i < 4; i++) {
          if ((nameView[i] ^ constraintView[i]) & constraintView[i + 4])
            return false;
        }

        return true;
      }
      //#endregion

      //#region Work with IPv6 addresses
      if ((nameView.length === 16) && (constraintView.length === 32)) {
        for (let i = 0; i < 16; i++) {
          if ((nameView[i] ^ constraintView[i]) & constraintView[i + 16])
            return false;
        }

        return true;
      }
      //#endregion

      return false;
    }

    /**
     * Compare two directoryName values
     * @param name directoryName from name
     * @param constraint Constraint for directoryName from name
     * @returns Boolean result - valid or invalid the "name" against the "constraint"
     */
    function compareDirectoryName(name: RelativeDistinguishedNames, constraint: RelativeDistinguishedNames): boolean {
      //#region Initial check
      if ((name.typesAndValues.length === 0) || (constraint.typesAndValues.length === 0))
        return true;

      if (name.typesAndValues.length < constraint.typesAndValues.length)
        return false;
      //#endregion

      //#region Initial variables
      let result = true;
      let nameStart = 0;
      //#endregion

      for (let i = 0; i < constraint.typesAndValues.length; i++) {
        let localResult = false;

        for (let j = nameStart; j < name.typesAndValues.length; j++) {
          localResult = name.typesAndValues[j].isEqual(constraint.typesAndValues[i]);

          if (name.typesAndValues[j].type === constraint.typesAndValues[i].type)
            result = result && localResult;

          if (localResult === true) {
            if ((nameStart === 0) || (nameStart === j)) {
              nameStart = j + 1;
              break;
            }
            else // Structure of "name" must be the same with "constraint"
              return false;
          }
        }

        if (localResult === false)
          return false;
      }

      return (nameStart === 0) ? false : result;
    }
    //#endregion

    try {
      //#region Initial checks
      if (this.certs.length === 0)
        throw new Error("Empty certificate array");
      //#endregion

      //#region Get input variables
      const passedWhenNotRevValues = parameters.passedWhenNotRevValues || false;

      const initialPolicySet = parameters.initialPolicySet || [id_AnyPolicy];

      const initialExplicitPolicy = parameters.initialExplicitPolicy || false;
      const initialPolicyMappingInhibit = parameters.initialPolicyMappingInhibit || false;
      const initialInhibitPolicy = parameters.initialInhibitPolicy || false;

      const initialPermittedSubtreesSet = parameters.initialPermittedSubtreesSet || [];
      const initialExcludedSubtreesSet = parameters.initialExcludedSubtreesSet || [];
      const initialRequiredNameForms = parameters.initialRequiredNameForms || [];

      let explicitPolicyIndicator = initialExplicitPolicy;
      let policyMappingInhibitIndicator = initialPolicyMappingInhibit;
      let inhibitAnyPolicyIndicator = initialInhibitPolicy;

      const pendingConstraints = [
        false, // For "explicitPolicyPending"
        false, // For "policyMappingInhibitPending"
        false, // For "inhibitAnyPolicyPending"
      ];

      let explicitPolicyPending = 0;
      let policyMappingInhibitPending = 0;
      let inhibitAnyPolicyPending = 0;

      let permittedSubtrees = initialPermittedSubtreesSet;
      let excludedSubtrees = initialExcludedSubtreesSet;
      const requiredNameForms = initialRequiredNameForms;

      let pathDepth = 1;
      //#endregion

      //#region Sorting certificates in the chain array
      this.certs = await this.sort(passedWhenNotRevValues, crypto);
      //#endregion

      //#region Work with policies
      //#region Support variables
      const allPolicies: string[] = []; // Array of all policies (string values)
      allPolicies.push(id_AnyPolicy); // Put "anyPolicy" at first place

      const policiesAndCerts = []; // In fact "array of array" where rows are for each specific policy, column for each certificate and value is "true/false"

      const anyPolicyArray = new Array(this.certs.length - 1); // Minus "trusted anchor"
      for (let ii = 0; ii < (this.certs.length - 1); ii++)
        anyPolicyArray[ii] = true;

      policiesAndCerts.push(anyPolicyArray);

      const policyMappings = new Array(this.certs.length - 1); // Array of "PolicyMappings" for each certificate
      const certPolicies = new Array(this.certs.length - 1); // Array of "CertificatePolicies" for each certificate

      let explicitPolicyStart = (explicitPolicyIndicator) ? (this.certs.length - 1) : (-1);
      //#endregion

      //#region Gather all necessary information from certificate chain
      for (let i = (this.certs.length - 2); i >= 0; i--, pathDepth++) {
        const cert = this.certs[i];
        if (cert.extensions) {
          //#region Get information about certificate extensions
          for (let j = 0; j < cert.extensions.length; j++) {
            const extension = cert.extensions[j];
            //#region CertificatePolicies
            if (extension.extnID === id_CertificatePolicies) {
              certPolicies[i] = extension.parsedValue;

              //#region Remove entry from "anyPolicies" for the certificate
              for (let s = 0; s < allPolicies.length; s++) {
                if (allPolicies[s] === id_AnyPolicy) {
                  delete (policiesAndCerts[s])[i];
                  break;
                }
              }
              //#endregion

              for (let k = 0; k < extension.parsedValue.certificatePolicies.length; k++) {
                let policyIndex = (-1);
                const policyId = extension.parsedValue.certificatePolicies[k].policyIdentifier;

                //#region Try to find extension in "allPolicies" array
                for (let s = 0; s < allPolicies.length; s++) {
                  if (policyId === allPolicies[s]) {
                    policyIndex = s;
                    break;
                  }
                }
                //#endregion

                if (policyIndex === (-1)) {
                  allPolicies.push(policyId);

                  const certArray = new Array(this.certs.length - 1);
                  certArray[i] = true;

                  policiesAndCerts.push(certArray);
                }
                else
                  (policiesAndCerts[policyIndex])[i] = true;
              }
            }
            //#endregion

            //#region PolicyMappings
            if (extension.extnID === id_PolicyMappings) {
              if (policyMappingInhibitIndicator) {
                return {
                  result: false,
                  resultCode: 98,
                  resultMessage: "Policy mapping prohibited"
                };
              }

              policyMappings[i] = extension.parsedValue;
            }
            //#endregion

            //#region PolicyConstraints
            if (extension.extnID === id_PolicyConstraints) {
              if (explicitPolicyIndicator === false) {
                //#region requireExplicitPolicy
                if (extension.parsedValue.requireExplicitPolicy === 0) {
                  explicitPolicyIndicator = true;
                  explicitPolicyStart = i;
                }
                else {
                  if (pendingConstraints[0] === false) {
                    pendingConstraints[0] = true;
                    explicitPolicyPending = extension.parsedValue.requireExplicitPolicy;
                  }
                  else
                    explicitPolicyPending = (explicitPolicyPending > extension.parsedValue.requireExplicitPolicy) ? extension.parsedValue.requireExplicitPolicy : explicitPolicyPending;
                }
                //#endregion

                //#region inhibitPolicyMapping
                if (extension.parsedValue.inhibitPolicyMapping === 0)
                  policyMappingInhibitIndicator = true;
                else {
                  if (pendingConstraints[1] === false) {
                    pendingConstraints[1] = true;
                    policyMappingInhibitPending = extension.parsedValue.inhibitPolicyMapping + 1;
                  }
                  else
                    policyMappingInhibitPending = (policyMappingInhibitPending > (extension.parsedValue.inhibitPolicyMapping + 1)) ? (extension.parsedValue.inhibitPolicyMapping + 1) : policyMappingInhibitPending;
                }
                //#endregion
              }
            }
            //#endregion

            //#region InhibitAnyPolicy
            if (extension.extnID === id_InhibitAnyPolicy) {
              if (inhibitAnyPolicyIndicator === false) {
                if (extension.parsedValue.valueBlock.valueDec === 0)
                  inhibitAnyPolicyIndicator = true;
                else {
                  if (pendingConstraints[2] === false) {
                    pendingConstraints[2] = true;
                    inhibitAnyPolicyPending = extension.parsedValue.valueBlock.valueDec;
                  }
                  else
                    inhibitAnyPolicyPending = (inhibitAnyPolicyPending > extension.parsedValue.valueBlock.valueDec) ? extension.parsedValue.valueBlock.valueDec : inhibitAnyPolicyPending;
                }
              }
            }
            //#endregion
          }
          //#endregion

          //#region Check "inhibitAnyPolicyIndicator"
          if (inhibitAnyPolicyIndicator === true) {
            let policyIndex = (-1);

            //#region Find "anyPolicy" index
            for (let searchAnyPolicy = 0; searchAnyPolicy < allPolicies.length; searchAnyPolicy++) {
              if (allPolicies[searchAnyPolicy] === id_AnyPolicy) {
                policyIndex = searchAnyPolicy;
                break;
              }
            }
            //#endregion

            if (policyIndex !== (-1))
              delete (policiesAndCerts[0])[i]; // Unset value to "undefined" for "anyPolicies" value for current certificate
          }
          //#endregion

          //#region Process with "pending constraints"
          if (explicitPolicyIndicator === false) {
            if (pendingConstraints[0] === true) {
              explicitPolicyPending--;
              if (explicitPolicyPending === 0) {
                explicitPolicyIndicator = true;
                explicitPolicyStart = i;

                pendingConstraints[0] = false;
              }
            }
          }

          if (policyMappingInhibitIndicator === false) {
            if (pendingConstraints[1] === true) {
              policyMappingInhibitPending--;
              if (policyMappingInhibitPending === 0) {
                policyMappingInhibitIndicator = true;
                pendingConstraints[1] = false;
              }
            }
          }

          if (inhibitAnyPolicyIndicator === false) {
            if (pendingConstraints[2] === true) {
              inhibitAnyPolicyPending--;
              if (inhibitAnyPolicyPending === 0) {
                inhibitAnyPolicyIndicator = true;
                pendingConstraints[2] = false;
              }
            }
          }
          //#endregion
        }
      }
      //#endregion

      //#region Working with policy mappings
      for (let i = 0; i < (this.certs.length - 1); i++) {
        //#region Check that there is "policy mapping" for level "i + 1"
        if ((i < (this.certs.length - 2)) && (typeof policyMappings[i + 1] !== "undefined")) {
          for (let k = 0; k < policyMappings[i + 1].mappings.length; k++) {
            //#region Check that we do not have "anyPolicy" in current mapping
            if ((policyMappings[i + 1].mappings[k].issuerDomainPolicy === id_AnyPolicy) || (policyMappings[i + 1].mappings[k].subjectDomainPolicy === id_AnyPolicy)) {
              return {
                result: false,
                resultCode: 99,
                resultMessage: "The \"anyPolicy\" should not be a part of policy mapping scheme"
              };
            }
            //#endregion

            //#region Initial variables
            let issuerDomainPolicyIndex = (-1);
            let subjectDomainPolicyIndex = (-1);
            //#endregion

            //#region Search for index of policies indexes
            for (let n = 0; n < allPolicies.length; n++) {
              if (allPolicies[n] === policyMappings[i + 1].mappings[k].issuerDomainPolicy)
                issuerDomainPolicyIndex = n;

              if (allPolicies[n] === policyMappings[i + 1].mappings[k].subjectDomainPolicy)
                subjectDomainPolicyIndex = n;
            }
            //#endregion

            //#region Delete existing "issuerDomainPolicy" because on the level we mapped the policy to another one
            if (typeof (policiesAndCerts[issuerDomainPolicyIndex])[i] !== "undefined")
              delete (policiesAndCerts[issuerDomainPolicyIndex])[i];
            //#endregion

            //#region Check all policies for the certificate
            for (let j = 0; j < certPolicies[i].certificatePolicies.length; j++) {
              if (policyMappings[i + 1].mappings[k].subjectDomainPolicy === certPolicies[i].certificatePolicies[j].policyIdentifier) {
                //#region Set mapped policy for current certificate
                if ((issuerDomainPolicyIndex !== (-1)) && (subjectDomainPolicyIndex !== (-1))) {
                  for (let m = 0; m <= i; m++) {
                    if (typeof (policiesAndCerts[subjectDomainPolicyIndex])[m] !== "undefined") {
                      (policiesAndCerts[issuerDomainPolicyIndex])[m] = true;
                      delete (policiesAndCerts[subjectDomainPolicyIndex])[m];
                    }
                  }
                }
                //#endregion
              }
            }
            //#endregion
          }
        }
        //#endregion
      }
      //#endregion

      //#region Working with "explicitPolicyIndicator" and "anyPolicy"
      for (let i = 0; i < allPolicies.length; i++) {
        if (allPolicies[i] === id_AnyPolicy) {
          for (let j = 0; j < explicitPolicyStart; j++)
            delete (policiesAndCerts[i])[j];
        }
      }
      //#endregion

      //#region Create "set of authorities-constrained policies"
      const authConstrPolicies = [];

      for (let i = 0; i < policiesAndCerts.length; i++) {
        let found = true;

        for (let j = 0; j < (this.certs.length - 1); j++) {
          let anyPolicyFound = false;

          if ((j < explicitPolicyStart) && (allPolicies[i] === id_AnyPolicy) && (allPolicies.length > 1)) {
            found = false;
            break;
          }

          if (typeof (policiesAndCerts[i])[j] === "undefined") {
            if (j >= explicitPolicyStart) {
              //#region Search for "anyPolicy" in the policy set
              for (let k = 0; k < allPolicies.length; k++) {
                if (allPolicies[k] === id_AnyPolicy) {
                  if ((policiesAndCerts[k])[j] === true)
                    anyPolicyFound = true;

                  break;
                }
              }
              //#endregion
            }

            if (!anyPolicyFound) {
              found = false;
              break;
            }
          }
        }

        if (found === true)
          authConstrPolicies.push(allPolicies[i]);
      }
      //#endregion

      //#region Create "set of user-constrained policies"
      let userConstrPolicies: string[] = [];

      if ((initialPolicySet.length === 1) && (initialPolicySet[0] === id_AnyPolicy) && (explicitPolicyIndicator === false))
        userConstrPolicies = initialPolicySet;
      else {
        if ((authConstrPolicies.length === 1) && (authConstrPolicies[0] === id_AnyPolicy))
          userConstrPolicies = initialPolicySet;
        else {
          for (let i = 0; i < authConstrPolicies.length; i++) {
            for (let j = 0; j < initialPolicySet.length; j++) {
              if ((initialPolicySet[j] === authConstrPolicies[i]) || (initialPolicySet[j] === id_AnyPolicy)) {
                userConstrPolicies.push(authConstrPolicies[i]);
                break;
              }
            }
          }
        }
      }

      //#endregion

      //#region Combine output object
      const policyResult: CertificateChainValidationEngineVerifyResult = {
        result: (userConstrPolicies.length > 0),
        resultCode: 0,
        resultMessage: (userConstrPolicies.length > 0) ? EMPTY_STRING : "Zero \"userConstrPolicies\" array, no intersections with \"authConstrPolicies\"",
        authConstrPolicies,
        userConstrPolicies,
        explicitPolicyIndicator,
        policyMappings,
        certificatePath: this.certs
      };

      if (userConstrPolicies.length === 0)
        return policyResult;
      //#endregion
      //#endregion

      //#region Work with name constraints
      //#region Check a result from "policy checking" part
      if (policyResult.result === false)
        return policyResult;
      //#endregion

      //#region Check all certificates, excluding "trust anchor"
      pathDepth = 1;

      for (let i = (this.certs.length - 2); i >= 0; i--, pathDepth++) {
        const cert = this.certs[i];
        //#region Support variables
        let subjectAltNames: GeneralName[] = [];

        let certPermittedSubtrees: GeneralSubtree[] = [];
        let certExcludedSubtrees: GeneralSubtree[] = [];
        //#endregion

        if (cert.extensions) {
          for (let j = 0; j < cert.extensions.length; j++) {
            const extension = cert.extensions[j];
            //#region NameConstraints
            if (extension.extnID === id_NameConstraints) {
              if ("permittedSubtrees" in extension.parsedValue)
                certPermittedSubtrees = certPermittedSubtrees.concat(extension.parsedValue.permittedSubtrees);

              if ("excludedSubtrees" in extension.parsedValue)
                certExcludedSubtrees = certExcludedSubtrees.concat(extension.parsedValue.excludedSubtrees);
            }
            //#endregion

            //#region SubjectAltName
            if (extension.extnID === id_SubjectAltName)
              subjectAltNames = subjectAltNames.concat(extension.parsedValue.altNames);
            //#endregion
          }
        }

        //#region Checking for "required name forms"
        let formFound = (requiredNameForms.length <= 0);

        for (let j = 0; j < requiredNameForms.length; j++) {
          switch (requiredNameForms[j].base.type) {
            case 4: // directoryName
              {
                if (requiredNameForms[j].base.value.typesAndValues.length !== cert.subject.typesAndValues.length)
                  continue;

                formFound = true;

                for (let k = 0; k < cert.subject.typesAndValues.length; k++) {
                  if (cert.subject.typesAndValues[k].type !== requiredNameForms[j].base.value.typesAndValues[k].type) {
                    formFound = false;
                    break;
                  }
                }

                if (formFound === true)
                  break;
              }
              break;
            default: // ??? Probably here we should reject the certificate ???
          }
        }

        if (formFound === false) {
          policyResult.result = false;
          policyResult.resultCode = 21;
          policyResult.resultMessage = "No necessary name form found";

          throw policyResult;
        }
        //#endregion

        //#region Checking for "permited sub-trees"
        //#region Make groups for all types of constraints
        const constrGroups: GeneralSubtree[][] = [ // Array of array for groupped constraints
          [], // rfc822Name
          [], // dNSName
          [], // directoryName
          [], // uniformResourceIdentifier
          [], // iPAddress
        ];

        for (let j = 0; j < permittedSubtrees.length; j++) {
          switch (permittedSubtrees[j].base.type) {
            //#region rfc822Name
            case 1:
              constrGroups[0].push(permittedSubtrees[j]);
              break;
            //#endregion
            //#region dNSName
            case 2:
              constrGroups[1].push(permittedSubtrees[j]);
              break;
            //#endregion
            //#region directoryName
            case 4:
              constrGroups[2].push(permittedSubtrees[j]);
              break;
            //#endregion
            //#region uniformResourceIdentifier
            case 6:
              constrGroups[3].push(permittedSubtrees[j]);
              break;
            //#endregion
            //#region iPAddress
            case 7:
              constrGroups[4].push(permittedSubtrees[j]);
              break;
            //#endregion
            //#region default
            default:
            //#endregion
          }
        }
        //#endregion

        //#region Check name constraints groupped by type, one-by-one
        for (let p = 0; p < 5; p++) {
          let groupPermitted = false;
          let valueExists = false;
          const group = constrGroups[p];

          for (let j = 0; j < group.length; j++) {
            switch (p) {
              //#region rfc822Name
              case 0:
                if (subjectAltNames.length > 0) {
                  for (let k = 0; k < subjectAltNames.length; k++) {
                    if (subjectAltNames[k].type === 1) // rfc822Name
                    {
                      valueExists = true;
                      groupPermitted = groupPermitted || compareRFC822Name(subjectAltNames[k].value, group[j].base.value);
                    }
                  }
                }
                else // Try to find out "emailAddress" inside "subject"
                {
                  for (let k = 0; k < cert.subject.typesAndValues.length; k++) {
                    if ((cert.subject.typesAndValues[k].type === "1.2.840.113549.1.9.1") ||    // PKCS#9 e-mail address
                      (cert.subject.typesAndValues[k].type === "0.9.2342.19200300.100.1.3")) // RFC1274 "rfc822Mailbox" e-mail address
                    {
                      valueExists = true;
                      groupPermitted = groupPermitted || compareRFC822Name(cert.subject.typesAndValues[k].value.valueBlock.value, group[j].base.value);
                    }
                  }
                }
                break;
              //#endregion
              //#region dNSName
              case 1:
                if (subjectAltNames.length > 0) {
                  for (let k = 0; k < subjectAltNames.length; k++) {
                    if (subjectAltNames[k].type === 2) // dNSName
                    {
                      valueExists = true;
                      groupPermitted = groupPermitted || compareDNSName(subjectAltNames[k].value, group[j].base.value);
                    }
                  }
                }
                break;
              //#endregion
              //#region directoryName
              case 2:
                valueExists = true;
                groupPermitted = compareDirectoryName(cert.subject, group[j].base.value);
                break;
              //#endregion
              //#region uniformResourceIdentifier
              case 3:
                if (subjectAltNames.length > 0) {
                  for (let k = 0; k < subjectAltNames.length; k++) {
                    if (subjectAltNames[k].type === 6) // uniformResourceIdentifier
                    {
                      valueExists = true;
                      groupPermitted = groupPermitted || compareUniformResourceIdentifier(subjectAltNames[k].value, group[j].base.value);
                    }
                  }
                }
                break;
              //#endregion
              //#region iPAddress
              case 4:
                if (subjectAltNames.length > 0) {
                  for (let k = 0; k < subjectAltNames.length; k++) {
                    if (subjectAltNames[k].type === 7) // iPAddress
                    {
                      valueExists = true;
                      groupPermitted = groupPermitted || compareIPAddress(subjectAltNames[k].value, group[j].base.value);
                    }
                  }
                }
                break;
              //#endregion
              //#region default
              default:
              //#endregion
            }

            if (groupPermitted)
              break;
          }

          if ((groupPermitted === false) && (group.length > 0) && valueExists) {
            policyResult.result = false;
            policyResult.resultCode = 41;
            policyResult.resultMessage = "Failed to meet \"permitted sub-trees\" name constraint";

            throw policyResult;
          }
        }
        //#endregion
        //#endregion

        //#region Checking for "excluded sub-trees"
        let excluded = false;

        for (let j = 0; j < excludedSubtrees.length; j++) {
          switch (excludedSubtrees[j].base.type) {
            //#region rfc822Name
            case 1:
              if (subjectAltNames.length >= 0) {
                for (let k = 0; k < subjectAltNames.length; k++) {
                  if (subjectAltNames[k].type === 1) // rfc822Name
                    excluded = excluded || compareRFC822Name(subjectAltNames[k].value, excludedSubtrees[j].base.value);
                }
              }
              else // Try to find out "emailAddress" inside "subject"
              {
                for (let k = 0; k < cert.subject.typesAndValues.length; k++) {
                  if ((cert.subject.typesAndValues[k].type === "1.2.840.113549.1.9.1") ||    // PKCS#9 e-mail address
                    (cert.subject.typesAndValues[k].type === "0.9.2342.19200300.100.1.3")) // RFC1274 "rfc822Mailbox" e-mail address
                    excluded = excluded || compareRFC822Name(cert.subject.typesAndValues[k].value.valueBlock.value, excludedSubtrees[j].base.value);
                }
              }
              break;
            //#endregion
            //#region dNSName
            case 2:
              if (subjectAltNames.length > 0) {
                for (let k = 0; k < subjectAltNames.length; k++) {
                  if (subjectAltNames[k].type === 2) // dNSName
                    excluded = excluded || compareDNSName(subjectAltNames[k].value, excludedSubtrees[j].base.value);
                }
              }
              break;
            //#endregion
            //#region directoryName
            case 4:
              excluded = excluded || compareDirectoryName(cert.subject, excludedSubtrees[j].base.value);
              break;
            //#endregion
            //#region uniformResourceIdentifier
            case 6:
              if (subjectAltNames.length > 0) {
                for (let k = 0; k < subjectAltNames.length; k++) {
                  if (subjectAltNames[k].type === 6) // uniformResourceIdentifier
                    excluded = excluded || compareUniformResourceIdentifier(subjectAltNames[k].value, excludedSubtrees[j].base.value);
                }
              }
              break;
            //#endregion
            //#region iPAddress
            case 7:
              if (subjectAltNames.length > 0) {
                for (let k = 0; k < subjectAltNames.length; k++) {
                  if (subjectAltNames[k].type === 7) // iPAddress
                    excluded = excluded || compareIPAddress(subjectAltNames[k].value, excludedSubtrees[j].base.value);
                }
              }
              break;
            //#endregion
            //#region default
            default: // No action, but probably here we need to create a warning for "malformed constraint"
            //#endregion
          }

          if (excluded)
            break;
        }

        if (excluded === true) {
          policyResult.result = false;
          policyResult.resultCode = 42;
          policyResult.resultMessage = "Failed to meet \"excluded sub-trees\" name constraint";

          throw policyResult;
        }
        //#endregion

        //#region Append "cert_..._subtrees" to "..._subtrees"
        permittedSubtrees = permittedSubtrees.concat(certPermittedSubtrees);
        excludedSubtrees = excludedSubtrees.concat(certExcludedSubtrees);
        //#endregion
      }
      //#endregion

      return policyResult;
      //#endregion
    } catch (error) {
      if (error instanceof Error) {
        if (error instanceof ChainValidationError) {
          return {
            result: false,
            resultCode: error.code,
            resultMessage: error.message,
            error: error,
          };
        }

        return {
          result: false,
          resultCode: ChainValidationCode.unknown,
          resultMessage: error.message,
          error: error,
        };
      }

      if (error && typeof error === "object" && "resultMessage" in error) {
        return error as CertificateChainValidationEngineVerifyResult;
      }

      return {
        result: false,
        resultCode: -1,
        resultMessage: `${error}`,
      };
    }
  }

}