All files / src CertificateChainValidationEngine.js

82.5% Statements 547/663
71.97% Branches 362/503
85% Functions 17/20
82.45% Lines 545/661

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866                                        216x         216x         216x         216x         216x         216x         216x                                                                                     682x   682x   682x 682x       682x   232x   232x 232x 212x                 470x   470x   470x   470x 470x                   470x                   1807x   1807x   1807x   1807x   3144x   1807x   1807x 468x   1807x       1807x 1807x                                                             470x 470x       470x 1337x       470x   468x   468x 468x 2x                 470x                 1512x     216x   216x   216x   216x   216x   216x   216x                 216x 216x           682x         465x   465x   886x   2336x 886x   1450x   188x 188x       886x 188x     465x         682x 682x 4x   678x   678x   212x 212x     466x   465x   465x 465x   465x 277x   188x       677x               268x 268x 268x       1100x 268x                   783x 268x   7x               261x           279x 2x     277x   285x   285x 285x   274x         274x                   261x   256x             5x                                                                               638x 638x 638x 638x     638x   638x   3142x                   3142x   638x   638x   638x 634x   638x 636x     3142x   635x   635x 634x         638x   2x             636x   2x             634x   2x               632x   2x             630x                       212x   693x     5x                       207x                 207x     479x   435x   2x                       205x   181x               268x                                           268x   268x 268x   12x             256x     266x 266x   20x                 246x 246x   8x                                                   165x   392x 392x                     165x               216x 216x       216x   699x   2579x 699x   1880x   24x 24x 24x               216x       216x 212x                     212x   212x   212x   489x   489x   489x   212x 212x       489x 212x     212x             212x                     212x 212x   212x   212x                 212x 489x       212x 200x 35x     165x                     216x     216x         216x 216x   216x 216x 216x   216x 216x 216x   216x 21x   216x 8x   216x 1x   216x 1x   216x     216x     216x     216x 216x 216x   216x 216x 216x 216x   216x 216x 216x   216x 216x 216x   216x       216x         165x 165x   165x   165x 165x 392x   165x   165x 165x   165x       165x   380x     380x     1867x   346x     346x   346x   346x 346x         346x   398x     398x   715x   199x 199x         398x   199x   199x 199x   199x     199x           1867x   37x   8x             29x         1859x   57x     56x   48x 48x       8x   6x 6x     2x         56x 1x     55x   53x 53x     2x               1859x   9x   7x 1x     6x   5x 5x     1x                 372x   18x     18x   18x   18x 18x         18x 18x         372x   225x   21x 21x   5x 5x   5x         372x   370x   148x 148x   7x 7x         372x   354x   6x 6x   5x 5x                   157x     357x   28x     44x   2x                 42x 42x       42x   210x 42x   210x 26x         42x 7x       42x   64x     23x   23x   34x   29x 29x                             155x   340x   155x 92x           155x   155x   340x   340x   510x   510x   49x 49x     461x   158x     92x   92x   92x 6x   92x           158x   152x 152x         340x 139x         155x   155x 104x     51x       51x   36x   36x   22x 22x                 155x                     155x 30x                           18x 18x       18x 18x       18x 18x   18x 2x       16x   40x           16x   34x   2x   2x     2x                   16x   34x 2x   32x 5x       11x                     9x 9x       9x 9x       9x       9x   9x   9x     6x 6x     6x 1x   5x     3x                           4x 4x       4x 4x   4x     4x   4x   12x   4x 4x 4x           4x   4x     3x 3x     3x 1x   2x     1x                                                                                                         31x 1x   30x         30x 30x     30x   90x   90x   95x   95x 84x   95x   79x   79x 79x             90x 11x     19x           125x         125x   125x     256x   256x 256x     256x   256x     1209x   42x 26x   42x 18x         1209x 20x           256x   256x                                                       256x                       256x 256x 256x 256x 256x 256x   256x   31x       7x 7x       3x 3x       19x 19x       2x 2x                             256x   1253x 1253x 1253x   1253x   27x       7x   6x   6x   6x 6x           1x   5x     1x 1x       7x       3x   3x   3x   3x 3x       3x       15x 15x 15x       2x   2x   2x   2x 2x       2x                                           27x 18x     1253x   9x 9x 9x   9x             247x   247x   22x       2x   2x   2x 2x                       2x       2x   2x   2x 2x     2x       16x 16x       2x   2x   2x 2x     2x                                     22x 10x     247x   10x 10x 10x   10x         237x 237x         106x         70x   70x 66x   4x   4x                                    
import { getParametersValue, isEqualBuffer } from "pvutils";
import { getAlgorithmByOID, stringPrep } from "./common.js";
import CertificateRevocationList from "./CertificateRevocationList.js";
import Certificate from "./Certificate.js";
//**************************************************************************************
export default class CertificateChainValidationEngine
{
	//**********************************************************************************
	/**
	 * Constructor for CertificateChainValidationEngine class
	 * @param {Object} [parameters={}]
	 * @property {Object} [schema] asn1js parsed value
	 */
	constructor(parameters = {})
	{
		//region Internal properties of the object
		/**
		 * @type {Array.<Certificate>}
		 * @description Array of pre-defined trusted (by user) certificates
		 */
		this.trustedCerts = getParametersValue(parameters, "trustedCerts", this.defaultValues("trustedCerts"));
		/**
		 * @type {Array.<Certificate>}
		 * @description Array with certificate chain. Could be only one end-user certificate in there!
		 */
		this.certs = getParametersValue(parameters, "certs", this.defaultValues("certs"));
		/**
		 * @type {Array.<CertificateRevocationList>}
		 * @description Array of all CRLs for all certificates from certificate chain
		 */
		this.crls = getParametersValue(parameters, "crls", this.defaultValues("crls"));
		/**
		 * @type {Array}
		 * @description Array of all OCSP responses
		 */
		this.ocsps = getParametersValue(parameters, "ocsps", this.defaultValues("ocsps"));
		/**
		 * @type {Date}
		 * @description The date at which the check would be
		 */
		this.checkDate = getParametersValue(parameters, "checkDate", this.defaultValues("checkDate"));
		/**
		 * @type {Function}
		 * @description The date at which the check would be
		 */
		this.findOrigin = getParametersValue(parameters, "findOrigin", this.defaultValues("findOrigin"));
		/**
		 * @type {Function}
		 * @description The date at which the check would be
		 */
		this.findIssuer = getParametersValue(parameters, "findIssuer", this.defaultValues("findIssuer"));
		//endregion
	}
	//**********************************************************************************
	defaultFindOrigin(certificate, validationEngine)
	{
		//region Firstly encode TBS for certificate
		if(certificate.tbs.byteLength === 0)
			certificate.tbs = certificate.encodeTBS();
		//endregion
		
		//region Search in Intermediate Certificates
		for(const localCert of validationEngine.certs)
		{
			//region Firstly encode TBS for certificate
			if(localCert.tbs.byteLength === 0)
				localCert.tbs = localCert.encodeTBS();
			//endregion
			
			if(isEqualBuffer(certificate.tbs, localCert.tbs))
				return "Intermediate Certificates";
		}
		//endregion
		
		//region Search in Trusted Certificates
		for(const trustedCert of validationEngine.trustedCerts)
		{
			//region Firstly encode TBS for certificate
			if(trustedCert.tbs.byteLength === 0)
				trustedCert.tbs = trustedCert.encodeTBS();
			//endregion
			
			if(isEqualBuffer(certificate.tbs, trustedCert.tbs))
				return "Trusted Certificates";
		}
		//endregion
		
		return "Unknown";
	}
	//**********************************************************************************
	async defaultFindIssuer(certificate, validationEngine)
	{
		//region Initial variables
		let result = [];
		
		let keyIdentifier = null;
		
		let authorityCertIssuer = null;
		let authorityCertSerialNumber = null;
		//endregion
		
		//region Speed-up searching in case of self-signed certificates
		if(certificate.subject.isEqual(certificate.issuer))
		{
			try
			{
				const verificationResult = await certificate.verify();
				if(verificationResult === true)
					return [certificate];
			}
			catch(ex)
			{
			}
		}
		//endregion
		
		//region Find values to speed-up search
		Eif("extensions" in certificate)
		{
			for(const extension of certificate.extensions)
			{
				Eif(extension.extnID === "2.5.29.35") // AuthorityKeyIdentifier
				{
					Eif("keyIdentifier" in extension.parsedValue)
						keyIdentifier = extension.parsedValue.keyIdentifier;
					else
					{
						if("authorityCertIssuer" in extension.parsedValue)
							authorityCertIssuer = extension.parsedValue.authorityCertIssuer;
						
						if("authorityCertSerialNumber" in extension.parsedValue)
							authorityCertSerialNumber = extension.parsedValue.authorityCertSerialNumber;
					}
					
					break;
				}
			}
		}
		//endregion
		
		//region Aux function
		function checkCertificate(possibleIssuer)
		{
			//region Firstly search for appropriate extensions
			Eif(keyIdentifier !== null)
			{
				Eif("extensions" in possibleIssuer)
				{
					let extensionFound = false;
					
					for(const extension of possibleIssuer.extensions)
					{
						if(extension.extnID === "2.5.29.14") // SubjectKeyIdentifier
						{
							extensionFound = true;
							
							if(isEqualBuffer(extension.parsedValue.valueBlock.valueHex, keyIdentifier.valueBlock.valueHex))
								result.push(possibleIssuer);
							
							break;
						}
					}
					
					Eif(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
		}
		//endregion
		
		//region Search in Trusted Certificates
		for(const trustedCert of validationEngine.trustedCerts)
			checkCertificate(trustedCert);
		//endregion
		
		//region Search in Intermediate Certificates
		for(const intermediateCert of validationEngine.certs)
			checkCertificate(intermediateCert);
		//endregion
		
		//region Now perform certificate verification checking
		for(let i = 0; i < result.length; i++)
		{
			try
			{
				const verificationResult = await certificate.verify(result[i]);
				if(verificationResult === false)
					result.splice(i, 1);
			}
			catch(ex)
			{
				result.splice(i, 1); // Something wrong, remove the certificate
			}
		}
		//endregion
		
		return result;
	}
	//**********************************************************************************
	/**
	 * Return default values for all class members
	 * @param {string} memberName String name for a class member
	 */
	defaultValues(memberName)
	{
		switch(memberName)
		{
			case "trustedCerts":
				return [];
			case "certs":
				return [];
			case "crls":
				return [];
			case "ocsps":
				return [];
			case "checkDate":
				return new Date();
			case "findOrigin":
				return this.defaultFindOrigin;
			case "findIssuer":
				return this.defaultFindIssuer;
			default:
				throw new Error(`Invalid member name for CertificateChainValidationEngine class: ${memberName}`);
		}
	}
	//**********************************************************************************
	async sort()
	{
		//region Initial variables
		const localCerts = [];
		const _this = this;
		//endregion
		
		//region Building certificate path
		async function buildPath(certificate)
		{
			const result = [];
			
			//region Aux function checking array for unique elements
			function checkUnique(array)
			{
				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;
			}
			
			//endregion
			
			const findIssuerResult = await _this.findIssuer(certificate, _this);
			if(findIssuerResult.length === 0)
				throw new Error("No valid certificate paths found");
			
			for(let i = 0; i < findIssuerResult.length; i++)
			{
				if(isEqualBuffer(findIssuerResult[i].tbs, certificate.tbs))
				{
					result.push([findIssuerResult[i]]);
					continue;
				}
				
				const buildPathResult = await buildPath(findIssuerResult[i]);
				
				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
		async function findCRL(certificate)
		{
			//region Initial variables
			const issuerCertificates = [];
			const crls = [];
			const crlsAndCertificates = [];
			//endregion
			
			//region Find all possible CRL issuers
			issuerCertificates.push(...localCerts.filter(element => certificate.issuer.isEqual(element.subject)));
			Iif(issuerCertificates.length === 0)
			{
				return {
					status: 1,
					statusMessage: "No certificate's issuers"
				};
			}
			//endregion
			
			//region Find all CRLs for crtificate's issuer
			crls.push(..._this.crls.filter(element => element.issuer.isEqual(certificate.issuer)));
			if(crls.length === 0)
			{
				return {
					status: 1,
					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++)
			{
				//region Check "nextUpdate" for the CRL
				// The "nextUpdate" is older than "checkDate".
				// Thus we should do have another, updated CRL.
				// Thus the CRL assumed to be invalid.
				if(crls[i].nextUpdate.value < _this.checkDate)
					continue;
				//endregion
				
				for(let j = 0; j < issuerCertificates.length; j++)
				{
					try
					{
						const result = await crls[i].verify({ issuerCertificate: issuerCertificates[j] });
						if(result)
						{
							crlsAndCertificates.push({
								crl: crls[i],
								certificate: issuerCertificates[j]
							});
							
							break;
						}
					}
					catch(ex)
					{
					}
				}
			}
			//endregion
			
			if(crlsAndCertificates.length)
			{
				return {
					status: 0,
					statusMessage: "",
					result: crlsAndCertificates
				};
			}
			
			return {
				status: 1,
				statusMessage: "No valid CRLs found"
			};
		}
		//endregion
		
		//region Find OCSP for specific certificate
		async function findOCSP(certificate, issuerCertificate)
		{
			//region Get hash algorithm from certificate
			const hashAlgorithm = getAlgorithmByOID(certificate.signatureAlgorithm.algorithmId);
			if(("name" in hashAlgorithm) === false)
				return 1;
			if(("hash" in hashAlgorithm) === false)
				return 1;
			//endregion
			
			//region Search for OCSP response for the certificate
			for(let i = 0; i < _this.ocsps.length; i++)
			{
				const result = await _this.ocsps[i].getCertificateStatus(certificate, issuerCertificate);
				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, needToCheckCRL = false)
		{
			//region Initial variables
			let isCA = false;
			let mustBeCA = false;
			let keyUsagePresent = false;
			let cRLSign = false;
			//endregion
			
			Eif("extensions" in certificate)
			{
				for(let j = 0; j < certificate.extensions.length; j++)
				{
					Iif((certificate.extensions[j].critical === true) &&
						(("parsedValue" in certificate.extensions[j]) === false))
					{
						return {
							result: false,
							resultCode: 6,
							resultMessage: `Unable to parse critical certificate extension: ${certificate.extensions[j].extnID}`
						};
					}
					
					if(certificate.extensions[j].extnID === "2.5.29.15") // KeyUsage
					{
						keyUsagePresent = true;
						
						const view = new Uint8Array(certificate.extensions[j].parsedValue.valueBlock.valueHex);
						
						if((view[0] & 0x04) === 0x04) // Set flag "keyCertSign"
							mustBeCA = true;
						
						if((view[0] & 0x02) === 0x02) // Set flag "cRLSign"
							cRLSign = true;
					}
					
					if(certificate.extensions[j].extnID === "2.5.29.19") // BasicConstraints
					{
						Eif("cA" in certificate.extensions[j].parsedValue)
						{
							if(certificate.extensions[j].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 BasicConstaints"
					};
				}
				
				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: ""
			};
		}
		//endregion
		
		//region Basic check for certificate path
		async function basicCheck(path, checkDate)
		{
			//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: "Certificate validity period is out of checking date"
					};
				}
			}
			//endregion
			
			//region Check certificate name chain
			
			// We should have at least two certificates: end entity and trusted root
			Iif(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 - 2); i++)
				{
					//region Initial variables
					let ocspResult;
					let crlResult;
					//endregion
					
					//region Check OCSPs first
					Iif(_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
					Eif(_this.crls.length !== 0)
					{
						crlResult = await findCRL(path[i]);
						if(crlResult.status)
						{
							throw {
								result: false,
								resultCode: 11,
								resultMessage: `No revocation values found for one of certificates: ${crlResult.statusMessage}`
							};
						}
						
						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(ocspResult === 2)
						{
							return {
								result: false,
								resultCode: 11,
								resultMessage: "No revocation values found for one of certificates"
							};
						}
					}
					//endregion
				}
			}
			//endregion
			
			//region Check each certificate (except "end entity") in the path to be a CA certificate
			for(let i = 1; i < path.length; i++)
			{
				const result = await checkForCA(path[i]);
				Iif(result.result === false)
				{
					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(isEqualBuffer(localCerts[i].tbs, localCerts[j].tbs))
				{
					localCerts.splice(j, 1);
					i = 0;
					break;
				}
			}
		}
		//endregion
		
		//region Initial variables
		let result;
		const certificatePath = [localCerts[localCerts.length - 1]]; // The "end entity" certificate must be the least in "certs" array
		//endregion
		
		//region Build path for "end entity" certificate
		result = await buildPath(localCerts[localCerts.length - 1]);
		Iif(result.length === 0)
		{
			return {
				result: false,
				resultCode: 60,
				resultMessage: "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(isEqualBuffer(certificate.tbs, _this.trustedCerts[k].tbs))
					{
						found = true;
						break;
					}
				}
				
				if(found)
					break;
			}
			
			Iif(!found)
			{
				result.splice(i, 1);
				i = 0;
			}
		}
		
		Iif(result.length === 0)
		{
			throw {
				result: false,
				resultCode: 97,
				resultMessage: "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++)
		{
			Iif(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 {{initialPolicySet, initialExplicitPolicy, initialPolicyMappingInhibit, initialInhibitPolicy, initialPermittedSubtreesSet, initialExcludedSubtreesSet, initialRequiredNameForms}} [parameters]
	 * @returns {Promise}
	 */
	async verify(parameters = {})
	{
		try
		{
			//region Initial checks
			Iif(this.certs.length === 0)
				throw "Empty certificate array";
			//endregion
			
			//region Get input variables
			let initialPolicySet = [];
			initialPolicySet.push("2.5.29.32.0"); // "anyPolicy"
			
			let initialExplicitPolicy = false;
			let initialPolicyMappingInhibit = false;
			let initialInhibitPolicy = false;
			
			let initialPermittedSubtreesSet = []; // Array of "simpl.x509.GeneralSubtree"
			let initialExcludedSubtreesSet = [];  // Array of "simpl.x509.GeneralSubtree"
			let initialRequiredNameForms = [];    // Array of "simpl.x509.GeneralSubtree"
			
			if("initialPolicySet" in parameters)
				initialPolicySet = parameters.initialPolicySet;
			
			if("initialExplicitPolicy" in parameters)
				initialExplicitPolicy = parameters.initialExplicitPolicy;
			
			if("initialPolicyMappingInhibit" in parameters)
				initialPolicyMappingInhibit = parameters.initialPolicyMappingInhibit;
			
			if("initialInhibitPolicy" in parameters)
				initialInhibitPolicy = parameters.initialInhibitPolicy;
			
			Iif("initialPermittedSubtreesSet" in parameters)
				initialPermittedSubtreesSet = parameters.initialPermittedSubtreesSet;
			
			Iif("initialExcludedSubtreesSet" in parameters)
				initialExcludedSubtreesSet = parameters.initialExcludedSubtreesSet;
			
			Iif("initialRequiredNameForms" in parameters)
				initialRequiredNameForms = parameters.initialRequiredNameForms;
			
			let explicitPolicyIndicator = initialExplicitPolicy;
			let policyMappingInhibitIndicator = initialPolicyMappingInhibit;
			let inhibitAnyPolicyIndicator = initialInhibitPolicy;
			
			const pendingConstraints = new Array(3);
			pendingConstraints[0] = false; // For "explicitPolicyPending"
			pendingConstraints[1] = false; // For "policyMappingInhibitPending"
			pendingConstraints[2] = 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();
			//endregion
			
			//region Work with policies
			//region Support variables
			const allPolicies = []; // Array of all policies (string values)
			allPolicies.push("2.5.29.32.0"); // 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 neccessary information from certificate chain
			for(let i = (this.certs.length - 2); i >= 0; i--, pathDepth++)
			{
				Eif("extensions" in this.certs[i])
				{
					//region Get information about certificate extensions
					for(let j = 0; j < this.certs[i].extensions.length; j++)
					{
						//region CertificatePolicies
						if(this.certs[i].extensions[j].extnID === "2.5.29.32")
						{
							certPolicies[i] = this.certs[i].extensions[j].parsedValue;
							
							//region Remove entry from "anyPolicies" for the certificate
							for(let s = 0; s < allPolicies.length; s++)
							{
								Eif(allPolicies[s] === "2.5.29.32.0")
								{
									delete (policiesAndCerts[s])[i];
									break;
								}
							}
							//endregion
							
							for(let k = 0; k < this.certs[i].extensions[j].parsedValue.certificatePolicies.length; k++)
							{
								let policyIndex = (-1);
								
								//region Try to find extension in "allPolicies" array
								for(let s = 0; s < allPolicies.length; s++)
								{
									if(this.certs[i].extensions[j].parsedValue.certificatePolicies[k].policyIdentifier === allPolicies[s])
									{
										policyIndex = s;
										break;
									}
								}
								//endregion
								
								if(policyIndex === (-1))
								{
									allPolicies.push(this.certs[i].extensions[j].parsedValue.certificatePolicies[k].policyIdentifier);
									
									const certArray = new Array(this.certs.length - 1);
									certArray[i] = true;
									
									policiesAndCerts.push(certArray);
								}
								else
									(policiesAndCerts[policyIndex])[i] = true;
							}
						}
						//endregion
						
						//region PolicyMappings
						if(this.certs[i].extensions[j].extnID === "2.5.29.33")
						{
							if(policyMappingInhibitIndicator)
							{
								return {
									result: false,
									resultCode: 98,
									resultMessage: "Policy mapping prohibited"
								};
							}
							
							policyMappings[i] = this.certs[i].extensions[j].parsedValue;
						}
						//endregion
						
						//region PolicyConstraints
						if(this.certs[i].extensions[j].extnID === "2.5.29.36")
						{
							if(explicitPolicyIndicator === false)
							{
								//region requireExplicitPolicy
								if(this.certs[i].extensions[j].parsedValue.requireExplicitPolicy === 0)
								{
									explicitPolicyIndicator = true;
									explicitPolicyStart = i;
								}
								else
								{
									if(pendingConstraints[0] === false)
									{
										pendingConstraints[0] = true;
										explicitPolicyPending = this.certs[i].extensions[j].parsedValue.requireExplicitPolicy;
									}
									else
										explicitPolicyPending = (explicitPolicyPending > this.certs[i].extensions[j].parsedValue.requireExplicitPolicy) ? this.certs[i].extensions[j].parsedValue.requireExplicitPolicy : explicitPolicyPending;
								}
								//endregion
								
								//region inhibitPolicyMapping
								if(this.certs[i].extensions[j].parsedValue.inhibitPolicyMapping === 0)
									policyMappingInhibitIndicator = true;
								else
								{
									if(pendingConstraints[1] === false)
									{
										pendingConstraints[1] = true;
										policyMappingInhibitPending = this.certs[i].extensions[j].parsedValue.inhibitPolicyMapping + 1;
									}
									else
										policyMappingInhibitPending = (policyMappingInhibitPending > (this.certs[i].extensions[j].parsedValue.inhibitPolicyMapping + 1)) ? (this.certs[i].extensions[j].parsedValue.inhibitPolicyMapping + 1) : policyMappingInhibitPending;
								}
								//endregion
							}
						}
						//endregion
						
						//region InhibitAnyPolicy
						if(this.certs[i].extensions[j].extnID === "2.5.29.54")
						{
							if(inhibitAnyPolicyIndicator === false)
							{
								if(this.certs[i].extensions[j].parsedValue.valueBlock.valueDec === 0)
									inhibitAnyPolicyIndicator = true;
								else
								{
									if(pendingConstraints[2] === false)
									{
										pendingConstraints[2] = true;
										inhibitAnyPolicyPending = this.certs[i].extensions[j].parsedValue.valueBlock.valueDec;
									}
									else
										inhibitAnyPolicyPending = (inhibitAnyPolicyPending > this.certs[i].extensions[j].parsedValue.valueBlock.valueDec) ? this.certs[i].extensions[j].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++)
						{
							Eif(allPolicies[searchAnyPolicy] === "2.5.29.32.0")
							{
								policyIndex = searchAnyPolicy;
								break;
							}
						}
						//endregion
						
						Eif(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 === "2.5.29.32.0") || (policyMappings[i + 1].mappings[k].subjectDomainPolicy === "2.5.29.32.0"))
						{
							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 indedes
						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
								Eif((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] === "2.5.29.32.0")
				{
					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] === "2.5.29.32.0") && (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++)
							{
								Eif(allPolicies[k] === "2.5.29.32.0")
								{
									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 = [];
			
			if((initialPolicySet.length === 1) && (initialPolicySet[0] === "2.5.29.32.0") && (explicitPolicyIndicator === false))
				userConstrPolicies = initialPolicySet;
			else
			{
				Iif((authConstrPolicies.length === 1) && (authConstrPolicies[0] === "2.5.29.32.0"))
					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] === "2.5.29.32.0"))
							{
								userConstrPolicies.push(authConstrPolicies[i]);
								break;
							}
						}
					}
				}
			}
			//endregion
			
			//region Combine output object
			const policyResult = {
				result: (userConstrPolicies.length > 0),
				resultCode: 0,
				resultMessage: (userConstrPolicies.length > 0) ? "" : "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 Auxiliary functions for name constraints checking
			function compareDNSName(name, constraint)
			{
				/// <summary>Compare two dNSName values</summary>
				/// <param name="name" type="String">DNS from name</param>
				/// <param name="constraint" type="String">Constraint for DNS from name</param>
				/// <returns type="Boolean">Boolean result - valid or invalid the "name" against the "constraint"</returns>
				
				//region Make a "string preparation" for both name and constrain
				const namePrepared = stringPrep(name);
				const constraintPrepared = 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++)
				{
					Iif(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)
					{
						Eif(i === 0)
						{
							Iif(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;
			}
			
			function compareRFC822Name(name, constraint)
			{
				/// <summary>Compare two rfc822Name values</summary>
				/// <param name="name" type="String">E-mail address from name</param>
				/// <param name="constraint" type="String">Constraint for e-mail address from name</param>
				/// <returns type="Boolean">Boolean result - valid or invalid the "name" against the "constraint"</returns>
				
				//region Make a "string preparation" for both name and constrain
				const namePrepared = stringPrep(name);
				const constraintPrepared = 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
				Iif((nameSplitted.length === 0) || (constraintSplitted.length === 0) || (nameSplitted.length < constraintSplitted.length))
					return false;
				//endregion
				
				Eif(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);
			}
			
			function compareUniformResourceIdentifier(name, constraint)
			{
				/// <summary>Compare two uniformResourceIdentifier values</summary>
				/// <param name="name" type="String">uniformResourceIdentifier from name</param>
				/// <param name="constraint" type="String">Constraint for uniformResourceIdentifier from name</param>
				/// <returns type="Boolean">Boolean result - valid or invalid the "name" against the "constraint"</returns>
				
				//region Make a "string preparation" for both name and constrain
				let namePrepared = stringPrep(name);
				const constraintPrepared = stringPrep(constraint);
				//endregion
				
				//region Find out a major URI part to compare with
				const ns = namePrepared.split("/");
				const cs = constraintPrepared.split("/");
				
				Iif(cs.length > 1) // Malformed constraint
					return false;
				
				Eif(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;
			}
			
			function compareIPAddress(name, constraint)
			{
				/// <summary>Compare two iPAddress values</summary>
				/// <param name="name" type="in_window.org.pkijs.asn1.OCTETSTRING">iPAddress from name</param>
				/// <param name="constraint" type="in_window.org.pkijs.asn1.OCTETSTRING">Constraint for iPAddress from name</param>
				/// <returns type="Boolean">Boolean result - valid or invalid the "name" against the "constraint"</returns>
				
				//region Common variables
				const nameView = new Uint8Array(name.valueBlock.valueHex);
				const constraintView = new Uint8Array(constraint.valueBlock.valueHex);
				//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;
			}
			
			function compareDirectoryName(name, constraint)
			{
				/// <summary>Compare two directoryName values</summary>
				/// <param name="name" type="in_window.org.pkijs.simpl.RDN">directoryName from name</param>
				/// <param name="constraint" type="in_window.org.pkijs.simpl.RDN">Constraint for directoryName from name</param>
				/// <param name="any" type="Boolean">Boolean flag - should be comparision interrupted after first match or we need to match all "constraints" parts</param>
				/// <returns type="Boolean">Boolean result - valid or invalid the "name" against the "constraint"</returns>
				
				//region Initial check
				if((name.typesAndValues.length === 0) || (constraint.typesAndValues.length === 0))
					return true;
				
				Iif(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)
						{
							Eif((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
			
			//region Check a result from "policy checking" part
			Iif(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++)
			{
				//region Support variables
				let subjectAltNames = [];
				
				let certPermittedSubtrees = [];
				let certExcludedSubtrees = [];
				//endregion
				
				Eif("extensions" in this.certs[i])
				{
					for(let j = 0; j < this.certs[i].extensions.length; j++)
					{
						//region NameConstraints
						if(this.certs[i].extensions[j].extnID === "2.5.29.30")
						{
							if("permittedSubtrees" in this.certs[i].extensions[j].parsedValue)
								certPermittedSubtrees = certPermittedSubtrees.concat(this.certs[i].extensions[j].parsedValue.permittedSubtrees);
							
							if("excludedSubtrees" in this.certs[i].extensions[j].parsedValue)
								certExcludedSubtrees = certExcludedSubtrees.concat(this.certs[i].extensions[j].parsedValue.excludedSubtrees);
						}
						//endregion
						
						//region SubjectAltName
						if(this.certs[i].extensions[j].extnID === "2.5.29.17")
							subjectAltNames = subjectAltNames.concat(this.certs[i].extensions[j].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 !== this.certs[i].subject.typesAndValues.length)
								continue;
							
							formFound = true;
							
							for(let k = 0; k < this.certs[i].subject.typesAndValues.length; k++)
							{
								if(this.certs[i].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 ???
					}
				}
				
				Iif(formFound === false)
				{
					policyResult.result = false;
					policyResult.resultCode = 21;
					policyResult.resultMessage = "No neccessary name form found";
					
					throw policyResult;
				}
				//endregion
				
				//region Checking for "permited sub-trees"
				//region Make groups for all types of constraints
				const constrGroups = []; // Array of array for groupped constraints
				constrGroups[0] = []; // rfc822Name
				constrGroups[1] = []; // dNSName
				constrGroups[2] = []; // directoryName
				constrGroups[3] = []; // uniformResourceIdentifier
				constrGroups[4] = []; // 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++)
									{
										Eif(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 < this.certs[i].subject.typesAndValues.length; k++)
									{
										if((this.certs[i].subject.typesAndValues[k].type === "1.2.840.113549.1.9.1") ||    // PKCS#9 e-mail address
											(this.certs[i].subject.typesAndValues[k].type === "0.9.2342.19200300.100.1.3")) // RFC1274 "rfc822Mailbox" e-mail address
										{
											valueExists = true;
											groupPermitted = groupPermitted || compareRFC822Name(this.certs[i].subject.typesAndValues[k].value.valueBlock.value, group[j].base.value);
										}
									}
								}
								break;
							//endregion
							//region dNSName
							case 1:
								Eif(subjectAltNames.length > 0)
								{
									for(let k = 0; k < subjectAltNames.length; k++)
									{
										Eif(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(this.certs[i].subject, group[j].base.value);
								break;
							//endregion
							//region uniformResourceIdentifier
							case 3:
								Eif(subjectAltNames.length > 0)
								{
									for(let k = 0; k < subjectAltNames.length; k++)
									{
										Eif(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:
							Eif(subjectAltNames.length >= 0)
							{
								for(let k = 0; k < subjectAltNames.length; k++)
								{
									Eif(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 < this.subject.typesAndValues.length; k++)
								{
									if((this.subject.typesAndValues[k].type === "1.2.840.113549.1.9.1") ||    // PKCS#9 e-mail address
										(this.subject.typesAndValues[k].type === "0.9.2342.19200300.100.1.3")) // RFC1274 "rfc822Mailbox" e-mail address
										excluded = excluded || compareRFC822Name(this.subject.typesAndValues[k].value.valueBlock.value, excludedSubtrees[j].base.value);
								}
							}
							break;
						//endregion
						//region dNSName
						case 2:
							Eif(subjectAltNames.length > 0)
							{
								for(let k = 0; k < subjectAltNames.length; k++)
								{
									Eif(subjectAltNames[k].type === 2) // dNSName
										excluded = excluded || compareDNSName(subjectAltNames[k].value, excludedSubtrees[j].base.value);
								}
							}
							break;
						//endregion
						//region directoryName
						case 4:
							excluded = excluded || compareDirectoryName(this.certs[i].subject, excludedSubtrees[j].base.value);
							break;
						//endregion
						//region uniformResourceIdentifier
						case 6:
							Eif(subjectAltNames.length > 0)
							{
								for(let k = 0; k < subjectAltNames.length; k++)
								{
									Eif(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)
		{
			Eif(error instanceof Object)
			{
				if("resultMessage" in error)
					return error;
				
				Eif("message" in error)
				{
					return {
						result: false,
						resultCode: -1,
						resultMessage: error.message
					};
				}
			}
			
			return {
				result: false,
				resultCode: -1,
				resultMessage: error
			};
		}
	}
	//**********************************************************************************
}
//**************************************************************************************