forked from jjzazuet/crypto
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gostKeys.js
2503 lines (2413 loc) · 110 KB
/
gostKeys.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
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
/**
* @file Key and Certificate Store methods
* @version 1.76
* @copyright 2014-2016, Rudolf Nickolaev. All rights reserved.
*/
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
(function (root, factory) {
/*
* Module imports and exports
*
*/ // <editor-fold defaultstate="collapsed">
if (typeof define === 'function' && define.amd) {
define(['gostCrypto', 'gostASN1', 'gostCert', 'gostCMS'], factory);
} else if (typeof exports === 'object') {
module.exports = factory(require('./gostCrypto'), require('./gostASN1'), require('./gostCert'), require('./gostCMS'));
} else {
root.GostKeys = factory(root.gostCrypto, root.GostASN1, root.GostCert, root.GostCMS);
}
// </editor-fold>
}(this, function (gostCrypto) {
/*
* Common tools and methods
*/ // <editor-fold defaultstate="collapsed">
var root = this;
var Promise = root.Promise;
var Object = root.Object;
var CryptoOperationData = root.ArrayBuffer;
var Date = root.Date;
var subtle = gostCrypto.subtle;
var asn1 = gostCrypto.asn1;
var coding = gostCrypto.coding;
var providers = gostCrypto.security.providers;
var cert = gostCrypto.cert;
var cms = gostCrypto.cms;
// Expand javascript object
function expand() {
var r = {};
for (var i = 0, n = arguments.length; i < n; i++) {
var item = arguments[i];
if (typeof item === 'object')
for (var name in item)
if (item.hasOwnProperty(name))
r[name] = item[name];
}
return r;
}
function defineProperty(object, name, descriptor, enumerable) {
if (typeof descriptor !== 'object')
descriptor = {value: descriptor};
if (enumerable !== undefined)
descriptor.enumerable = enumerable;
Object.defineProperty(object, name, descriptor);
}
function defineProperties(object, properties, enumerable) {
for (var name in properties)
defineProperty(object, name, properties[name], enumerable);
}
// Extend javascript class
function extend(Super, Class, propertiesObject, propertiesClass) {
// If constructor not defined
if (typeof Class !== 'function') {
propertiesClass = propertiesObject;
propertiesObject = Class;
Class = function () {
Super.apply(this, arguments);
};
}
// Create prototype properties
Class.prototype = Object.create(Super.prototype, {
constructor: {
value: Class
},
superclass: {
value: Super.prototype
}
});
if (propertiesObject)
defineProperties(Class.prototype, propertiesObject, true);
// Inherites super class properties
if (Super !== Object)
for (var name in Super)
Class[name] = Super[name];
Class.super = Super;
if (propertiesClass)
defineProperties(Class, propertiesClass, true);
return Class;
}
// Get random values
function getSeed(length) {
var seed = new Uint8Array(length);
gostCrypto.getRandomValues(seed);
return seed.buffer;
}
// Self resolver
function call(callback) {
try {
callback();
} catch (e) {
}
}
// Get buffer
function buffer(d) {
if (d instanceof CryptoOperationData)
return d;
else if (d && d.buffer && d.buffer instanceof CryptoOperationData)
return d.byteOffset === 0 && d.byteLength === d.buffer.byteLength ?
d.buffer : new Uint8Array(new Uint8Array(d, d.byteOffset, d.byteLength)).buffer;
else
throw new DataError('CryptoOperationData required');
}
// Today date + n days with time
function now(n) {
var date = new Date();
if (n)
date.setDate(date.getDate() + n);
return date;
}
// Today date + n days
function today(n) {
var date = now(n);
date.setHours(0, 0, 0, 0);
return date;
}
// Check the buffers to equal
function equalBuffers(r1, r2) {
var s1 = new Uint8Array(r1),
s2 = new Uint8Array(r2);
if (s1.length !== s2.length)
return false;
for (var i = 0, n = s1.length; i < n; i++)
if (s1[i] !== s2[i])
return false;
return true;
}
// Generate new alias
function generateUUID() {
var r = new Uint8Array(getSeed(16)), s = '';
for (var i = 0; i < 16; i++)
s += ('00' + r[i].toString(16)).slice(-2);
return s.substr(0, 8) + '-' + s.substr(8, 4) + '-4' + s.substr(13, 3) +
'-9' + s.substr(17, 3) + '-' + s.substr(20, 12);
}
// Return get32 from buffer
function get32(buffer, offset) {
var r = new Uint8Array(buffer, offset, 4);
return (r[3] << 24) | (r[2] << 16) | (r[1] << 8) | r[0];
}
function set32(buffer, offset, int) {
var r = new Uint8Array(buffer, offset, 4);
r[3] = int >>> 24;
r[2] = int >>> 16 & 0xff;
r[1] = int >>> 8 & 0xff;
r[0] = int & 0xff;
return r;
}
// Salt size
function saltSize(algorithm) {
switch (algorithm.id) {
case 'pbeWithSHAAnd40BitRC2-CBC':
case 'pbeWithSHAAnd128BitRC2-CBC':
return 8;
case 'pbeUnknownGost':
return 16;
case 'sha1':
return 20;
default:
return 32;
}
}
// Password to bytes
function passwordData(derivation, password) {
if (!password)
return new CryptoOperationData(0);
if (derivation.name.indexOf('CPKDF') >= 0) {
// CryptoPro store password
var r = [];
for (var i = 0; i < password.length; i++) {
var c = password.charCodeAt(i);
r.push(c & 0xff);
r.push(c >>> 8 & 0xff);
r.push(0);
r.push(0);
}
return new Uint8Array(r).buffer;
} else if (derivation.name.indexOf('PFXKDF') >= 0)
// PKCS#12 unicode password
return coding.Chars.decode(password + '\0', 'unicode');
else
// PKCS#5 password mode
return coding.Chars.decode(password, 'utf8');
}
// </editor-fold>
/**
* Key and Certificate Store methods
*
* @class GostKeys
*/
function GostKeys() {
}
/**
* Key templates
* <ul>
* <li>providerName - provider name for key encryption, default 'CP-01'</li>
* <li>days - validity of the key in days, default 7305</li>
* </ul>
*
* @memberOf GostKeys
* @instance
*/
var options = {// <editor-fold defaultstate="collapsed">
providerName: 'CP-01',
days: 7305 // </editor-fold>
};
GostKeys.prototype.options = options;
/**
* A class for private keys in PKCS #8 format
*
* @class GostKeys.PKCS8
* @extends GostASN1.PrivateKeyInfo
* @param {(FormatedData|GostASN1.PrivateKeyInfo)} keyInfo
*/
function PKCS8(keyInfo) {
asn1.PrivateKeyInfo.call(this, keyInfo);
}
extend(asn1.PrivateKeyInfo, PKCS8, {
/**
* Get the private key
*
* @memberOf GostKeys.PKCS8
* @instance
* @returns {Promise} Promise to return the {@link Key}
*/
getPrivateKey: function () // <editor-fold defaultstate="collapsed">
{
var keyUsages = (this.privateKeyAlgorithm.id === 'rsaEncryption') ? ['sign'] :
['sign', 'deriveKey', 'deriveBits'];
return subtle.importKey('pkcs8', this.encode(), this.privateKeyAlgorithm, 'true', keyUsages);
}, // </editor-fold>
/**
* Set the private key
*
* @memberOf GostKeys.PKCS8
* @instance
* @param {Key} privateKey The Private Key
* @returns {Promise} Promise to return the self object after set the key
*/
setPrivateKey: function (privateKey) // <editor-fold defaultstate="collapsed">
{
var self = this;
return subtle.exportKey('pkcs8', privateKey).then(function (keyInfo) {
asn1.PrivateKeyInfo.call(self, keyInfo);
return self;
});
}, // </editor-fold>
/**
* Generate private key and return certification request
*
* @memberOf GostKeys.PKCS8
* @instance
* @param {(FormatedData|GostASN1.CertificationRequest)} req The request templates
* @param {(AlgorithmIdentifier|string)} keyAlgorithm The name of provider or algorithm identifier
* @returns {Promise} Promise to return the {@link GostCert.Request} after key generation
*/
generate: function (req, keyAlgorithm) // <editor-fold defaultstate="collapsed">
{
var self = this;
return new Promise(call).then(function () {
if (!(req instanceof cert.Request))
req = new cert.Request(req);
// Generate request
return req.generate(keyAlgorithm);
}).then(function (key) {
asn1.PrivateKeyInfo.call(self, key);
;
return req;
});
} // </editor-fold>
});
/**
* A class for private keys in PKCS #8 format
*
* @memberOf GostKeys
* @type GostKeys.PKCS8
*/
GostKeys.prototype.PKCS8 = PKCS8;
/**
* A class for PKCS #5 and PKCS #12 password-encrypted private keys in PKCS #8 format
*
* @class GostKeys.PKCS8Encrypted
* @extends GostASN1.EncryptedPrivateKeyInfo
* @param {(FormatedData|GostASN1.EncryptedPrivateKeyInfo)} encryptedKey
*/
function PKCS8Encrypted(encryptedKey) {
asn1.EncryptedPrivateKeyInfo.call(this, encryptedKey);
}
extend(asn1.EncryptedPrivateKeyInfo, PKCS8Encrypted, {
/**
* Get the private key info
*
* @memberOf GostKeys.PKCS8Encrypted
* @instance
* @param {(Key|CryptoOperationData|string)} keyPassword The secret key or password for decryption
* @returns {Promise} Promise to return decrypted {@link GostKeys.PKCS8}
*/
getKey: function (keyPassword) // <editor-fold defaultstate="collapsed">
{
var self = this, engine;
return new Promise(call).then(function () {
engine = new cms.EncryptedDataContentInfo({
contentType: 'encryptedData',
version: 0,
encryptedContentInfo: {
contentType: 'data',
contentEncryptionAlgorithm: self.encryptionAlgorithm,
encryptedContent: self.encryptedData
}
});
return engine.getEnclosed(keyPassword);
}).then(function (contentInfo) {
// Create key object
return PKCS8.decode(contentInfo.content);
});
}, // </editor-fold>
/**
* Get the private key
*
* @memberOf GostKeys.PKCS8Encrypted
* @instance
* @param {(Key|CryptoOperationData|string)} keyPassword The secret key or password for decryption
* @returns {Promise} Promise to return decrypted {@link Key}
*/
getPrivateKey: function (keyPassword) // <editor-fold defaultstate="collapsed">
{
return this.getKey(keyPassword).then(function (keyInfo) {
return keyInfo.getPrivateKey();
});
}, // </editor-fold>
/**
* Sets and encrypt the private key info
*
* @memberOf GostKeys.PKCS8Encrypted
* @instance
* @param {(FormatedData|GostKeys.PKCS8)} keyInfo The private key info
* @param {(Key|CryptoOperationData|string)} keyPassword The secret key or password for encryption
* @param {(AlgorithmIdentifier|string)} encryptionAlgorithm The encryption algorithm or provider name
* @returns {Promise} Promise to return self object after set key
*/
setKey: function (keyInfo, keyPassword, encryptionAlgorithm) // <editor-fold defaultstate="collapsed">
{
var self = this, engine;
return new Promise(call).then(function () {
keyInfo = new PKCS8(keyInfo);
engine = new cms.EncryptedDataContentInfo();
return engine.encloseContent(keyInfo.encode(), keyPassword, encryptionAlgorithm || options.providerName);
}).then(function () {
self.encryptionAlgorithm = engine.encryptedContentInfo.contentEncryptionAlgorithm;
self.encryptedData = engine.encryptedContentInfo.encryptedContent;
return self;
});
}, // </editor-fold>
/**
* Set the private key
*
* @memberOf GostKeys.PKCS8Encrypted
* @instance
* @param {Key} privateKey The private key
* @param {(Key|CryptoOperationData|string)} keyPassword The secret key or password for decryption
* @param {(AlgorithmIdentifier|string)} encryptionAlgorithm The encryption algorithm or provider name
* @returns {Promise} Promise to return self object after set key
*/
setPrivateKey: function (privateKey, keyPassword, encryptionAlgorithm) // <editor-fold defaultstate="collapsed">
{
var self = this;
return new PKCS8().setPrivateKey(privateKey).then(function (keyInfo) {
return self.setKey(keyInfo, keyPassword, encryptionAlgorithm);
});
}, // </editor-fold>
/**
* Generate private key and return certification request
*
* @memberOf GostKeys.PKCS8Encrypted
* @instance
* @param {(FormatedData|GostASN1.CertificationRequest)} req The request templates
* @param {(Key|CryptoOperationData|string)} keyPassword The secret key or password for decryption
* @param {(AlgorithmIdentifier|string)} keyAlgorithm The name of provider or algorithm
* @param {(AlgorithmIdentifier|string)} encryptionAlgorithm The encryption algorithm or provider name
* @returns {Promise} Promise to return {@link GostCert.Request}
*/
generate: function (req, keyPassword, keyAlgorithm, encryptionAlgorithm) // <editor-fold defaultstate="collapsed">
{
var self = this;
return new Promise(call).then(function () {
if (!(req instanceof cert.Request))
req = new cert.Request(req);
// Generate request
return req.generate(keyAlgorithm);
}).then(function (key) {
return self.setKey(key, keyPassword, encryptionAlgorithm);
}).then(function () {
return req;
});
} // </editor-fold>
});
/**
* A class for PKCS #5 and PKCS #12 password-encrypted private keys in PKCS #8 format
*
* @memberOf GostKeys
* @type GostKeys.PKCS8Encrypted
*/
GostKeys.prototype.PKCS8Encrypted = PKCS8Encrypted;
/**
* A class for password-encrypted private keys in SignalCom container<br><br>
*
* The container file list:
* <ul>
* <li>mk.db3 - master key data</li>
* <li>masks.db3 - encrypted or decrypted masks</li>
* <li>kek.opq - wrapped key encryption key</li>
* <li>rand.opq - wrapped random data</li>
* </ul>
*
* @class GostKeys.SignalComKeyContainer
* @param {SignalComKeyContainer} container
*/
function SignalComKeyContainer(container) // <editor-fold defaultstate="collapsed">
{
if (container) {
var self = this;
['mk.db3', 'masks.db3', 'kek.opq', 'rand.opq'].forEach(function (name) {
self[name] = container[name];
});
}
} // </editor-fold>
extend(Object, SignalComKeyContainer, {
/**
* Get password-based encryption key
*
* @memberOf GostKeys.SignalComKeyContainer
* @instance
* @param {string} keyPassword
* @returns {Promise} Promise to return {@link Key}
*/
getEncryptionKey: function (keyPassword) // <editor-fold defaultstate="collapsed">
{
var self = this, wrapping = providers['SC-01'].wrapping,
encryption = providers['SC-01'].encryption,
derivation = providers['SC-01'].derivation,
masks = self['masks.db3'], mk = self['mk.db3'], kek = self['kek.opq'];
// Decrypt key
return new Promise(call).then(function () {
if ((!masks || !mk || !kek))
throw new Error('Not enougth key container files');
// Check for encrypted key
if (masks.byteLength > 32) {
if (keyPassword) {
// Extract password based encryption mask
return subtle.importKey('raw', coding.Chars.decode(keyPassword, 'utf8'),
derivation, false, ['deriveKey', 'deriveBits']).then(function (integrityKey) {
return subtle.deriveKey(expand(derivation,
{salt: new Uint8Array([0, 0, 0, 0, 0, 0, 0, 0])}),
integrityKey, encryption, false, ['decrypt']);
}).then(function (encryptionKey) {
var encrypted = new cms.EncryptedDataContentInfo(masks);
return encrypted.getEnclosed(encryptionKey);
}).then(function (digested) {
return digested.verify();
}).then(function (data) {
return data.content;
});
} else
throw new Error('Key password is required');
} else if (keyPassword)
throw new Error('Key password is not required');
return masks;
}).then(function (decrypedMasks) {
// Combine masks
masks = decrypedMasks;
var mkm = new Uint8Array(mk.byteLength + masks.byteLength);
mkm.set(new Uint8Array(mk), 0);
mkm.set(new Uint8Array(masks), mk.byteLength);
// Import master key
return subtle.importKey('raw', mkm.buffer, wrapping, false, ['unwrapKey']);
}).then(function (unwrappingKey) {
// Unwrap kek
return subtle.unwrapKey('raw', kek, unwrappingKey, wrapping, encryption,
false, ['wrapKey', 'unwrapKey']);
});
}, // </editor-fold>
/**
* Generate encryption key and container files
*
* @memberOf GostKeys.SignalComKeyContainer
* @instance
* @param {string} keyPassword
* @returns {Promise} Promise to return {@link Key}
*/
generateContainer: function (keyPassword) // <editor-fold defaultstate="collapsed">
{
var self = this, wrapping = providers['SC-01'].wrapping,
encryption = providers['SC-01'].encryption,
derivation = providers['SC-01'].derivation,
digest = providers['SC-01'].digest,
encryptionKey, wrappingKey;
return new Promise(call).then(function () {
// Generate wrapping key
return subtle.generateKey(wrapping, true, ['wrapKey']);
}).then(function (key) {
wrappingKey = key;
// Split masks
var len = wrappingKey.buffer.byteLength;
self['mk.db3'] = new Uint8Array(new Uint8Array(wrappingKey.buffer, 0, len - 32)).buffer;
var masks = new Uint8Array(new Uint8Array(wrappingKey.buffer, len - 32, 32)).buffer;
if (keyPassword) {
// Encrypt masks
var encrypted = new cms.EncryptedDataContentInfo(),
digested = new cms.DigestedDataContentInfo();
// Digest data
return digested.encloseContent(masks, digest).then(function () {
digested = {// Double wrapping - SignalCom mistake
contentType: 'digestedData',
content: digested.encode()
};
return subtle.importKey('raw', coding.Chars.decode(keyPassword, 'utf8'),
derivation, false, ['deriveKey', 'deriveBits']);
}).then(function (integrityKey) {
return subtle.deriveKey(expand(derivation,
{salt: new Uint8Array([0, 0, 0, 0, 0, 0, 0, 0])}),
integrityKey, encryption, false, ['encrypt']);
}).then(function (encryptionKey) {
// Encrypt data with password
return encrypted.encloseContent(digested, encryptionKey, encryption);
}).then(function () {
return encrypted.encode();
});
}
return masks;
}).then(function (masks) {
self['masks.db3'] = masks;
// Generate encryption key
return subtle.generateKey(encryption, false, ['wrapKey', 'unwrapKey']);
}).then(function (key) {
encryptionKey = key;
// Wrap encryption key
return subtle.wrapKey('raw', key, wrappingKey, wrapping);
}).then(function (data) {
self['kek.opq'] = data;
// Generate random seed
return subtle.generateKey(encryption, false, ['wrapKey', 'unwrapKey']);
}).then(function (key) {
// Wrap random seed
return subtle.wrapKey('raw', key, wrappingKey, wrapping);
}).then(function (data) {
self['rand.opq'] = data;
return encryptionKey;
});
} // </editor-fold>
});
/**
* A class for password-encrypted private keys in SignalCom container
*
* @memberOf GostKeys
* @type GostKeys.SignalComKeyContainer
*/
GostKeys.prototype.SignalComKeyContainer = SignalComKeyContainer;
/**
* A class for password-encrypted SignalCom private keys
*
* @class GostKeys.SignalComPrivateKeyInfo
* @extends GostASN1.GostWrappedPrivateKey
* @extends GostKeys.SignalComKeyContainer
* @param {GostASN1.PrivateKeyInfo} keyInfo
* @param {GostKeys.SignalComKeyContainer} container
*/
function SignalComPrivateKeyInfo(keyInfo, container) // <editor-fold defaultstate="collapsed">
{
asn1.GostWrappedPrivateKey.call(this, keyInfo);
SignalComKeyContainer.call(this, container);
} // </editor-fold>
extend(asn1.GostWrappedPrivateKey, SignalComPrivateKeyInfo, {
/**
* Get the private key info
*
* @memberOf GostKeys.SignalComPrivateKeyInfo
* @param {string} keyPassword The password for decryption
* @returns {Promise} Promise to return {@link GostKeys.PKCS8}
*/
getKey: function (keyPassword) // <editor-fold defaultstate="collapsed">
{
return this.getPrivateKey(keyPassword).then(function (privateKey) {
return new PKCS8().setPrivateKey(privateKey);
});
}, // </editor-fold>
/**
* Get the private key
*
* @memberOf GostKeys.SignalComPrivateKeyInfo
* @instance
* @param {string} keyPassword The password for decryption
* @returns {Promise} Promise to return the {@link Key}
*/
getPrivateKey: function (keyPassword) // <editor-fold defaultstate="collapsed">
{
var self = this, wrapping = providers['SC-01'].wrapping,
publicKeyData;
// Decrypt key
return new Promise(call).then(function () {
// Get password key
return self.getEncryptionKey(keyPassword, true);
}).then(function (encryptionKey) {
// Unwrap private key
return subtle.unwrapKey('raw', self.privateKeyWrapped, encryptionKey, wrapping,
self.privateKeyAlgorithm, true, ['sign', 'deriveKey', 'deriveBits']);
}).then(function (privateKey) {
publicKeyData = self.attributes && self.attributes['id-sc-gostR3410-2001-publicKey'];
// Generate key pair
if (publicKeyData)
return subtle.generateKey(expand(privateKey.algorithm, {ukm: privateKey.buffer}),
privateKey.extractable, privateKey.usages);
else
return {privateKey: privateKey};
}).then(function (keyPair) {
// Compare public key
if (publicKeyData && !equalBuffers(keyPair.publicKey.buffer, publicKeyData))
throw new Error('Check public key failed');
return keyPair.privateKey;
});
}, // </editor-fold>
/**
* Sets and encrypt the private key info
*
* @memberOf GostKeys.SignalComPrivateKeyInfo
* @instance
* @param {(FormatedData|GostKeys.PKCS8)} keyInfo The private key info
* @param {string} keyPassword The password for encryption
* @returns {Promise} Promise to return self object after set the key
*/
setKey: function (keyInfo, keyPassword) // <editor-fold defaultstate="collapsed">
{
var self = this;
return new PKCS8(keyInfo).getPrivateKey().then(function (privateKey) {
return self.setPrivateKey(privateKey, keyPassword);
});
}, // </editor-fold>
/**
* Set the private key
*
* @memberOf GostKeys.SignalComPrivateKeyInfo
* @instance
* @param {Key} privateKey The private key
* @param {string} keyPassword The secret key encryption
* @returns {Promise} Promise to return self object after set the key
*/
setPrivateKey: function (privateKey, keyPassword) // <editor-fold defaultstate="collapsed">
{
var self = this, wrapping = providers['SC-01'].wrapping, wrappedData;
return new Promise(call).then(function () {
// Get or generate encryption key
return self.getEncryptionKey(keyPassword)['catch'](function () {
return self.generateContainer(keyPassword);
});
}).then(function (encryptionKey) {
// Encrypt key buffer
return subtle.wrapKey('raw', privateKey, encryptionKey, wrapping);
}).then(function (data) {
wrappedData = data;
// Generate public key
return subtle.generateKey(expand(privateKey.algorithm,
{ukm: privateKey.buffer}), true, ['sign', 'verify']);
}).then(function (keyPair) {
self.object = {
version: 0,
privateKeyAlgorithm: privateKey.algorithm,
privateKeyWrapped: wrappedData,
attributes: {
'id-sc-gostR3410-2001-publicKey': keyPair.publicKey.buffer
}
};
return self;
});
}, // </editor-fold>
/**
* Change key password
*
* @memberOf GostKeys.SignalComPrivateKeyInfo
* @instance
* @param {string} oldKeyPassword Old key password
* @param {string} newKeyPassword New key password
* @returns {Promise} Promise to return self object after change password
*/
changePassword: function (oldKeyPassword, newKeyPassword) // <editor-fold defaultstate="collapsed">
{
var self = this;
return self.getPrivateKey(oldKeyPassword).then(function (privateKey) {
return self.setPrivateKey(privateKey, newKeyPassword);
});
}, // </editor-fold>
/**
* Generate private key, certificate and return certification request
*
* @memberOf GostKeys.SignalComPrivateKeyInfo
* @instance
* @param {(FormatedData|GostASN1.CertificationRequest)} req The request templates
* @param {(Key|CryptoOperationData|string)} keyPassword The secret key or password for decryption
* @param {(AlgorithmIdentifier|string)} keyAlgorithm The name of provider or algorithm
* @returns {Promise} Promise to return {@link GostCert.Request}
*/
generate: function (req, keyPassword, keyAlgorithm) // <editor-fold defaultstate="collapsed">
{
var self = this, keyInfo;
return new Promise(call).then(function () {
if (!(req instanceof cert.Request))
req = new cert.Request(req);
// Generate request
return req.generate(keyAlgorithm);
}).then(function (key) {
keyInfo = key;
return self.setKey(keyInfo, keyPassword);
}).then(function () {
return req;
});
} // </editor-fold>
});
defineProperties(SignalComPrivateKeyInfo.prototype, SignalComKeyContainer.prototype);
/**
* A class for password-encrypted SignalCom private keys
*
* @memberOf GostKeys
* @type GostKeys.SignalComPrivateKeyInfo
*/
GostKeys.prototype.SignalComPrivateKeyInfo = SignalComPrivateKeyInfo;
/**
* A class for password-encrypted private keys in CryptoPro container
*
* The container file list:
* <ul>
* <li>header - container header @link GostASN1.GostKeyContainer</li>
* <li>name - container name @link GostASN1.GostKeyContainerName</li>
* <li>primary - private keys data @link GostASN1.GostPrivateKeys</li>
* <li>masks - private key masks @link GostASN1.GostPrivateMasks</li>
* <li>primary2 - reserve of private keys data @link GostASN1.GostPrivateKeys</li>
* <li>masks2 - reserve of private key masks @link GostASN1.GostPrivateMasks</li>
* </ul>
*
* @class GostKeys.CryptoProKeyContainer
* @param {Object} container
*/
function CryptoProKeyContainer(container) // <editor-fold defaultstate="collapsed">
{
if (container) {
this.header = asn1.GostKeyContainer.decode(container.header);
this.name = asn1.GostKeyContainerName.decode(container.name);
this.primary = asn1.GostPrivateKeys.decode(container.primary);
this.masks = asn1.GostPrivateMasks.decode(container.masks);
if (container.primary2 && container.masks2) {
this.primary2 = asn1.GostPrivateKeys.decode(container.primary2);
this.masks2 = asn1.GostPrivateMasks.decode(container.masks2);
}
}
} // </editor-fold>
extend(Object, CryptoProKeyContainer, (function () {
// <editor-fold defaultstate="collapsed">
// True if 512 bit
function isKeySize512(algorithm) {
return algorithm.name.indexOf('-512') >= 0 || algorithm.length === 512;
}
// Test version 2012
function isVersion2012(algorithm) {
return !((algorithm.name.indexOf('-94') >= 0 || algorithm.name.indexOf('-2001') >= 0 ||
algorithm.version === 1994 || algorithm.version === 2001));
}
// Derive password key
function derivePasswordKey(algorithm, password, salt) {
var hash = isVersion2012(algorithm) ? 'GOST R 34.11-256' : 'GOST R 34.11-94/' + (algorithm.sBox || 'D-A'),
derivation = {name: 'CPKDF', hash: hash, salt: salt, iterations: password ? 2000 : 2};
// Import password
return subtle.importKey('raw', passwordData(derivation, password),
derivation, false, ['deriveKey', 'deriveBits']).then(function (baseKey) {
// Derive key
return subtle.deriveKey(derivation, baseKey, 'GOST 28147',
false, ['sign', 'verify', 'encrypt', 'decrypt']);
});
}
// Compute password MAC
function computePasswordMAC(algorithm, password, salt) {
var mac = expand({name: 'GOST 28147-MAC'}, algorithm.encParams);
// Derive password
return derivePasswordKey(algorithm, password, salt).then(function (macKey) {
// Mac for 16 zero bytes
return subtle.sign(mac, macKey,
new Uint8Array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]));
});
}
// var lastBuffer;
// Compute container MAC
function computeContainerMAC(algorithm, content) {
var mac = expand({name: 'GOST 28147-MAC'}, algorithm.encParams),
keyData = new Uint8Array([// 32 zero bytes
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
return subtle.importKey('raw', keyData, mac, false, ['sign']).then(function (macKey) {
// var buffer = new Uint8Array(content.encode());
// console.log(coding.Hex.encode(buffer));
// if (lastBuffer && lastBuffer.length === buffer.length) {
// for (var i = 0; i < buffer.length; i++)
// if (lastBuffer[i] !== buffer[i])
// console.log('diff at ' + i);
// } else
// console.log('diff length');
// lastBuffer = buffer;
// Mac for content
return subtle.sign(mac, macKey, content.encode());
});
}
// Compute mask MAC
function computeMaskMAC(algorithm, mask, status) {
// Import mask as key for MAC
var mac = expand({name: 'GOST 28147-MAC'}, algorithm.encParams),
keyData = mask.byteLength === 64 ?
new Uint8Array(new Uint8Array(mask, 32, 32)).buffer : mask;
return subtle.importKey('raw', keyData, mac, false, ['sign']).then(function (macKey) {
// Verify MAC for maskStatus
return subtle.sign(mac, macKey, status);
});
}
// Generate mask
function generateMasks(algorithm) {
var wrapAlgorithm = expand(algorithm, {mode: 'MASK'}),
mask, status = getSeed(12);
wrapAlgorithm.name = wrapAlgorithm.name.replace('-DH', '');
return subtle.generateKey(wrapAlgorithm, true, ['wrapKey', 'unwrapKey']).then(function (key) {
return subtle.exportKey('raw', key);
}).then(function (data) {
mask = data;
return computeMaskMAC(algorithm, mask, status);
}).then(function (hmac) {
return new asn1.GostPrivateMasks({
mask: mask,
randomStatus: status,
hmacRandom: hmac
});
});
}
// Compute FP
function computeFP(privateKey) {
// Generate key pair with predefined ukm for check public key
return subtle.generateKey(expand(privateKey.algorithm, {ukm: privateKey.buffer}), true, ['sign', 'verify']).then(function (keyPair) {
return new Uint8Array(new Uint8Array(keyPair.publicKey.buffer, 0, 8)).buffer;
});
}
// Unwrap private key
function unwrapKey(algorithm, encryptionKey, key, mask, fp) {
var encryption = {name: 'GOST 28147-ECB', sBox: algorithm.encParams && algorithm.encParams.sBox},
unwrapAlgorithm = expand(algorithm, {mode: 'MASK'}), privateKey;
unwrapAlgorithm.name = unwrapAlgorithm.name.replace('-DH', '');
var wrappedKey;
// Encrypt ukm data for private key
return subtle.decrypt(encryption, encryptionKey, key).then(function (data) {
wrappedKey = data;
// Import mask key
return subtle.importKey('raw', mask, unwrapAlgorithm, 'false', ['sign', 'unwrapKey']);
}).then(function (unwrappingKey) {
// Unwrap private key
return subtle.unwrapKey('raw', wrappedKey, unwrappingKey,
unwrapAlgorithm, algorithm, 'true', ['sign']);
}).then(function (key) {
privateKey = key;
return computeFP(privateKey);
}).then(function (computedFP) {
// Check public key buffer
if (!equalBuffers(computedFP, fp))
throw new Error('Incorrect fp');
return privateKey;
});
}
// Wrap private key
function wrapKey(algorithm, encryptionKey, privateKey, mask) {
var encryption = {name: 'GOST 28147-ECB', sBox: algorithm.encParams && algorithm.encParams.sBox},
wrapAlgorithm = expand(algorithm, {mode: 'MASK'});
wrapAlgorithm.name = wrapAlgorithm.name.replace('-DH', '');
// Import mask key
return subtle.importKey('raw', mask, wrapAlgorithm, false,
['sign', 'wrapKey']).then(function (wrappingKey) {
// Wrap private key
return subtle.wrapKey('raw', privateKey, wrappingKey, wrapAlgorithm);
}).then(function (wrappedKey) {
// Encrypt key
return subtle.encrypt(encryption, encryptionKey, wrappedKey);
});
}
// Decrypt private key
function decryptKey(content, primary, masks, keyPassword, secondary) {
var algorithm = content.primaryPrivateKeyParameters.privateKeyAlgorithm;
return new Promise(call).then(function () {
// Check format
if (primary.hmacKey)
throw new Error('Old key format');
if (masks.randomStatus.byteLength < 12)
throw new Error("Invalid random status length");
// Import mask as key for MAC
return computeMaskMAC(algorithm, masks.mask, masks.randomStatus);
}).then(function (hmac) {
if (!equalBuffers(hmac, masks.hmacRandom))
throw new Error("Imita for mask is invalid");
// Derive key
return derivePasswordKey(algorithm, keyPassword, new Uint8Array(masks.randomStatus, 0, 12));
}).then(function (encryptionKey) {
// Unwrap keys
return secondary && primary.secondaryKey ?
unwrapKey(content.secondaryPrivateKeyParameters.privateKeyAlgorithm,
encryptionKey, primary.secondaryKey, masks.mask, content.secondaryFP) :
unwrapKey(algorithm, encryptionKey, primary.primaryKey, masks.mask, content.primaryFP);
});