/
es6.js
258 lines (228 loc) · 7.59 KB
/
es6.js
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
/* eslint-disable no-undef,no-unreachable */
import * as asn1js from "asn1js";
import { getCrypto, getAlgorithmParameters, setEngine } from "../../src/common";
import { arrayBufferToString, toBase64 } from "pvutils";
import Certificate from "../../src/Certificate";
import AttributeTypeAndValue from "../../src/AttributeTypeAndValue";
import Extension from "../../src/Extension";
import SignedData from "../../src/SignedData";
import EncapsulatedContentInfo from "../../src/EncapsulatedContentInfo";
import ContentInfo from "../../src/ContentInfo";
//<nodewebcryptoossl>
//*********************************************************************************
let cmsSignedBuffer = new ArrayBuffer(0);
let hashAlg = "SHA-1";
let signAlg = "RSASSA-PKCS1-v1_5";
//*********************************************************************************
//region Auxiliary functions
//*********************************************************************************
function formatPEM(pemString)
{
/// <summary>Format string in order to have each line with length equal to 63</summary>
/// <param name="pemString" type="String">String to format</param>
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 Create P7B Data
//*********************************************************************************
function createP7BInternal()
{
//region Initial variables
let sequence = Promise.resolve();
const certSimpl = new Certificate();
let publicKey;
let privateKey;
//endregion
//region Get a "crypto" extension
const crypto = getCrypto();
if(typeof crypto === "undefined")
return Promise.reject("No WebCrypto extension found");
//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(2013, 0, 1);
certSimpl.notAfter.value = new Date(2016, 0, 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] |= 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(signAlg, "generatekey");
if("hash" in algorithm.algorithm)
algorithm.algorithm.hash.name = hashAlg;
//endregion
return crypto.generateKey(algorithm.algorithm, true, algorithm.usages);
});
//endregion
//region Store new key in an interim variables
sequence = sequence.then((keyPair) =>
{
publicKey = keyPair.publicKey;
privateKey = keyPair.privateKey;
});
//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, hashAlg));
//endregion
//region Encode final ContentInfo
sequence = sequence.then(() =>
{
const cmsContentSimp = new ContentInfo({
contentType: "1.2.840.113549.1.7.2",
content: (new SignedData({
version: 1,
encapContentInfo: new EncapsulatedContentInfo({
eContentType: "1.2.840.113549.1.7.1" // "data" content type
}),
certificates: [
certSimpl,
certSimpl,
certSimpl
] // Put 3 copies of the same X.509 certificate
})).toSchema(true)
});
cmsSignedBuffer = cmsContentSimp.toSchema().toBER(false);
});
//endregion
return sequence;
}
//*********************************************************************************
function createP7B()
{
return Promise.resolve().then(() => createP7BInternal()).then(() =>
{
// noinspection InnerHTMLJS
let resultString = "\r\n-----BEGIN CMS-----\r\n";
resultString = `${resultString}${formatPEM(toBase64(arrayBufferToString(cmsSignedBuffer)))}`;
resultString = `${resultString}\r\n-----END CMS-----\r\n\r\n`;
// noinspection InnerHTMLJS
document.getElementById("newSignedData").innerHTML = resultString;
});
}
//*********************************************************************************
//endregion
//*********************************************************************************
function handleHashAlgOnChange()
{
const hashOption = document.getElementById("hashAlg").value;
switch(hashOption)
{
case "algSHA1":
hashAlg = "sha-1";
break;
case "algSHA256":
hashAlg = "sha-256";
break;
case "algSHA384":
hashAlg = "sha-384";
break;
case "algSHA512":
hashAlg = "sha-512";
break;
default:
}
}
//*********************************************************************************
function handleSignAlgOnChange()
{
const signOption = document.getElementById("signAlg").value;
switch(signOption)
{
case "algRSA15":
signAlg = "RSASSA-PKCS1-V1_5";
break;
case "algRSA2":
signAlg = "RSA-PSS";
break;
case "algECDSA":
signAlg = "ECDSA";
break;
default:
}
}
//*********************************************************************************
context("Hack for Rollup.js", () =>
{
return;
// noinspection UnreachableCodeJS
createP7B();
handleHashAlgOnChange();
handleSignAlgOnChange();
setEngine();
});
//*********************************************************************************
context("P7B Simple Example", () =>
{
//region Initial variables
const hashAlgs = ["SHA-1", "SHA-256", "SHA-384", "SHA-512"];
const signAlgs = ["RSASSA-PKCS1-V1_5", "ECDSA", "RSA-PSS"];
//endregion
signAlgs.forEach(_signAlg =>
{
hashAlgs.forEach(_hashAlg =>
{
const testName = `${_hashAlg} + ${_signAlg}`;
it(testName, () =>
{
hashAlg = _hashAlg;
signAlg = _signAlg;
return createP7BInternal().then(() =>
{
const asn1 = asn1js.fromBER(cmsSignedBuffer);
const contentInfo = new ContentInfo({ schema: asn1.result });
assert.equal(contentInfo.contentType, "1.2.840.113549.1.7.2", "Content Type ID must be '1.2.840.113549.1.7.2'");
const signedData = new SignedData({ schema: contentInfo.content });
assert.equal(signedData.certificates.length, 3, "SignedData must contains 3 certificates");
});
});
});
});
});
//*********************************************************************************