forked from disaipe/crypto-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcryptohelper.js
364 lines (316 loc) · 8.85 KB
/
cryptohelper.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
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
window.CryptoHelper = function() {
const self = this;
const crypto = cadesplugin;
const SIGN_DETACHED = true;
const VERBOSE = true;
self.isReady = false;
/**
* Handle plugin init event
* @returns {Promise}
*/
this.init = () => {
return new Promise((resolve, reject) => {
crypto.then(async () => {
if (await check()) {
resolve();
} else {
reject(new Error('Cadesplugin not activated'));
}
}).catch((e) => {
reject(e);
});
});
};
/**
* Get valid certificates from store
* @param {Number} location location of the store to be opened
* @param {String} storeName a string that contains the name of the system certificate store to be opened
* @param {Number} mode open mode of the store
* @returns {Array<Certificate>}
*/
this.getCertificates = (location, storeName, mode) => {
const _location = location || crypto.CAPICOM_CURRENT_USER_STORE;
const _storeName = storeName || crypto.CAPICOM_MY_STORE;
const _mode = mode || crypto.CAPICOM_STORE_OPEN_MAXIMUM_ALLOWED;
return new Promise(async (resolve) => {
const store = await createStore();
store.Open(_location, _storeName, _mode);
let certs = await store.Certificates;
certs = await certs.Find(crypto.CAPICOM_CERTIFICATE_FIND_TIME_VALID);
const certificates = [];
for (let i = 1; i <= await certs.Count; i += 1) {
const cert = await certs.Item(i);
certificates.push(await parseCertificate(cert));
}
store.Close();
resolve(certificates);
});
};
/**
* Sign various data type by chosen certificate
* @param {Certificate} certificate
* @param {String|File|DomElement} data
* @returns {String}
*/
this.sign = (certificate, data) => {
if (data instanceof File) {
log('[Crypto] Signing File');
return this.signFile(certificate, data);
} else if (data instanceof FileList) {
log('[Crypto] Signing FileList');
return this.signFileList(certificate, data);
} else if (data instanceof HTMLInputElement && data.type === 'file') {
log('[Crypto] Signing file input');
return this.signFileList(certificate, data.files);
} else {
log('[Crypto] Signing string');
return this.signString(certificate, data);
}
};
/**
* Sign string data by chosen certificate
* @param {Certificate} certificate
* @param {String} data
* @param {Boolean} toBase64
* @returns {String}
*/
this.signString = (certificate, data, toBase64 = true) => {
return new Promise(async (resolve, reject) => {
const signer = await createSigner();
const signedData = await createSignedData();
await signer.propset_Certificate(certificate.$original || certificate);
await signer.propset_Options(crypto.CAPICOM_CERTIFICATE_INCLUDE_WHOLE_CHAIN)
await signedData.propset_ContentEncoding(crypto.CADESCOM_BASE64_TO_BINARY);
await signedData.propset_Content(toBase64 ? btoa(data) : data);
try {
const signedMessage = await signedData.SignCades(signer, crypto.CADESCOM_CADES_BES, SIGN_DETACHED);
resolve(signedMessage);
} catch (e) {
console.error('[Crypto] Sign failed', e);
reject(false);
}
});
};
/**
* Sign file by chosen certificate
* @param {Certificate} certificate
* @param {File} file
* @returns {String}
*/
this.signFile = (certificate, file) => {
return new Promise((resolve) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => {
const header = ';base64,';
const fileData = reader.result;
const fileContent = fileData.substr(fileData.indexOf(header) + header.length);
resolve(this.signString(certificate, fileContent, false));
};
});
};
/**
* Sign file list by chosen certificate
* @param {Certificate} certificate
* @param {FileList} fileList
* @returns {Array<String>}
*/
this.signFileList = (certificate, fileList) => {
const promises = Array.from(fileList).map((file) => {
return this.signFile(certificate, file);
});
return Promise.all(promises);
};
/**
* Verify data sign
* @param {String} data
* @param {String} sign
* @param {Boolean} toBase64
* @returns {Array<Object>}
*/
this.verify = (data, sign, toBase64 = false) => {
return new Promise(async (resolve) => {
const signedData = await createSignedData();
signedData.propset_ContentEncoding(crypto.CADESCOM_BASE64_TO_BINARY);
signedData.propset_Content(toBase64 ? btoa(data) : data);
try {
await signedData.VerifyCades(sign, crypto.CADESCOM_CADES_BES, true);
const signs = await signInfo(signedData);
resolve(signs);
} catch (e) {
console.error('[Crypto] Verify failed', e);
resolve(false);
}
});
};
/**
* Get installed CSP version
*/
this.checkCSP = () => {
return new Promise(async (resolve, reject) => {
try {
let oAbout = await crypto.CreateObjectAsync('CAdESCOM.About');
let oVersion = await oAbout.CSPVersion();
const about = {
version: await oVersion.toString(),
name: await oAbout.CSPName()
};
resolve(about);
} catch (e) {
reject();
}
});
};
/**
* Check cadesplugin is ready
* (try create Store object)
*/
async function check() {
try {
await createStore();
return self.isReady = true;
} catch (e) {
return self.isReady = false;
}
}
/**
* Create new CAdESCOM.Store instance
* View more at https://cpdn.cryptopro.ru/content/cades/class_store.html
* @returns {CAdESCOM.Store}
*/
async function createStore() {
return await crypto.CreateObjectAsync('CAdESCOM.Store');
}
/**
* Create new CAdESCOM.CPSigner instance
* View more at https://cpdn.cryptopro.ru/content/cades/class_c_ad_e_s_c_o_m_1_1_c_p_signer.html
* @returns {CAdESCOM.CPSigner}
*/
async function createSigner() {
return await crypto.CreateObjectAsync('CAdESCOM.CPSigner');
}
/**
* Create new CAdESCOM.CadesSignedData instance
* View more at https://cpdn.cryptopro.ru/content/cades/class_c_ad_e_s_c_o_m_1_1_cades_signed_data.html
* @returns {CAdESCOM.CadesSignedData}
*/
async function createSignedData() {
return await crypto.CreateObjectAsync('CAdESCOM.CadesSignedData');
}
/**
* Extract certificate subject info
* @param {Certificate} certificate
* @returns {Object}
*/
async function extractSubjectName(certificate) {
var subject = await certificate.SubjectName;
return parseDN(subject);
}
/**
* Extract certificate issuer info
* @param {Certificate} certificate
* @return {Object}
*/
async function extractIssuerName(certificate) {
var issuer = await certificate.IssuerName;
return parseDN(issuer);
}
/**
* Extract certificate info
* @param {Certificate} certificate
* @returns {Object}
*/
async function parseCertificate(certificate) {
const isValid = await certificate.IsValid();
return {
$original: certificate,
subject: await extractSubjectName(certificate),
issuer: await extractIssuerName(certificate),
version: await certificate.Version,
serialNumber: await certificate.SerialNumber,
thumbprint: await certificate.Thumbprint,
validFrom: await certificate.ValidFromDate,
validTo: await certificate.ValidToDate,
hasPrivate: await certificate.HasPrivateKey(),
isValid: await isValid.Result
}
}
/**
* Extract signers from SignedData object
* @param {CAdESCOM.CadesSignedData} signedData
* @returns {Array<Object>}
*/
async function signInfo(signedData) {
const signers = await signedData.Signers;
const count = await signers.Count;
const signs = [];
for (let i = 1; i <= count; i += 1) {
const signer = await signers.Item(i);
const certificate = await signer.Certificate;
const sign = {
ts: await signer.SigningTime,
cert: await parseCertificate(certificate)
};
signs.push(sign);
}
return signs;
}
/**
* Parse DN string to object
* @param {String} dn
* @returns {Object}
*/
function parseDN(dn) {
const tags = {
'CN': 'name',
'S': 'region',
'STREET': 'address',
'O': 'company',
'OU': 'postType',
'T': 'post',
'ОГРН': 'ogrn',
'СНИЛС': 'snils',
'ИНН': 'inn',
'E': 'email',
'L': 'city'
};
let buf = dn;
const fields = [...buf.matchAll(/(\w+)=/g)].reduceRight((acc, cur) => {
let v = buf.substring(cur.index);
v = v.replace(cur[0], '');
v = v.replace(/\s*"?(.*?)"?,?\s?$/, '$1');
v = v.replace(/""/g, '"');
const tag = cur[1];
if (tags[tag]) {
acc[tags[tag]] = v;
}
buf = buf.substring(0, cur.index);
return acc;
}, {});
return fields;
}
/**
* Write verbose message to console
* @param {...any} args
*/
function log(...args) {
if (VERBOSE) {
console.log(...args);
}
}
}
/**
* String.matchAll polyfill
*/
if (!String.prototype.matchAll) {
String.prototype.matchAll = function*(regex) {
function ensureFlag(flags, flag) {
return flags.includes(flag) ? flags : (flags + flag);
}
const localRegex = new RegExp(regex, ensureFlag(regex.flags, 'g'));
let match;
while (match = localRegex.exec(this)) {
yield match;
}
}
}