-
Notifications
You must be signed in to change notification settings - Fork 29.9k
/
pkijs-tests.ts
659 lines (550 loc) · 23.7 KB
/
pkijs-tests.ts
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
import * as asn1js from "asn1js";
import { arrayBufferToString, stringToArrayBuffer, bufferToHexCodes } from "pvutils";
import { getCrypto, getAlgorithmParameters } from "pkijs/src/common";
import Certificate from "pkijs/src/Certificate";
import CertificateRevocationList from "pkijs/src/CertificateRevocationList";
import AttributeTypeAndValue from "pkijs/src/AttributeTypeAndValue";
import Extension from "pkijs/src/Extension";
import Attribute from "pkijs/src/Attribute";
import SignedData from "pkijs/src/SignedData";
import EncapsulatedContentInfo from "pkijs/src/EncapsulatedContentInfo";
import SignerInfo from "pkijs/src/SignerInfo";
import IssuerAndSerialNumber from "pkijs/src/IssuerAndSerialNumber";
import SignedAndUnsignedAttributes from "pkijs/src/SignedAndUnsignedAttributes";
import ContentInfo from "pkijs/src/ContentInfo";
// *********************************************************************************
let cmsSignedBuffer = new ArrayBuffer(0); // ArrayBuffer with loaded or created CMS_Signed
const trustedCertificates: Certificate[] = []; // Array of root certificates from "CA Bundle"
// *********************************************************************************
// region Auxiliary functions
// *********************************************************************************
function formatPEM(pemString: string) {
const stringLength = pemString.length;
let resultString = "";
for (let i = 0, count = 0; i < stringLength; i++ , count++) {
if (count > 63) {
resultString = `${resultString}\r\n`;
count = 0;
}
resultString = resultString + pemString[i];
}
return resultString;
}
// *********************************************************************************
// endregion
// *********************************************************************************
// region Parse "CA Bundle" file
// *********************************************************************************
function parseCAbundle(buffer: ArrayBuffer) {
// region Initial variables
const base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
const startChars = "-----BEGIN CERTIFICATE-----";
const endChars = "-----END CERTIFICATE-----";
const endLineChars = "\r\n";
const view = new Uint8Array(buffer);
let waitForStart = false;
let middleStage = true;
let waitForEnd = false;
let waitForEndLine = false;
let started = false;
let certBodyEncoded = "";
// endregion
for (let i = 0; i < view.length; i++) {
if (started === true) {
if (base64Chars.indexOf(String.fromCharCode(view[i])) !== (-1))
certBodyEncoded = certBodyEncoded + String.fromCharCode(view[i]);
else {
if (String.fromCharCode(view[i]) === "-") {
// region Decoded trustedCertificates
const asn1 = asn1js.fromBER(stringToArrayBuffer(window.atob(certBodyEncoded)));
try {
trustedCertificates.push(new Certificate({ schema: asn1.result }));
}
catch (ex) {
alert("Wrong certificate format");
return;
}
// endregion
// region Set all "flag variables"
certBodyEncoded = "";
started = false;
waitForEnd = true;
// endregion
}
}
}
else {
if (waitForEndLine === true) {
if (endLineChars.indexOf(String.fromCharCode(view[i])) === (-1)) {
waitForEndLine = false;
if (waitForEnd === true) {
waitForEnd = false;
middleStage = true;
}
else {
if (waitForStart === true) {
waitForStart = false;
started = true;
certBodyEncoded = certBodyEncoded + String.fromCharCode(view[i]);
}
else
middleStage = true;
}
}
}
else {
if (middleStage === true) {
if (String.fromCharCode(view[i]) === "-") {
if (i === 0 || String.fromCharCode(view[i - 1]) === "\r" || String.fromCharCode(view[i - 1]) === "\n") {
middleStage = false;
waitForStart = true;
}
}
}
else {
if (waitForStart === true) {
if (startChars.indexOf(String.fromCharCode(view[i])) === (-1))
waitForEndLine = true;
}
else {
if (waitForEnd === true) {
if (endChars.indexOf(String.fromCharCode(view[i])) === (-1))
waitForEndLine = true;
}
}
}
}
}
}
}
// *********************************************************************************
// endregion
// *********************************************************************************
// region Parse existing CMS_Signed
// *********************************************************************************
export function parseCMSSigned() {
// region Initial check
if (cmsSignedBuffer.byteLength === 0) {
alert("Nothing to parse!");
return;
}
// endregion
// region Initial activities
document.getElementById("cms-dgst-algos").innerHTML = "";
document.getElementById("cms-certs").style.display = "none";
document.getElementById("cms-crls").style.display = "none";
const certificatesTable = document.getElementById("cms-certificates") as HTMLTableElement;
while (certificatesTable.rows.length > 1)
certificatesTable.deleteRow(certificatesTable.rows.length - 1);
const crlsTable = document.getElementById("cms-rev-lists") as HTMLTableElement;
while (crlsTable.rows.length > 1)
crlsTable.deleteRow(crlsTable.rows.length - 1);
// endregion
// region Decode existing CMS Signed Data
const asn1 = asn1js.fromBER(cmsSignedBuffer);
const cmsContentSimpl = new ContentInfo({ schema: asn1.result });
const cmsSignedSimpl = new SignedData({ schema: cmsContentSimpl.content });
// endregion
// region Put information about digest algorithms in the CMS Signed Data
const dgstmap: { [oid: string]: string } = {
"1.3.14.3.2.26": "SHA-1",
"2.16.840.1.101.3.4.2.1": "SHA-256",
"2.16.840.1.101.3.4.2.2": "SHA-384",
"2.16.840.1.101.3.4.2.3": "SHA-512"
};
for (let i = 0; i < cmsSignedSimpl.digestAlgorithms.length; i++) {
let typeval = dgstmap[cmsSignedSimpl.digestAlgorithms[i].algorithmId];
if (typeof typeval === "undefined")
typeval = cmsSignedSimpl.digestAlgorithms[i].algorithmId;
const ulrow = `<li><p><span>${typeval}</span></p></li>`;
document.getElementById("cms-dgst-algos").innerHTML = document.getElementById("cms-dgst-algos").innerHTML + ulrow;
}
// endregion
// region Put information about encapsulated content type
const contypemap: { [oid: string]: string } = {
"1.3.6.1.4.1.311.2.1.4": "Authenticode signing information",
"1.2.840.113549.1.7.1": "Data content"
};
let eContentType = contypemap[cmsSignedSimpl.encapContentInfo.eContentType];
if (typeof eContentType === "undefined")
eContentType = cmsSignedSimpl.encapContentInfo.eContentType;
document.getElementById("cms-encap-type").innerHTML = eContentType;
// endregion
// region Put information about included certificates
const rdnmap: { [oid: string]: string } = {
"2.5.4.6": "C",
"2.5.4.10": "OU",
"2.5.4.11": "O",
"2.5.4.3": "CN",
"2.5.4.7": "L",
"2.5.4.8": "S",
"2.5.4.12": "T",
"2.5.4.42": "GN",
"2.5.4.43": "I",
"2.5.4.4": "SN",
"1.2.840.113549.1.9.1": "E-mail"
};
if ("certificates" in cmsSignedSimpl) {
for (let cert of cmsSignedSimpl.certificates) {
if (cert instanceof Certificate) {
let ul = "<ul>";
for (let i = 0; i < cert.issuer.typesAndValues.length; i++) {
let typeval = rdnmap[cert.issuer.typesAndValues[i].type.toString()];
if (typeof typeval === "undefined")
typeval = cert.issuer.typesAndValues[i].type.toString();
const subjval = cert.issuer.typesAndValues[i].value.valueBlock.value;
const ulrow = `<li><p><span>${typeval}</span> ${subjval}</p></li>`;
ul = ul + ulrow;
}
ul = `${ul}</ul>`;
const row = certificatesTable.insertRow(certificatesTable.rows.length);
const cell0 = row.insertCell(0);
cell0.innerHTML = bufferToHexCodes(cert.serialNumber.valueBlock.valueHex);
const cell1 = row.insertCell(1);
cell1.innerHTML = ul;
}
}
document.getElementById("cms-certs").style.display = "block";
}
// endregion
// region Put information about included CRLs
if ("crls" in cmsSignedSimpl) {
for (let crl of cmsSignedSimpl.crls) {
if (crl instanceof CertificateRevocationList) {
let ul = "<ul>";
for (let i = 0; i < crl.issuer.typesAndValues.length; i++) {
let typeval = rdnmap[crl.issuer.typesAndValues[i].type.toString()];
if (typeof typeval === "undefined")
typeval = crl.issuer.typesAndValues[i].type.toString();
const subjval = crl.issuer.typesAndValues[i].value.valueBlock.value;
const ulrow = `<li><p><span>${typeval}</span> ${subjval}</p></li>`;
ul = ul + ulrow;
}
ul = `${ul}</ul>`;
const row = crlsTable.insertRow(certificatesTable.rows.length);
const cell = row.insertCell(0);
cell.innerHTML = ul;
}
}
document.getElementById("cms-certs").style.display = "block";
}
// endregion
// region Put information about number of signers
document.getElementById("cms-signs").innerHTML = cmsSignedSimpl.signerInfos.length.toString();
// endregion
document.getElementById("cms-signed-data-block").style.display = "block";
}
// *********************************************************************************
// endregion
// *********************************************************************************
// region Create CMS_Signed
// *********************************************************************************
export function createCMSSigned(buffer: ArrayBuffer) {
// region Initial variables
let sequence = Promise.resolve(null);
const certSimpl = new Certificate();
let cmsSignedSimpl: SignedData;
let publicKey: CryptoKey;
let privateKey: CryptoKey;
let hashAlgorithm: string;
const hashOption = (document.getElementById("hash_alg") as HTMLInputElement).value;
switch (hashOption) {
case "alg_SHA1":
hashAlgorithm = "sha-1";
break;
case "alg_SHA256":
hashAlgorithm = "sha-256";
break;
case "alg_SHA384":
hashAlgorithm = "sha-384";
break;
case "alg_SHA512":
hashAlgorithm = "sha-512";
break;
default:
}
let signatureAlgorithmName: string;
const signOption = (document.getElementById("sign_alg") as HTMLInputElement).value;
switch (signOption) {
case "alg_RSA15":
signatureAlgorithmName = "RSASSA-PKCS1-V1_5";
break;
case "alg_RSA2":
signatureAlgorithmName = "RSA-PSS";
break;
case "alg_ECDSA":
signatureAlgorithmName = "ECDSA";
break;
default:
}
// endregion
// region Get a "crypto" extension
const crypto = getCrypto();
if (typeof crypto === "undefined") {
alert("No WebCrypto extension found");
return;
}
// endregion
// region Put a static values
certSimpl.version = 2;
certSimpl.serialNumber = new asn1js.Integer({ value: 1 });
certSimpl.issuer.typesAndValues.push(new AttributeTypeAndValue({
type: "2.5.4.6", // Country name
value: new asn1js.PrintableString({ value: "RU" })
}));
certSimpl.issuer.typesAndValues.push(new AttributeTypeAndValue({
type: "2.5.4.3", // Common name
value: new asn1js.BmpString({ value: "Test" })
}));
certSimpl.subject.typesAndValues.push(new AttributeTypeAndValue({
type: "2.5.4.6", // Country name
value: new asn1js.PrintableString({ value: "RU" })
}));
certSimpl.subject.typesAndValues.push(new AttributeTypeAndValue({
type: "2.5.4.3", // Common name
value: new asn1js.BmpString({ value: "Test" })
}));
certSimpl.notBefore.value = new Date(2016, 1, 1);
certSimpl.notAfter.value = new Date(2019, 1, 1);
certSimpl.extensions = []; // Extensions are not a part of certificate by default, it's an optional array
// region "KeyUsage" extension
const bitArray = new ArrayBuffer(1);
const bitView = new Uint8Array(bitArray);
bitView[0] = bitView[0] | 0x02; // Key usage "cRLSign" flag
// bitView[0] = bitView[0] | 0x04; // Key usage "keyCertSign" flag
const keyUsage = new asn1js.BitString({ valueHex: bitArray });
certSimpl.extensions.push(new Extension({
extnID: "2.5.29.15",
critical: false,
extnValue: keyUsage.toBER(false),
parsedValue: keyUsage // Parsed value for well-known extensions
}));
// endregion
// endregion
// region Create a new key pair
sequence = sequence.then(
() => {
// region Get default algorithm parameters for key generation
const algorithm = getAlgorithmParameters(signatureAlgorithmName, "generatekey");
if ("hash" in algorithm.algorithm)
(algorithm.algorithm as any).hash.name = hashAlgorithm;
// endregion
return crypto.generateKey(algorithm.algorithm as any, true, algorithm.usages);
}
);
// endregion
// region Store new key in an interim variables
sequence = sequence.then(
(keyPair: CryptoKeyPair) => {
publicKey = keyPair.publicKey;
privateKey = keyPair.privateKey;
},
(error: Error) => alert(`Error during key generation: ${error}`)
);
// endregion
// region Exporting public key into "subjectPublicKeyInfo" value of certificate
sequence = sequence.then(
() => certSimpl.subjectPublicKeyInfo.importKey(publicKey)
);
// endregion
// region Signing final certificate
sequence = sequence.then(
() => certSimpl.sign(privateKey, hashAlgorithm),
error => alert(`Error during exporting public key: ${error}`)
);
// endregion
// region Encode and store certificate
sequence = sequence.then(
() => {
const certSimplEncoded = certSimpl.toSchema(true).toBER(false);
const certSimplString = String.fromCharCode.apply(null, new Uint8Array(certSimplEncoded));
let resultString = "-----BEGIN CERTIFICATE-----\r\n";
resultString = resultString + formatPEM(window.btoa(certSimplString));
resultString = `${resultString}\r\n-----END CERTIFICATE-----\r\n`;
document.getElementById("new_signed_data").innerHTML = resultString;
alert("Certificate created successfully!");
},
error => alert(`Error during signing: ${error}`)
);
// endregion
// region Exporting private key
sequence = sequence.then(
() => crypto.exportKey("pkcs8", privateKey)
);
// endregion
// region Store exported key on Web page
sequence = sequence.then(
result => {
const privateKeyString = String.fromCharCode.apply(null, new Uint8Array(result));
let resultString = document.getElementById("new_signed_data").innerHTML;
resultString = `${resultString}\r\n-----BEGIN PRIVATE KEY-----\r\n`;
resultString = resultString + formatPEM(window.btoa(privateKeyString));
resultString = `${resultString}\r\n-----END PRIVATE KEY-----\r\n`;
document.getElementById("new_signed_data").innerHTML = resultString;
alert("Private key exported successfully!");
},
error => alert(`Error during exporting of private key: ${error}`)
);
// endregion
// region Check if user wants us to include signed extensions
if ((document.getElementById("add_ext") as HTMLInputElement).checked) {
// region Create a message digest
sequence = sequence.then(
() => crypto.digest({ name: hashAlgorithm }, new Uint8Array(buffer))
);
// endregion
// region Combine all signed extensions
sequence = sequence.then(
result => {
const signedAttr: Attribute[] = [];
signedAttr.push(new Attribute({
type: "1.2.840.113549.1.9.3",
values: [
new asn1js.ObjectIdentifier({ value: "1.2.840.113549.1.7.1" })
]
})); // contentType
signedAttr.push(new Attribute({
type: "1.2.840.113549.1.9.5",
values: [
new asn1js.UTCTime({ valueDate: new Date() })
]
})); // signingTime
signedAttr.push(new Attribute({
type: "1.2.840.113549.1.9.4",
values: [
new asn1js.OctetString({ valueHex: result })
]
})); // messageDigest
return signedAttr;
}
);
// endregion
}
// endregion
// region Initialize CMS Signed Data structures and sign it
sequence = sequence.then(
result => {
cmsSignedSimpl = new SignedData({
version: 1,
encapContentInfo: new EncapsulatedContentInfo({
eContentType: "1.2.840.113549.1.7.1" // "data" content type
}),
signerInfos: [
new SignerInfo({
version: 1,
sid: new IssuerAndSerialNumber({
issuer: certSimpl.issuer,
serialNumber: certSimpl.serialNumber
})
})
],
certificates: [certSimpl]
});
if ((document.getElementById("add_ext") as HTMLInputElement).checked) {
cmsSignedSimpl.signerInfos[0].signedAttrs = new SignedAndUnsignedAttributes({
type: 0,
attributes: result
});
}
if ((document.getElementById("detached_signature") as HTMLInputElement).checked === false) {
const contentInfo = new EncapsulatedContentInfo({
eContent: new asn1js.OctetString({ valueHex: buffer })
});
cmsSignedSimpl.encapContentInfo.eContent = contentInfo.eContent;
return cmsSignedSimpl.sign(privateKey, 0, hashAlgorithm);
}
return cmsSignedSimpl.sign(privateKey, 0, hashAlgorithm, buffer);
}
);
// endregion
// region Create final result
sequence.then(
() => {
const cmsSignedSchema = cmsSignedSimpl.toSchema(true);
const cmsContentSimp = new ContentInfo({
contentType: "1.2.840.113549.1.7.2",
content: cmsSignedSchema
});
const _cmsSignedSchema = cmsContentSimp.toSchema();
// region Make length of some elements in "indefinite form"
_cmsSignedSchema.lenBlock.isIndefiniteForm = true;
const block1 = _cmsSignedSchema.valueBlock.value[1];
block1.lenBlock.isIndefiniteForm = true;
const block2 = block1.valueBlock.value[0];
block2.lenBlock.isIndefiniteForm = true;
if ((document.getElementById("detached_signature") as HTMLInputElement).checked === false) {
const block3 = block2.valueBlock.value[2];
block3.lenBlock.isIndefiniteForm = true;
block3.valueBlock.value[1].lenBlock.isIndefiniteForm = true;
block3.valueBlock.value[1].valueBlock.value[0].lenBlock.isIndefiniteForm = true;
}
// endregion
cmsSignedBuffer = _cmsSignedSchema.toBER(false);
// region Convert ArrayBuffer to String
let signedDataString = "";
const view = new Uint8Array(cmsSignedBuffer);
for (let i = 0; i < view.length; i++)
signedDataString = signedDataString + String.fromCharCode(view[i]);
// endregion
let resultString = document.getElementById("new_signed_data").innerHTML;
resultString = `${resultString}\r\n-----BEGIN CMS-----\r\n`;
resultString = resultString + formatPEM(window.btoa(signedDataString));
resultString = `${resultString}\r\n-----END CMS-----\r\n\r\n`;
document.getElementById("new_signed_data").innerHTML = resultString;
parseCMSSigned();
alert("CMS Signed Data created successfully!");
},
error =>
alert(`Erorr during signing of CMS Signed Data: ${error}`)
);
// endregion
}
// *********************************************************************************
// endregion
// *********************************************************************************
// region Verify existing CMS_Signed
// *********************************************************************************
function verifyCMSSigned() {
// region Initial check
if (cmsSignedBuffer.byteLength === 0) {
alert("Nothing to verify!");
return;
}
// endregion
// region Decode existing CMS_Signed
const asn1 = asn1js.fromBER(cmsSignedBuffer);
const cmsContentSimpl = new ContentInfo({ schema: asn1.result });
const cmsSignedSimpl = new SignedData({ schema: cmsContentSimpl.content });
// endregion
// region Verify CMS_Signed
cmsSignedSimpl.verify({ signer: 0, trustedCerts: trustedCertificates }).
then(
result => alert(`Verification result: ${result}`),
error => alert(`Error during verification: ${error}`)
);
// endregion
}
function handleFileBrowse(evt: Event) {
const tempReader = new FileReader();
const currentFiles = (evt.target as any).files;
tempReader.onload =
event => createCMSSigned((event.target as any).result);
tempReader.readAsArrayBuffer(currentFiles[0]);
}
function handleParsingFile(evt: Event) {
const tempReader = new FileReader();
const currentFiles = (evt.target as any).files;
tempReader.onload =
event => {
cmsSignedBuffer = (event.target as any).result;
parseCMSSigned();
};
tempReader.readAsArrayBuffer(currentFiles[0]);
}
function handleCABundle(evt: Event) {
const tempReader = new FileReader();
const currentFiles = (evt.target as any).files;
tempReader.onload =
event => parseCAbundle((event.target as any).result);
tempReader.readAsArrayBuffer(currentFiles[0]);
}