All files / src SignedData.js

53.8% Statements 198/368
45.85% Branches 127/277
55.1% Functions 27/49
54.34% Lines 194/357

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                                                                                          193x         193x         193x   193x         73x   193x                     193x       193x 120x                   845x     193x   193x   193x   73x       193x                                                                                                           120x   120x 120x   120x                                                                                                                         120x         120x         120x   120x 108x   120x   120x   120x   144x     144x                                                                                     120x                               120x 108x                     73x   73x     73x 61x       73x   73x   73x             97x                   97x         73x                                                 73x 61x           73x                                                                                                         60x   60x       60x   60x   60x   60x       60x 60x         60x                                     60x                                     60x   60x   60x   60x     60x     60x 60x                                                                                                                                               60x   60x     12x         12x     12x   12x                 12x 12x       12x                                   12x     48x                                                                         60x                                                                                                                                                                           60x     60x       60x 60x                                 60x   60x         60x     60x       60x   36x     36x 12x     24x 24x               24x                                   60x     24x 24x   24x     72x 24x       72x   24x 24x         72x 24x       24x                                 24x                                     60x         60x     60x           60x 20x   40x   60x 60x                                 60x 60x 40x     60x     20x   20x   20x   20x 20x       20x     20x 20x       20x         60x 60x 60x   60x         60x     60x       60x     60x 24x   36x         60x       60x   24x   24x 24x           36x       60x         60x 60x 60x       60x       20x   20x                                     20x 20x       20x   20x   20x 20x                                 20x     20x         60x   60x   20x 20x       60x               60x   60x                           60x                                             60x                           61x         61x     61x       61x 61x         61x   61x           61x             61x   61x   61x 61x         61x   61x   25x       25x     25x 25x           36x   24x     24x 12x     12x 12x               12x         61x         61x   61x   61x   61x       61x          
import * as asn1js from "asn1js";
import { getParametersValue, utilConcatBuf, isEqualBuffer } from "pvutils";
import {
	getCrypto,
	getEngine,
	getOIDByAlgorithm,
	getAlgorithmByOID,
	createECDSASignatureFromCMS,
	getAlgorithmParameters
} from "./common.js";
import AlgorithmIdentifier from "./AlgorithmIdentifier.js";
import EncapsulatedContentInfo from "./EncapsulatedContentInfo.js";
import Certificate from "./Certificate.js";
import OtherCertificateFormat from "./OtherCertificateFormat.js";
import CertificateRevocationList from "./CertificateRevocationList.js";
import OtherRevocationInfoFormat from "./OtherRevocationInfoFormat.js";
import SignerInfo from "./SignerInfo.js";
import CertificateSet from "./CertificateSet.js";
import RevocationInfoChoices from "./RevocationInfoChoices.js";
import IssuerAndSerialNumber from "./IssuerAndSerialNumber.js";
import TSTInfo from "./TSTInfo.js";
import CertificateChainValidationEngine from "./CertificateChainValidationEngine.js";
import BasicOCSPResponse from "./BasicOCSPResponse.js";
import RSASSAPSSParams from "./RSASSAPSSParams.js";
import AttributeCertificateV1 from "./AttributeCertificateV1.js";
import AttributeCertificateV2 from "./AttributeCertificateV2.js";
//**************************************************************************************
/**
 * Class from RFC5652
 */
export default class SignedData 
{
	//**********************************************************************************
	/**
	 * Constructor for SignedData class
	 * @param {Object} [parameters={}]
	 * @property {Object} [schema] asn1js parsed value
	 */
	constructor(parameters = {})
	{
		//region Internal properties of the object
		/**
		 * @type {number}
		 * @description version
		 */
		this.version = getParametersValue(parameters, "version", SignedData.defaultValues("version"));
		/**
		 * @type {Array.<AlgorithmIdentifier>}
		 * @description digestAlgorithms
		 */
		this.digestAlgorithms = getParametersValue(parameters, "digestAlgorithms", SignedData.defaultValues("digestAlgorithms"));
		/**
		 * @type {EncapsulatedContentInfo}
		 * @description encapContentInfo
		 */
		this.encapContentInfo = getParametersValue(parameters, "encapContentInfo", SignedData.defaultValues("encapContentInfo"));
		
		if("certificates" in parameters)
			/**
			 * @type {Array.<Certificate|OtherCertificateFormat>}
			 * @description certificates
			 */
			this.certificates = getParametersValue(parameters, "certificates", SignedData.defaultValues("certificates"));
		
		Iif("crls" in parameters)
			/**
			 * @type {Array.<CertificateRevocationList|OtherRevocationInfoFormat>}
			 * @description crls
			 */
			this.crls = getParametersValue(parameters, "crls", SignedData.defaultValues("crls"));
		
		/**
		 * @type {Array.<SignerInfo>}
		 * @description signerInfos
		 */
		this.signerInfos = getParametersValue(parameters, "signerInfos", SignedData.defaultValues("signerInfos"));
		//endregion
		
		//region If input argument array contains "schema" for this object
		if("schema" in parameters)
			this.fromSchema(parameters.schema);
		//endregion
	}
	//**********************************************************************************
	/**
	 * Return default values for all class members
	 * @param {string} memberName String name for a class member
	 */
	static defaultValues(memberName)
	{
		switch(memberName)
		{
			case "version":
				return 0;
			case "digestAlgorithms":
				return [];
			case "encapContentInfo":
				return new EncapsulatedContentInfo();
			case "certificates":
				return [];
			case "crls":
				return [];
			case "signerInfos":
				return [];
			default:
				throw new Error(`Invalid member name for SignedData class: ${memberName}`);
		}
	}
	//**********************************************************************************
	/**
	 * Compare values with default values for all class members
	 * @param {string} memberName String name for a class member
	 * @param {*} memberValue Value to compare with default value
	 */
	static compareWithDefault(memberName, memberValue)
	{
		switch(memberName)
		{
			case "version":
				return (memberValue === SignedData.defaultValues("version"));
			case "encapContentInfo":
				return new EncapsulatedContentInfo();
			case "digestAlgorithms":
			case "certificates":
			case "crls":
			case "signerInfos":
				return (memberValue.length === 0);
			default:
				throw new Error(`Invalid member name for SignedData class: ${memberName}`);
		}
	}
	//**********************************************************************************
	/**
	 * Return value of asn1js schema for current class
	 * @param {Object} parameters Input parameters for the schema
	 * @returns {Object} asn1js schema object
	 */
	static schema(parameters = {})
	{
		//SignedData ::= SEQUENCE {
		//    version CMSVersion,
		//    digestAlgorithms DigestAlgorithmIdentifiers,
		//    encapContentInfo EncapsulatedContentInfo,
		//    certificates [0] IMPLICIT CertificateSet OPTIONAL,
		//    crls [1] IMPLICIT RevocationInfoChoices OPTIONAL,
		//    signerInfos SignerInfos }
		
		/**
		 * @type {Object}
		 * @property {string} [blockName]
		 * @property {string} [optional]
		 * @property {string} [digestAlgorithms]
		 * @property {string} [encapContentInfo]
		 * @property {string} [certificates]
		 * @property {string} [crls]
		 * @property {string} [signerInfos]
		 */
		const names = getParametersValue(parameters, "names", {});
		
		Eif(("optional" in names) === false)
			names.optional = false;
		
		return (new asn1js.Sequence({
			name: (names.blockName || "SignedData"),
			optional: names.optional,
			value: [
				new asn1js.Integer({ name: (names.version || "SignedData.version") }),
				new asn1js.Set({
					value: [
						new asn1js.Repeated({
							name: (names.digestAlgorithms || "SignedData.digestAlgorithms"),
							value: AlgorithmIdentifier.schema()
						})
					]
				}),
				EncapsulatedContentInfo.schema(names.encapContentInfo || {
					names: {
						blockName: "SignedData.encapContentInfo"
					}
				}),
				new asn1js.Constructed({
					optional: true,
					idBlock: {
						tagClass: 3, // CONTEXT-SPECIFIC
						tagNumber: 0 // [0]
					},
					value: CertificateSet.schema(names.certificates || {
						names: {
							certificates: "SignedData.certificates"
						}
					}).valueBlock.value
				}), // IMPLICIT CertificateSet
				new asn1js.Constructed({
					optional: true,
					idBlock: {
						tagClass: 3, // CONTEXT-SPECIFIC
						tagNumber: 1 // [1]
					},
					value: RevocationInfoChoices.schema(names.crls || {
						names: {
							crls: "SignedData.crls"
						}
					}).valueBlock.value
				}), // IMPLICIT RevocationInfoChoices
				new asn1js.Set({
					value: [
						new asn1js.Repeated({
							name: (names.signerInfos || "SignedData.signerInfos"),
							value: SignerInfo.schema()
						})
					]
				})
			]
		}));
	}
	//**********************************************************************************
	/**
	 * Convert parsed asn1js object into current class
	 * @param {!Object} schema
	 */
	fromSchema(schema)
	{
		//region Check the schema is valid
		const asn1 = asn1js.compareSchema(schema,
			schema,
			SignedData.schema()
		);
		
		Iif(asn1.verified === false)
			throw new Error("Object's schema was not verified against input data for SignedData");
		//endregion
		
		//region Get internal properties from parsed schema
		this.version = asn1.result["SignedData.version"].valueBlock.valueDec;
		
		if("SignedData.digestAlgorithms" in asn1.result) // Could be empty SET of digest algorithms
			this.digestAlgorithms = Array.from(asn1.result["SignedData.digestAlgorithms"], algorithm => new AlgorithmIdentifier({ schema: algorithm }));
		
		this.encapContentInfo = new EncapsulatedContentInfo({ schema: asn1.result["SignedData.encapContentInfo"] });
		
		Eif("SignedData.certificates" in asn1.result)
		{
			this.certificates = Array.from(asn1.result["SignedData.certificates"], certificate =>
			{
				switch(certificate.idBlock.tagClass)
				{
					case 1:
						return new Certificate({ schema: certificate });
					case 3:
						{
							const tagNumber = certificate.idBlock.tagNumber;
							
							//region Create SEQUENCE from [x]
							certificate.idBlock.tagClass = 1; // UNIVERSAL
							certificate.idBlock.tagNumber = 16; // SEQUENCE
							//endregion
							
							switch(tagNumber)
							{
								//region ExtendedCertificate
								case 0:
									break;
								//endregion
								//region AttributeCertificateV1
								case 1:
									return new AttributeCertificateV1({ schema: certificate });
								//endregion
								//region AttributeCertificateV2
								case 2:
									return new AttributeCertificateV2({ schema: certificate });
								//endregion
								//region OtherCertificateFormat
								case 3:
									return new OtherCertificateFormat({ schema: certificate });
								//endregion
								//region default
								default:
									throw new Error("Object's schema was not verified against input data for SignedData");
								//endregion
							}
						}
						break;
					default:
						throw new Error("Object's schema was not verified against input data for SignedData");
				}
				
				return new Certificate();
			});
		}
		
		Iif("SignedData.crls" in asn1.result)
		{
			this.crls = Array.from(asn1.result["SignedData.crls"], crl =>
			{
				if(crl.idBlock.tagClass === 1)
					return new CertificateRevocationList({ schema: crl });
				
				//region Create SEQUENCE from [1]
				crl.idBlock.tagClass = 1; // UNIVERSAL
				crl.idBlock.tagNumber = 16; // SEQUENCE
				//endregion
				
				return new OtherRevocationInfoFormat({ schema: crl });
			});
		}
		
		if("SignedData.signerInfos" in asn1.result) // Could be empty SET SignerInfos
			this.signerInfos = Array.from(asn1.result["SignedData.signerInfos"], signerInfoSchema => new SignerInfo({ schema: signerInfoSchema }));
		//endregion
	}
	//**********************************************************************************
	/**
	 * Convert current object to asn1js object and set correct values
	 * @returns {Object} asn1js object
	 */
	toSchema(encodeFlag = false)
	{
		//region Create array for output sequence
		const outputArray = [];
		
		outputArray.push(new asn1js.Integer({ value: this.version }));
		
		//region Create array of digest algorithms
		outputArray.push(new asn1js.Set({
			value: Array.from(this.digestAlgorithms, algorithm => algorithm.toSchema(encodeFlag))
		}));
		//endregion
		
		outputArray.push(this.encapContentInfo.toSchema());
		
		Eif("certificates" in this)
		{
			outputArray.push(new asn1js.Constructed({
				idBlock: {
					tagClass: 3, // CONTEXT-SPECIFIC
					tagNumber: 0 // [0]
				},
				value: Array.from(this.certificates, certificate =>
				{
					Iif(certificate instanceof OtherCertificateFormat)
					{
						const certificateSchema = certificate.toSchema(encodeFlag);
						
						certificateSchema.idBlock.tagClass = 3;
						certificateSchema.idBlock.tagNumber = 3;
						
						return certificateSchema;
					}
					
					return certificate.toSchema(encodeFlag);
				})
			}));
		}
		
		Iif("crls" in this)
		{
			outputArray.push(new asn1js.Constructed({
				idBlock: {
					tagClass: 3, // CONTEXT-SPECIFIC
					tagNumber: 1 // [1]
				},
				value: Array.from(this.crls, crl =>
				{
					if(crl instanceof OtherRevocationInfoFormat)
					{
						const crlSchema = crl.toSchema(encodeFlag);
						
						crlSchema.idBlock.tagClass = 3;
						crlSchema.idBlock.tagNumber = 1;
						
						return crlSchema;
					}
					
					return crl.toSchema(encodeFlag);
				})
			}));
		}
		
		//region Create array of signer infos
		outputArray.push(new asn1js.Set({
			value: Array.from(this.signerInfos, signerInfo => signerInfo.toSchema(encodeFlag))
		}));
		//endregion
		//endregion
		
		//region Construct and return new ASN.1 schema for this object
		return (new asn1js.Sequence({
			value: outputArray
		}));
		//endregion
	}
	//**********************************************************************************
	/**
	 * Convertion for the class to JSON object
	 * @returns {Object}
	 */
	toJSON()
	{
		const _object = {
			version: this.version,
			digestAlgorithms: Array.from(this.digestAlgorithms, algorithm => algorithm.toJSON()),
			encapContentInfo: this.encapContentInfo.toJSON()
		};
		
		if("certificates" in this)
			_object.certificates = Array.from(this.certificates, certificate => certificate.toJSON());
		
		if("crls" in this)
			_object.crls = Array.from(this.crls, crl => crl.toJSON());
		
		_object.signerInfos = Array.from(this.signerInfos, signerInfo => signerInfo.toJSON());
		
		return _object;
	}
	//**********************************************************************************
	/**
	 * Verify current SignedData value
	 * @param signer
	 * @param data
	 * @param trustedCerts
	 * @param checkDate
	 * @param checkChain
	 * @param includeSignerCertificate
	 * @param extendedMode
	 * @returns {*}
	 */
	verify({
		signer = (-1),
		data = (new ArrayBuffer(0)),
		trustedCerts = [],
		checkDate = (new Date()),
		checkChain = false,
		includeSignerCertificate = false,
		extendedMode = false,
		findOrigin = null,
		findIssuer = null
	} = {})
	{
		//region Global variables 
		let sequence = Promise.resolve();
		
		let messageDigestValue = new ArrayBuffer(0);
		
		let publicKey;
		
		let shaAlgorithm = "";
		
		let signerCertificate = {};
		
		let timestampSerial = null;
		
		let certificatePath = [];
		//endregion
		
		//region Get a "crypto" extension
		const crypto = getCrypto();
		Iif(typeof crypto === "undefined")
			return Promise.reject("Unable to create WebCrypto object");
		//endregion
		
		//region Get a signer number
		Iif(signer === (-1))
		{
			if(extendedMode)
			{
				return Promise.reject({
					date: checkDate,
					code: 1,
					message: "Unable to get signer index from input parameters",
					signatureVerified: null,
					signerCertificate: null,
					signerCertificateVerified: null
				});
			}
			
			return Promise.reject("Unable to get signer index from input parameters");
		}
		//endregion
		
		//region Check that certificates field was included in signed data
		Iif(("certificates" in this) === false)
		{
			if(extendedMode)
			{
				return Promise.reject({
					date: checkDate,
					code: 2,
					message: "No certificates attached to this signed data",
					signatureVerified: null,
					signerCertificate: null,
					signerCertificateVerified: null
				});
			}
			
			return Promise.reject("No certificates attached to this signed data");
		}
		//endregion
		
		//region Find a certificate for specified signer
		Eif(this.signerInfos[signer].sid instanceof IssuerAndSerialNumber)
		{
			sequence = sequence.then(() =>
			{
				for(const certificate of this.certificates)
				{
					Iif((certificate instanceof Certificate) === false)
						continue;
					
					Eif((certificate.issuer.isEqual(this.signerInfos[signer].sid.issuer)) &&
						(certificate.serialNumber.isEqual(this.signerInfos[signer].sid.serialNumber)))
					{
						signerCertificate = certificate;
						return Promise.resolve();
					}
				}
				
				if(extendedMode)
				{
					return Promise.reject({
						date: checkDate,
						code: 3,
						message: "Unable to find signer certificate",
						signatureVerified: null,
						signerCertificate: null,
						signerCertificateVerified: null
					});
				}
				
				return Promise.reject("Unable to find signer certificate");
			});
		}
		else // Find by SubjectKeyIdentifier
		{
			sequence = sequence.then(() =>
				Promise.all(Array.from(this.certificates.filter(certificate => (certificate instanceof Certificate)), certificate =>
					crypto.digest({ name: "sha-1" }, new Uint8Array(certificate.subjectPublicKeyInfo.subjectPublicKey.valueBlock.valueHex)))
				).then(results =>
				{
					for(const [index, certificate] of this.certificates.entries())
					{
						if((certificate instanceof Certificate) === false)
							continue;
						
						if(isEqualBuffer(results[index], this.signerInfos[signer].sid.valueBlock.valueHex))
						{
							signerCertificate = certificate;
							return Promise.resolve();
						}
					}
					
					if(extendedMode)
					{
						return Promise.reject({
							date: checkDate,
							code: 3,
							message: "Unable to find signer certificate",
							signatureVerified: null,
							signerCertificate: null,
							signerCertificateVerified: null
						});
					}
					
					return Promise.reject("Unable to find signer certificate");
				}, () =>
				{
					if(extendedMode)
					{
						return Promise.reject({
							date: checkDate,
							code: 3,
							message: "Unable to find signer certificate",
							signatureVerified: null,
							signerCertificate: null,
							signerCertificateVerified: null
						});
					}
					
					return Promise.reject("Unable to find signer certificate");
				})
			);
		}
		//endregion
		
		//region Verify internal digest in case of "tSTInfo" content type
		sequence = sequence.then(() =>
		{
			if(this.encapContentInfo.eContentType === "1.2.840.113549.1.9.16.1.4")
			{
				//region Check "eContent" precense
				Iif(("eContent" in this.encapContentInfo) === false)
					return false;
				//endregion
				
				//region Initialize TST_INFO value
				const asn1 = asn1js.fromBER(this.encapContentInfo.eContent.valueBlock.valueHex);
				let tstInfo;
				
				try
				{
					tstInfo = new TSTInfo({ schema: asn1.result });
				}
				catch(ex)
				{
					return false;
				}
				//endregion
				
				//region Change "checkDate" and append "timestampSerial"
				checkDate = tstInfo.genTime;
				timestampSerial = tstInfo.serialNumber.valueBlock.valueHex;
				//endregion
				
				//region Check that we do have detached data content
				Iif(data.byteLength === 0)
				{
					if(extendedMode)
					{
						return Promise.reject({
							date: checkDate,
							code: 4,
							message: "Missed detached data input array",
							signatureVerified: null,
							signerCertificate,
							signerCertificateVerified: null
						});
					}
					
					return Promise.reject("Missed detached data input array");
				}
				//endregion
				
				return tstInfo.verify({ data });
			}
			
			return true;
		});
		//endregion
		
		//region Make additional verification for signer's certificate
		function checkCA(cert)
		{
			/// <param name="cert" type="in_window.org.pkijs.simpl.CERT">Certificate to find CA flag for</param>
			
			//region Do not include signer's certificate
			if((cert.issuer.isEqual(signerCertificate.issuer) === true) && (cert.serialNumber.isEqual(signerCertificate.serialNumber) === true))
				return null;
			//endregion
			
			let isCA = false;
			
			if("extensions" in cert)
			{
				for(const extension of cert.extensions)
				{
					if(extension.extnID === "2.5.29.19") // BasicConstraints
					{
						if("cA" in extension.parsedValue)
						{
							if(extension.parsedValue.cA === true)
								isCA = true;
						}
					}
				}
			}
			
			if(isCA)
				return cert;
			
			return null;
		}
		
		Iif(checkChain)
		{
			sequence = sequence.then(result =>
			{
				//region Verify result of previous operation
				if(result === false)
					return false;
				//endregion
				
				const promiseResults = Array.from(this.certificates.filter(certificate => (certificate instanceof Certificate)), certificate => checkCA(certificate));
				
				const certificateChainValidationEngineParameters = {
					checkDate,
					certs: Array.from(promiseResults.filter(_result => (_result !== null))),
					trustedCerts
				};
				
				if(findIssuer !== null)
					certificateChainValidationEngineParameters.findIssuer = findIssuer;
				
				if(findOrigin !== null)
					certificateChainValidationEngineParameters.findOrigin = findOrigin;
 
				const certificateChainEngine = new CertificateChainValidationEngine(certificateChainValidationEngineParameters);
				
				certificateChainEngine.certs.push(signerCertificate);
				
				if("crls" in this)
				{
					for(const crl of this.crls)
					{
						if(crl instanceof CertificateRevocationList)
							certificateChainEngine.crls.push(crl);
						else // Assumed "revocation value" has "OtherRevocationInfoFormat"
						{
							if(crl.otherRevInfoFormat === "1.3.6.1.5.5.7.48.1.1") // Basic OCSP response
								certificateChainEngine.ocsps.push(new BasicOCSPResponse({ schema: crl.otherRevInfo }));
						}
					}
				}
				
				if("ocsps" in this)
					certificateChainEngine.ocsps.push(...(this.ocsps));
				
				return certificateChainEngine.verify().then(verificationResult =>
				{
					if("certificatePath" in verificationResult)
						certificatePath = verificationResult.certificatePath;
					
					if(verificationResult.result === true)
						return Promise.resolve(true);
					
					if(extendedMode)
					{
						return Promise.reject({
							date: checkDate,
							code: 5,
							message: `Validation of signer's certificate failed: ${verificationResult.resultMessage}`,
							signatureVerified: null,
							signerCertificate,
							signerCertificateVerified: false
						});
					}
					
					return Promise.reject("Validation of signer's certificate failed");
				}, error =>
				{
					if(extendedMode)
					{
						return Promise.reject({
							date: checkDate,
							code: 5,
							message: `Validation of signer's certificate failed with error: ${((error instanceof Object) ? error.resultMessage : error)}`,
							signatureVerified: null,
							signerCertificate,
							signerCertificateVerified: false
						});
					}
					
					return Promise.reject(`Validation of signer's certificate failed with error: ${((error instanceof Object) ? error.resultMessage : error)}`);
				});
			});
		}
		//endregion
		
		//region Find signer's hashing algorithm
		sequence = sequence.then(result =>
		{
			//region Verify result of previous operation
			Iif(result === false)
				return false;
			//endregion
			
			const signerInfoHashAlgorithm = getAlgorithmByOID(this.signerInfos[signer].digestAlgorithm.algorithmId);
			Iif(("name" in signerInfoHashAlgorithm) === false)
			{
				if(extendedMode)
				{
					return Promise.reject({
						date: checkDate,
						code: 7,
						message: `Unsupported signature algorithm: ${this.signerInfos[signer].digestAlgorithm.algorithmId}`,
						signatureVerified: null,
						signerCertificate,
						signerCertificateVerified: true
					});
				}
				
				return Promise.reject(`Unsupported signature algorithm: ${this.signerInfos[signer].digestAlgorithm.algorithmId}`);
			}
			
			shaAlgorithm = signerInfoHashAlgorithm.name;
			
			return true;
		});
		//endregion
		
		//region Create correct data block for verification
		sequence = sequence.then(result =>
		{
			//region Verify result of previous operation
			Iif(result === false)
				return false;
			//endregion
			
			if("eContent" in this.encapContentInfo) // Attached data
			{
				Eif((this.encapContentInfo.eContent.idBlock.tagClass === 1) &&
					(this.encapContentInfo.eContent.idBlock.tagNumber === 4))
				{
					if(this.encapContentInfo.eContent.idBlock.isConstructed === false)
						data = this.encapContentInfo.eContent.valueBlock.valueHex;
					else
					{
						for(const contentValue of this.encapContentInfo.eContent.valueBlock.value)
							data = utilConcatBuf(data, contentValue.valueBlock.valueHex);
					}
				}
				else
					data = this.encapContentInfo.eContent.valueBlock.valueBeforeDecode;
			}
			else // Detached data
			{
				Iif(data.byteLength === 0) // Check that "data" already provided by function parameter
				{
					if(extendedMode)
					{
						return Promise.reject({
							date: checkDate,
							code: 8,
							message: "Missed detached data input array",
							signatureVerified: null,
							signerCertificate,
							signerCertificateVerified: true
						});
					}
					
					return Promise.reject("Missed detached data input array");
				}
			}
			
			if("signedAttrs" in this.signerInfos[signer])
			{
				//region Check mandatory attributes
				let foundContentType = false;
				let foundMessageDigest = false;
				
				for(const attribute of this.signerInfos[signer].signedAttrs.attributes)
				{
					//region Check that "content-type" attribute exists
					if(attribute.type === "1.2.840.113549.1.9.3")
						foundContentType = true;
					//endregion
					
					//region Check that "message-digest" attribute exists
					if(attribute.type === "1.2.840.113549.1.9.4")
					{
						foundMessageDigest = true;
						messageDigestValue = attribute.values[0].valueBlock.valueHex;
					}
					//endregion
					
					//region Speed-up searching
					if(foundContentType && foundMessageDigest)
						break;
					//endregion
				}
				
				Iif(foundContentType === false)
				{
					if(extendedMode)
					{
						return Promise.reject({
							date: checkDate,
							code: 9,
							message: "Attribute \"content-type\" is a mandatory attribute for \"signed attributes\"",
							signatureVerified: null,
							signerCertificate,
							signerCertificateVerified: true
						});
					}
					
					return Promise.reject("Attribute \"content-type\" is a mandatory attribute for \"signed attributes\"");
				}
				
				Iif(foundMessageDigest === false)
				{
					if(extendedMode)
					{
						return Promise.reject({
							date: checkDate,
							code: 10,
							message: "Attribute \"message-digest\" is a mandatory attribute for \"signed attributes\"",
							signatureVerified: null,
							signerCertificate,
							signerCertificateVerified: true
						});
					}
					
					return Promise.reject("Attribute \"message-digest\" is a mandatory attribute for \"signed attributes\"");
				}
				//endregion
			}
			
			return true;
		});
		//endregion
		
		//region Import public key from signer's certificate
		sequence = sequence.then(result =>
		{
			//region Verify result of previous operation
			Iif(result === false)
				return false;
			//endregion
			
			//region Get information about public key algorithm and default parameters for import
			let algorithmId;
			if(signerCertificate.signatureAlgorithm.algorithmId === "1.2.840.113549.1.1.10")
				algorithmId = signerCertificate.signatureAlgorithm.algorithmId;
			else
				algorithmId = signerCertificate.subjectPublicKeyInfo.algorithm.algorithmId;
			
			const algorithmObject = getAlgorithmByOID(algorithmId);
			Iif(("name" in algorithmObject) === false)
			{
				if(extendedMode)
				{
					return Promise.reject({
						date: checkDate,
						code: 11,
						message: `Unsupported public key algorithm: ${algorithmId}`,
						signatureVerified: null,
						signerCertificate,
						signerCertificateVerified: true
					});
				}
				
				return Promise.reject(`Unsupported public key algorithm: ${algorithmId}`);
			}
			
			const algorithm = getAlgorithmParameters(algorithmObject.name, "importkey");
			if("hash" in algorithm.algorithm)
				algorithm.algorithm.hash.name = shaAlgorithm;
			
			//region Special case for ECDSA
			if(algorithmObject.name === "ECDSA")
			{
				//region Get information about named curve
				let algorithmParamsChecked = false;
				
				Eif(("algorithmParams" in signerCertificate.subjectPublicKeyInfo.algorithm) === true)
				{
					Eif("idBlock" in signerCertificate.subjectPublicKeyInfo.algorithm.algorithmParams)
					{
						Eif((signerCertificate.subjectPublicKeyInfo.algorithm.algorithmParams.idBlock.tagClass === 1) && (signerCertificate.subjectPublicKeyInfo.algorithm.algorithmParams.idBlock.tagNumber === 6))
							algorithmParamsChecked = true;
					}
				}
				
				Iif(algorithmParamsChecked === false)
					return Promise.reject("Incorrect type for ECDSA public key parameters");
				
				const curveObject = getAlgorithmByOID(signerCertificate.subjectPublicKeyInfo.algorithm.algorithmParams.valueBlock.toString());
				Iif(("name" in curveObject) === false)
					return Promise.reject(`Unsupported named curve algorithm: ${signerCertificate.subjectPublicKeyInfo.algorithm.algorithmParams.valueBlock.toString()}`);
				//endregion
				
				algorithm.algorithm.namedCurve = curveObject.name;
			}
			//endregion
			//endregion
			
			const publicKeyInfoSchema = signerCertificate.subjectPublicKeyInfo.toSchema();
			const publicKeyInfoBuffer = publicKeyInfoSchema.toBER(false);
			const publicKeyInfoView = new Uint8Array(publicKeyInfoBuffer);
			
			return crypto.importKey("spki", publicKeyInfoView, algorithm.algorithm, true, algorithm.usages);
		});
		//endregion
		
		//region Verify signer's signature
		sequence = sequence.then(result =>
		{
			//region Verify result of previous operation
			Iif(typeof result === "boolean")
				return false;
			//endregion
			
			publicKey = result;
			
			//region Verify "message-digest" attribute in case of "signedAttrs"
			if("signedAttrs" in this.signerInfos[signer])
				return crypto.digest(shaAlgorithm, new Uint8Array(data));
			
			return true;
			//endregion
		}).then(result =>
		{
			//region Verify result of previous operation
			Iif(result === false)
				return false;
			//endregion
			
			if("signedAttrs" in this.signerInfos[signer])
			{
				Eif(isEqualBuffer(result, messageDigestValue))
				{
					data = this.signerInfos[signer].signedAttrs.encodedValue;
					return true;
				}
				
				return false;
			}
			
			return true;
		}).then(result =>
		{
			//region Check result of previous operation
			Iif(result === false)
				return false;
			//endregion
			
			//region Get default algorithm parameters for verification
			const algorithm = getAlgorithmParameters(publicKey.algorithm.name, "verify");
			Eif("hash" in algorithm.algorithm)
				algorithm.algorithm.hash.name = shaAlgorithm;
			//endregion
			
			//region Special case for RSA-PSS
			if(publicKey.algorithm.name === "RSA-PSS")
			{
				let pssParameters;
				
				try
				{
					pssParameters = new RSASSAPSSParams({ schema: this.signerInfos[signer].signatureAlgorithm.algorithmParams });
				}
				catch(ex)
				{
					if(extendedMode)
					{
						return Promise.reject({
							date: checkDate,
							code: 12,
							message: ex,
							signatureVerified: null,
							signerCertificate,
							signerCertificateVerified: true
						});
					}
					
					return Promise.reject(ex);
				}
				
				Eif("saltLength" in pssParameters)
					algorithm.algorithm.saltLength = pssParameters.saltLength;
				else
					algorithm.algorithm.saltLength = 20;
				
				let hashName = "SHA-1";
				
				Eif("hashAlgorithm" in pssParameters)
				{
					const hashAlgorithm = getAlgorithmByOID(pssParameters.hashAlgorithm.algorithmId);
					Iif(("name" in hashAlgorithm) === false)
					{
						if(extendedMode)
						{
							return Promise.reject({
								date: checkDate,
								code: 13,
								message: `Unrecognized hash algorithm: ${pssParameters.hashAlgorithm.algorithmId}`,
								signatureVerified: null,
								signerCertificate,
								signerCertificateVerified: true
							});
						}
						
						return Promise.reject(`Unrecognized hash algorithm: ${pssParameters.hashAlgorithm.algorithmId}`);
					}
					
					hashName = hashAlgorithm.name;
				}
				
				algorithm.algorithm.hash.name = hashName;
			}
			//endregion
			
			//region Special case for ECDSA signatures
			let signatureValue = this.signerInfos[signer].signature.valueBlock.valueHex;
			
			if(publicKey.algorithm.name === "ECDSA")
			{
				const asn1 = asn1js.fromBER(signatureValue);
				signatureValue = createECDSASignatureFromCMS(asn1.result);
			}
			//endregion
			
			return crypto.verify(algorithm.algorithm,
				publicKey,
				new Uint8Array(signatureValue),
				new Uint8Array(data));
		});
		//endregion
		
		//region Make a final result
		sequence = sequence.then(result =>
		{
			Iif(extendedMode)
			{
				return {
					date: checkDate,
					code: 14,
					message: "",
					signatureVerified: result,
					signerCertificate,
					timestampSerial,
					signerCertificateVerified: true,
					certificatePath
				};
			}
			
			return result;
		}, error =>
		{
			if(extendedMode)
			{
				if("code" in error)
					return Promise.reject(error);
				
				return Promise.reject({
					date: checkDate,
					code: 15,
					message: `Error during verification: ${error.message}`,
					signatureVerified: null,
					signerCertificate,
					timestampSerial,
					signerCertificateVerified: true
				});
			}
			
			return Promise.reject(error);
		});
		//endregion 
		
		return sequence;
	}
	//**********************************************************************************
	/**
	 * Signing current SignedData
	 * @param {key} privateKey Private key for "subjectPublicKeyInfo" structure
	 * @param {number} signerIndex Index number (starting from 0) of signer index to make signature for
	 * @param {string} [hashAlgorithm="SHA-1"] Hashing algorithm. Default SHA-1
	 * @param {ArrayBuffer} [data] Detached data
	 * @returns {*}
	 */
	sign(privateKey, signerIndex, hashAlgorithm = "SHA-1", data = (new ArrayBuffer(0)))
	{
		//region Initial checking
		Iif(typeof privateKey === "undefined")
			return Promise.reject("Need to provide a private key for signing");
		//endregion
		
		//region Initial variables
		let sequence = Promise.resolve();
		let parameters;
		
		const engine = getEngine();
		//endregion
		
		//region Simple check for supported algorithm
		const hashAlgorithmOID = getOIDByAlgorithm({ name: hashAlgorithm });
		Iif(hashAlgorithmOID === "")
			return Promise.reject(`Unsupported hash algorithm: ${hashAlgorithm}`);
		//endregion
		
		//region Append information about hash algorithm
		Eif((this.digestAlgorithms.filter(algorithm => algorithm.algorithmId === hashAlgorithmOID)).length === 0)
		{
			this.digestAlgorithms.push(new AlgorithmIdentifier({
				algorithmId: hashAlgorithmOID,
				algorithmParams: new asn1js.Null()
			}));
		}
		
		this.signerInfos[signerIndex].digestAlgorithm = new AlgorithmIdentifier({
			algorithmId: hashAlgorithmOID,
			algorithmParams: new asn1js.Null()
		});
		//endregion
		
		//region Get a "default parameters" for current algorithm and set correct signature algorithm
		sequence = sequence.then(() => engine.subtle.getSignatureParameters(privateKey, hashAlgorithm));
		
		sequence = sequence.then(result =>
		{
			parameters = result.parameters;
			this.signerInfos[signerIndex].signatureAlgorithm = result.signatureAlgorithm;
		});
		//endregion
		
		//region Create TBS data for signing
		sequence = sequence.then(() =>
		{
			if("signedAttrs" in this.signerInfos[signerIndex])
			{
				Iif(this.signerInfos[signerIndex].signedAttrs.encodedValue.byteLength !== 0)
					data = this.signerInfos[signerIndex].signedAttrs.encodedValue;
				else
				{
					data = this.signerInfos[signerIndex].signedAttrs.toSchema(true).toBER(false);
					
					//region Change type from "[0]" to "SET" acordingly to standard
					const view = new Uint8Array(data);
					view[0] = 0x31;
					//endregion
				}
			}
			else
			{
				if("eContent" in this.encapContentInfo) // Attached data
				{
					Eif((this.encapContentInfo.eContent.idBlock.tagClass === 1) &&
						(this.encapContentInfo.eContent.idBlock.tagNumber === 4))
					{
						if(this.encapContentInfo.eContent.idBlock.isConstructed === false)
							data = this.encapContentInfo.eContent.valueBlock.valueHex;
						else
						{
							for(const content of this.encapContentInfo.eContent.valueBlock.value)
								data = utilConcatBuf(data, content.valueBlock.valueHex);
						}
					}
					else
						data = this.encapContentInfo.eContent.valueBlock.valueBeforeDecode;
				}
				else // Detached data
				{
					Iif(data.byteLength === 0) // Check that "data" already provided by function parameter
						return Promise.reject("Missed detached data input array");
				}
			}
			
			return Promise.resolve();
		});
		//endregion
		
		//region Signing TBS data on provided private key
		sequence = sequence.then(() => engine.subtle.signWithPrivateKey(data, privateKey, parameters));
		
		sequence = sequence.then(result =>
		{
			this.signerInfos[signerIndex].signature = new asn1js.OctetString({ valueHex: result });
			
			return result;
		});
		//endregion
		
		return sequence;
	}
	//**********************************************************************************
}
//**************************************************************************************