forked from rudonick/crypto
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gostCrypto.js
1663 lines (1547 loc) · 74.2 KB
/
gostCrypto.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 Implementation Web Crypto interfaces for GOST algorithms
* @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(['gostRandom'], factory);
} else if (typeof exports === 'object') {
module.exports = factory(require('gostRandom'));
} else {
root.gostCrypto = factory(root.GostRandom);
}
// </editor-fold>
}(this, function (GostRandom) {
/*
* Algorithm normalization
*
*/ // <editor-fold defaultstate="collapsed">
var root = this;
var rootCrypto = root.crypto || root.msCrypto;
var SyntaxError = root.SyntaxError || root.Error,
DataError = root.DataError || root.Error,
NotSupportedError = root.NotSupportedError || root.Error,
OperationError = root.OperationError || root.Error,
InvalidStateError = root.InvalidAccessError || root.Error,
InvalidAccessError = root.InvalidAccessError || root.Error;
// Normalize algorithm
function normalize(algorithm, method) {
if (typeof algorithm === 'string' || algorithm instanceof String)
algorithm = {name: algorithm};
var name = algorithm.name;
if (!name)
throw new SyntaxError('Algorithm name not defined');
// Extract algorithm modes from name
var modes = name.split('/'), modes = modes[0].split('-').concat(modes.slice(1));
// Normalize the name with default modes
var na = {};
name = modes[0].replace(/[\.\s]/g, '');
modes = modes.slice(1);
if (name.indexOf('28147') >= 0) {
na = {
name: 'GOST 28147',
version: 1989,
mode: (algorithm.mode || (// ES, MAC, KW
(method === 'sign' || method === 'verify') ? 'MAC' :
(method === 'wrapKey' || method === 'unwrapKey') ? 'KW' : 'ES')).toUpperCase(),
length: algorithm.length || 64
};
} else if (name.indexOf('3412') >= 0) {
na = {
name: 'GOST R 34.12',
version: 2015,
mode: (algorithm.mode || (// ES, MAC, KW
(method === 'sign' || method === 'verify') ? 'MAC' :
(method === 'wrapKey' || method === 'unwrapKey') ? 'KW' : 'ES')).toUpperCase(),
length: algorithm.length || 64 // 128
};
} else if (name.indexOf('3411') >= 0) {
na = {
name: 'GOST R 34.11',
version: 2012, // 1994
mode: (algorithm.mode || (// HASH, KDF, HMAC, PBKDF2, PFXKDF, CPKDF
(method === 'deriveKey' || method === 'deriveBits') ? 'KDF' :
(method === 'sign' || method === 'verify') ? 'HMAC' : 'HASH')).toUpperCase(),
length: algorithm.length || 256 // 512
};
} else if (name.indexOf('3410') >= 0) {
na = {
name: 'GOST R 34.10',
version: 2012, // 1994, 2001
mode: (algorithm.mode || (// SIGN, DH, MASK
(method === 'deriveKey' || method === 'deriveBits') ? 'DH' : 'SIGN')).toUpperCase(),
length: algorithm.length || 256 // 512
};
} else if (name.indexOf('SHA') >= 0) {
na = {
name: 'SHA',
version: (algorithm.length || 160) === 160 ? 1 : 2, // 1, 2
mode: (algorithm.mode || (// HASH, KDF, HMAC, PBKDF2, PFXKDF
(method === 'deriveKey' || method === 'deriveBits') ? 'KDF' :
(method === 'sign' || method === 'verify') ? 'HMAC' : 'HASH')).toUpperCase(),
length: algorithm.length || 160
};
} else if (name.indexOf('RC2') >= 0) {
na = {
name: 'RC2',
version: 1,
mode: (algorithm.mode || (// ES, MAC, KW
(method === 'sign' || method === 'verify') ? 'MAC' :
(method === 'wrapKey' || method === 'unwrapKey') ? 'KW' : 'ES')).toUpperCase(),
length: algorithm.length || 32 // 1 - 1024
};
} else if (name.indexOf('PBKDF2') >= 0) {
na = normalize(algorithm.hash, 'digest');
na.mode = 'PBKDF2';
} else if (name.indexOf('PFXKDF') >= 0) {
na = normalize(algorithm.hash, 'digest');
na.mode = 'PFXKDF';
} else if (name.indexOf('CPKDF') >= 0) {
na = normalize(algorithm.hash, 'digest');
na.mode = 'CPKDF';
} else if (name.indexOf('HMAC') >= 0) {
na = normalize(algorithm.hash, 'digest');
na.mode = 'HMAC';
} else
throw new NotSupportedError('Algorithm not supported');
// Compile modes
modes.forEach(function (mode) {
mode = mode.toUpperCase();
if (/^[0-9]+$/.test(mode)) {
if ((['8', '16', '32'].indexOf(mode) >= 0) || (na.length === '128' && mode === '64')) { // Shift bits
if (na.mode === 'ES')
na.shiftBits = parseInt(mode);
else if (na.mode === 'MAC')
na.macLength = parseInt(mode);
else
throw new NotSupportedError('Algorithm ' + na.name + ' mode ' + mode + ' not supported');
} else if (['89', '94', '01', '12', '15', '1989', '1994', '2001', '2012', '2015'].indexOf(mode) >= 0) { // GOST Year
var version = parseInt(mode);
version = version < 1900 ? (version < 80 ? 2000 + version : 1900 + version) : version;
na.version = version;
} else if (['1'].indexOf(mode) >= 0 && na.name === 'SHA') { // SHA-1
na.version = 1;
na.length = 160;
} else if (['256', '384', '512'].indexOf(mode) >= 0 && na.name === 'SHA') { // SHA-2
na.version = 2;
na.length = parseInt(mode);
} else if (['40', '128'].indexOf(mode) >= 0 && na.name === 'RC2') { // RC2
na.version = 1;
na.length = parseInt(mode); // key size
} else if (['64', '128', '256', '512'].indexOf(mode) >= 0) // block size
na.length = parseInt(mode);
else if (['1000', '2000'].indexOf(mode) >= 0) // Iterations
na.iterations = parseInt(mode);
// Named Paramsets
} else if (['E-TEST', 'E-A', 'E-B', 'E-C', 'E-D', 'E-SC', 'E-Z', 'D-TEST', 'D-A', 'D-SC'].indexOf(mode) >= 0) {
na.sBox = mode;
} else if (['S-TEST', 'S-A', 'S-B', 'S-C', 'S-D', 'X-A', 'X-B', 'X-C'].indexOf(mode) >= 0) {
na.namedParam = mode;
} else if (['S-256-TEST', 'S-256-A', 'S-256-B', 'S-256-C', 'P-256', 'T-512-TEST', 'T-512-A',
'T-512-B', 'X-256-A', 'X-256-B', 'T-256-TEST', 'T-256-A', 'T-256-B', 'S-256-B', 'T-256-C', 'S-256-C'].indexOf(mode) >= 0) {
na.namedCurve = mode;
} else if (['SC', 'CP', 'VN'].indexOf(mode) >= 0) {
na.procreator = mode;
// Encription GOST 28147 or GOST R 34.12
} else if (na.name === 'GOST 28147' || na.name === 'GOST R 34.12' || na.name === 'RC2') {
if (['ES', 'MAC', 'KW', 'MASK'].indexOf(mode) >= 0) {
na.mode = mode;
} else if (['ECB', 'CFB', 'OFB', 'CTR', 'CBC'].indexOf(mode) >= 0) {
na.mode = 'ES';
na.block = mode;
} else if (['CPKW', 'NOKW', 'SCKW'].indexOf(mode) >= 0) {
na.mode = 'KW';
na.keyWrapping = mode.replace('KW', '');
} else if (['ZEROPADDING', 'PKCS5PADDING', 'NOPADDING', 'RANDOMPADDING', 'BITPADDING'].indexOf(mode) >= 0) {
na.padding = mode.replace('PADDING', '');
} else if (['NOKM', 'CPKM'].indexOf(mode) >= 0) {
na.keyMeshing = mode.replace('KM', '');
} else
throw new NotSupportedError('Algorithm ' + na.name + ' mode ' + mode + ' not supported');
// Digesting GOST 34.11
} else if (na.name === 'GOST R 34.11' || na.name === 'SHA') {
if (['HASH', 'KDF', 'HMAC', 'PBKDF2', 'PFXKDF', 'CPKDF'].indexOf(mode) >= 0)
na.mode = mode;
else
throw new NotSupportedError('Algorithm ' + na.name + ' mode ' + mode + ' not supported');
// Signing GOST 34.10
} else if (na.name === 'GOST R 34.10') {
var hash = mode.replace(/[\.\s]/g, '');
if (hash.indexOf('GOST') >= 0 && hash.indexOf('3411') >= 0)
na.hash = mode;
else if (['SIGN', 'DH', 'MASK'].indexOf(mode))
na.mode = mode;
else
throw new NotSupportedError('Algorithm ' + na.name + ' mode ' + mode + ' not supported');
}
});
// Procreator
na.procreator = algorithm.procreator || na.procreator || 'CP';
// Key size
switch (na.name) {
case 'GOST R 34.10':
na.keySize = na.length / (na.version === 1994 ? 4 : 8);
break;
case 'GOST R 34.11':
na.keySize = 32;
break;
case 'GOST 28147':
case 'GOST R 34.12':
na.keySize = 32;
break;
case 'RC2':
na.keySize = Math.ceil(na.length / 8);
break;
case 'SHA':
na.keySize = na.length / 8;
break;
}
// Encrypt additional modes
if (na.mode === 'ES') {
if (algorithm.block)
na.block = algorithm.block; // ECB, CFB, OFB, CTR, CBC
if (na.block)
na.block = na.block.toUpperCase();
if (algorithm.padding)
na.padding = algorithm.padding; // NO, ZERO, PKCS5, RANDOM, BIT
if (na.padding)
na.padding = na.padding.toUpperCase();
if (algorithm.shiftBits)
na.shiftBits = algorithm.shiftBits; // 8, 16, 32, 64
if (algorithm.keyMeshing)
na.keyMeshing = algorithm.keyMeshing; // NO, CP
if (na.keyMeshing)
na.keyMeshing = na.keyMeshing.toUpperCase();
// Default values
if (method !== 'importKey' && method !== 'generateKey') {
na.block = na.block || 'ECB';
na.padding = na.padding || (na.block === 'CBC' || na.block === 'ECB' ? 'ZERO' : 'NO');
if (na.block === 'CFB' || na.block === 'OFB')
na.shiftBits = na.shiftBits || na.length;
na.keyMeshing = na.keyMeshing || 'NO';
}
}
if (na.mode === 'KW') {
if (algorithm.keyWrapping)
na.keyWrapping = algorithm.keyWrapping; // NO, CP, SC
if (na.keyWrapping)
na.keyWrapping = na.keyWrapping.toUpperCase();
if (method !== 'importKey' && method !== 'generateKey')
na.keyWrapping = na.keyWrapping || 'NO';
}
// Paramsets
['sBox', 'namedParam', 'namedCurve', 'curve', 'param', 'modulusLength'].forEach(function (name) {
algorithm[name] && (na[name] = algorithm[name]);
});
// Default values
if (method !== 'importKey' && method !== 'generateKey') {
if (na.name === 'GOST 28147') {
na.sBox = na.sBox || (na.procreator === 'SC' ? 'E-SC' : 'E-A'); // 'E-A', 'E-B', 'E-C', 'E-D', 'E-SC'
} else if (na.name === 'GOST R 34.12' && na.length === 64) {
na.sBox = 'E-Z';
} else if (na.name === 'GOST R 34.11' && na.version === 1994) {
na.sBox = na.sBox || (na.procreator === 'SC' ? 'D-SC' : 'D-A'); // 'D-SC'
} else if (na.name === 'GOST R 34.10' && na.version === 1994) {
na.namedParam = na.namedParam || (na.mode === 'DH' ? 'X-A' : 'S-A'); // 'S-B', 'S-C', 'S-D', 'X-B', 'X-C'
} else if (na.name === 'GOST R 34.10' && na.version === 2001) {
na.namedCurve = na.namedCurve || (na.length === 256 ?
na.procreator === 'SC' ? 'P-256' : (na.mode === 'DH' ? 'X-256-A' : 'S-256-A') : // 'S-256-B', 'S-256-C', 'X-256-B', 'T-256-A', 'T-256-B', 'T-256-C', 'P-256'
na.mode === 'T-512-A'); // 'T-512-B', 'T-512-C'
} else if (na.name === 'GOST R 34.10' && na.version === 2012) {
na.namedCurve = na.namedCurve || (na.length === 256 ?
na.procreator === 'SC' ? 'P-256' : (na.mode === 'DH' ? 'X-256-A' : 'S-256-A') : // 'S-256-B', 'S-256-C', 'X-256-B', 'T-256-A', 'T-256-B', 'T-256-C', 'P-256'
na.mode === 'T-512-A'); // 'T-512-B', 'T-512-C'
}
}
// Vectors
switch (na.mode) {
case 'DH':
algorithm.ukm && (na.ukm = algorithm.ukm);
algorithm['public'] && (na['public'] = algorithm['public']);
break;
case 'SIGN':
case 'KW':
algorithm.ukm && (na.ukm = algorithm.ukm);
break;
case 'ES':
case 'MAC':
algorithm.iv && (na.iv = algorithm.iv);
break;
case 'KDF':
algorithm.label && (na.label = algorithm.label);
algorithm.contex && (na.context = algorithm.contex);
break;
case 'PBKDF2':
algorithm.salt && (na.salt = algorithm.salt);
algorithm.iterations && (na.iterations = algorithm.iterations);
algorithm.diversifier && (na.diversifier = algorithm.diversifier);
break;
case 'PFXKDF':
algorithm.salt && (na.salt = algorithm.salt);
algorithm.iterations && (na.iterations = algorithm.iterations);
algorithm.diversifier && (na.diversifier = algorithm.diversifier);
break;
case 'CPKDF':
algorithm.salt && (na.salt = algorithm.salt);
algorithm.iterations && (na.iterations = algorithm.iterations);
break;
}
// Verification method and modes
if (method && (
((na.mode !== 'ES' && na.mode !== 'SIGN' && na.mode !== 'MAC' &&
na.mode !== 'HMAC' && na.mode !== 'KW' && na.mode !== 'DH'
&& na.mode !== 'MASK') &&
(method === 'generateKey')) ||
((na.mode !== 'ES') &&
(method === 'encrypt' || method === 'decrypt')) ||
((na.mode !== 'SIGN' && na.mode !== 'MAC' && na.mode !== 'HMAC') &&
(method === 'sign' || method === 'verify')) ||
((na.mode !== 'HASH') &&
(method === 'digest')) ||
((na.mode !== 'KW' && na.mode !== 'MASK') &&
(method === 'wrapKey' || method === 'unwrapKey')) ||
((na.mode !== 'DH' && na.mode !== 'PBKDF2' && na.mode !== 'PFXKDF' &&
na.mode !== 'CPKDF' && na.mode !== 'KDF') &&
(method === 'deriveKey' || method === 'deriveBits'))))
throw new NotSupportedError('Algorithm mode ' + na.mode + ' not valid for method ' + method);
// Normalize hash algorithm
algorithm.hash && (na.hash = algorithm.hash);
if (na.hash) {
if ((typeof na.hash === 'string' || na.hash instanceof String)
&& na.procreator)
na.hash = na.hash + '/' + na.procreator;
na.hash = normalize(na.hash, 'digest');
}
// Algorithm object identirifer
algorithm.id && (na.id = algorithm.id);
return na;
}
// Check for possibility use native crypto.subtle
function checkNative(algorithm) {
if (!rootCrypto || !rootCrypto.subtle || !algorithm)
return false;
// Prepare name
var name = (typeof algorithm === 'string' || algorithm instanceof String) ?
name = algorithm : algorithm.name;
if (!name)
return false;
name = name.toUpperCase();
// Digest algorithm for key derivation
if ((name.indexOf('KDF') >= 0 || name.indexOf('HMAC') >= 0) && algorithm.hash)
return checkNative(algorithm.hash);
// True if no supported names
return name.indexOf('GOST') === -1 &&
name.indexOf('SHA-1') === -1 &&
name.indexOf('RC2') === -1 &&
name.indexOf('?DES') === -1;
}
// </editor-fold>
/*
* Key conversion methods
*
*/ // <editor-fold defaultstate="collapsed">
// Check key parameter
function checkKey(key, method) {
if (!key.algorithm)
throw new SyntaxError('Key algorithm not defined');
if (!key.algorithm.name)
throw new SyntaxError('Key algorithm name not defined');
var name = key.algorithm.name,
gostCipher = name === 'GOST 28147' || name === 'GOST R 34.12' || name === 'RC2',
gostDigest = name === 'GOST R 34.11' || name === 'SHA',
gostSign = name === 'GOST R 34.10';
if (!gostCipher && !gostSign && !gostDigest)
throw new NotSupportedError('Key algorithm ' + name + ' is unsupproted');
if (!key.type)
throw new SyntaxError('Key type not defined');
if (((gostCipher || gostDigest) && key.type !== 'secret') ||
(gostSign && !(key.type === 'public' || key.type === 'private')))
throw new DataError('Key type ' + key.type + ' is not valid for algorithm ' + name);
if (!key.usages || !key.usages.indexOf)
throw new SyntaxError('Key usages not defined');
for (var i = 0, n = key.usages.length; i < n; i++) {
var md = key.usages[i];
if (((md === 'encrypt' || md === 'decrypt') && key.type !== 'secret') ||
(md === 'sign' && key.type === 'public') ||
(md === 'verify' && key.type === 'private'))
throw new InvalidStateError('Key type ' + key.type + ' is not valid for ' + md);
}
if (method)
if (key.usages.indexOf(method) === -1)
throw new InvalidAccessError('Key usages is not contain method ' + method);
if (!key.buffer)
throw new SyntaxError('Key buffer is not defined');
var size = key.buffer.byteLength * 8, keySize = 8 * key.algorithm.keySize;
if ((key.type === 'secret' && size !== (keySize || 256) &&
(key.usages.indexOf('encrypt') >= 0 || key.usages.indexOf('decrypt') >= 0)) ||
(key.type === 'private' && !(size === 256 || size === 512)) ||
(key.type === 'public' && !(size === 512 || size === 1024)))
throw new SyntaxError('Key buffer has wrong size ' + size + ' bit');
}
// Extract key and enrich cipher algorithm
function extractKey(method, algorithm, key) {
checkKey(key, method);
if (algorithm) {
var params;
switch (algorithm.mode) {
case 'ES':
params = ['sBox', 'keyMeshing', 'padding', 'block'];
break;
case 'SIGN':
params = ['namedCurve', 'namedParam', 'sBox', 'curve', 'param', 'modulusLength'];
break;
case 'MAC':
params = ['sBox'];
break;
case 'KW':
params = ['keyWrapping', 'ukm'];
break;
case 'DH':
params = ['namedCurve', 'namedParam', 'sBox', 'ukm', 'curve', 'param', 'modulusLength'];
break;
case 'KDF':
params = ['context', 'label'];
break;
case 'PBKDF2':
params = ['sBox', 'iterations', 'salt'];
break;
case 'PFXKDF':
params = ['sBox', 'iterations', 'salt', 'diversifier'];
break;
case 'CPKDF':
params = ['sBox', 'salt'];
break;
}
if (params)
params.forEach(function (name) {
key.algorithm[name] && (algorithm[name] = key.algorithm[name]);
});
}
return key.buffer;
}
// Make key definition
function convertKey(algorithm, extractable, keyUsages, keyData, keyType) {
var key = {
type: keyType || (algorithm.name === 'GOST R 34.10' ? 'private' : 'secret'),
extractable: extractable || 'false',
algorithm: algorithm,
usages: keyUsages || [],
buffer: keyData
};
checkKey(key);
return key;
}
function convertKeyPair(publicAlgorithm, privateAlgorithm, extractable, keyUsages, publicBuffer, privateBuffer) {
if (!keyUsages || !keyUsages.indexOf)
throw new SyntaxError('Key usages not defined');
var publicUsages = keyUsages.filter(function (value) {
return value !== 'sign';
});
var privateUsages = keyUsages.filter(function (value) {
return value !== 'verify';
});
return {
publicKey: convertKey(publicAlgorithm, extractable, publicUsages, publicBuffer, 'public'),
privateKey: convertKey(privateAlgorithm, extractable, privateUsages, privateBuffer, 'private')
};
}
// Swap bytes in buffer
function swapBytes(src) {
if (src instanceof CryptoOperationData)
src = new Uint8Array(src);
var dst = new Uint8Array(src.length);
for (var i = 0, n = src.length; i < n; i++)
dst[n - i - 1] = src[i];
return dst.buffer;
}
// </editor-fold>
/**
* Promise stub object (not fulfill specification, only for internal use)
* Class not defined if Promise class already defined in root context<br><br>
*
* The Promise object is used for deferred and asynchronous computations. A Promise is in one of the three states:
* <ul>
* <li>pending: initial state, not fulfilled or rejected.</li>
* <li>fulfilled: successful operation</li>
* <li>rejected: failed operation.</li>
* </ul>
* Another term describing the state is settled: the Promise is either fulfilled or rejected, but not pending.<br><br>
* @class Promise
* @global
* @param {function} executor Function object with two arguments resolve and reject.
* The first argument fulfills the promise, the second argument rejects it.
* We can call these functions, once our operation is completed.
*/ // <editor-fold defaultstate="collapsed">
if (!root.Promise) {
root.Promise = (function () {
function mswrap(value) {
if (value && value.oncomplete === null && value.onerror === null) {
return new Promise(function (resolve, reject) {
value.oncomplete = function () {
resolve(value.result);
};
value.onerror = function () {
reject(new OperationError(value.toString()));
};
});
} else
return value;
}
function Promise(executor) {
var state = 'pending', result,
resolveQueue = [], rejectQueue = [];
function call(callback) {
try {
callback();
} catch (e) {
}
}
try {
executor(function (value) {
if (state === 'pending') {
state = 'fulfilled';
result = value;
resolveQueue.forEach(call);
}
}, function (reason) {
if (state === 'pending') {
state = 'rejected';
result = reason;
rejectQueue.forEach(call);
}
});
} catch (error) {
if (state === 'pending') {
state = 'rejected';
result = error;
rejectQueue.forEach(call);
}
}
/**
* The then() method returns a Promise. It takes two arguments, both are
* callback functions for the success and failure cases of the Promise.
*
* @method then
* @memberOf Promise
* @instance
* @param {function} onFulfilled A Function called when the Promise is fulfilled. This function has one argument, the fulfillment value.
* @param {function} onRejected A Function called when the Promise is rejected. This function has one argument, the rejection reason.
* @returns {Promise}
*/
this.then = function (onFulfilled, onRejected) {
return new Promise(function (resolve, reject) {
function asyncOnFulfilled() {
var value;
try {
value = onFulfilled ? onFulfilled(result) : result;
} catch (error) {
reject(error);
return;
}
value = mswrap(value);
if (value && value.then && value.then.call) {
value.then(resolve, reject);
} else {
resolve(value);
}
}
function asyncOnRejected() {
var reason;
try {
reason = onRejected ? onRejected(result) : result;
} catch (error) {
reject(error);
return;
}
reason = mswrap(reason);
if (reason && reason.then && reason.then.call) {
reason.then(resolve, reject);
} else {
reject(reason);
}
}
if (state === 'fulfilled') {
asyncOnFulfilled();
} else if (state === 'rejected') {
asyncOnRejected();
} else {
resolveQueue.push(asyncOnFulfilled);
rejectQueue.push(asyncOnRejected);
}
});
};
/**
* The catch() method returns a Promise and deals with rejected cases only.
* It behaves the same as calling Promise.prototype.then(undefined, onRejected).
*
* @method catch
* @memberOf Promise
* @instance
* @param {function} onRejected A Function called when the Promise is rejected. This function has one argument, the rejection reason.
* @returns {Promise}
*/
this['catch'] = function (onRejected) {
return this.then(undefined, onRejected);
};
}
/**
* The Promise.all(iterable) method returns a promise that resolves when all
* of the promises in the iterable argument have resolved.<br><br>
*
* The result is passed as an array of values from all the promises.
* If something passed in the iterable array is not a promise, it's converted to
* one by Promise.resolve. If any of the passed in promises rejects, the
* all Promise immediately rejects with the value of the promise that rejected,
* discarding all the other promises whether or not they have resolved.
*
* @method all
* @memberOf Promise
* @static
* @param {KeyUsages} promises Array with promises.
* @returns {Promise}
*/
Promise.all = function (promises) {
return new Promise(function (resolve, reject) {
var result = [], count = 0;
function asyncResolve(k) {
count++;
return function (data) {
result[k] = data;
count--;
if (count === 0)
resolve(result);
};
}
function asyncReject(reason) {
if (count > 0)
reject(reason);
count = 0;
}
for (var i = 0, n = promises.length; i < n; i++) {
var data = promises[i];
if (data.then && data.then.call)
data.then(asyncResolve(i), asyncReject);
else
result[i] = data;
}
if (count === 0)
resolve(result);
});
};
return Promise;
})();
} // </editor-fold>
/*
* Worker executor
*
*/ // <editor-fold defaultstate="collapsed">
var baseUrl = '', nameSuffix = '';
// Try to define from DOM model
if (typeof document !== 'undefined') {
(function () {
var regs = /^(.*)gostCrypto(.*)\.js$/i;
var list = document.querySelectorAll('script');
for (var i = 0, n = list.length; i < n; i++) {
var value = list[i].getAttribute('src');
var test = regs.exec(value);
if (test) {
baseUrl = test[1];
nameSuffix = test[2];
}
}
})();
}
// Local importScripts procedure for include dependens
function importScripts() {
for (var i = 0, n = arguments.length; i < n; i++) {
var name = arguments[i].split('.'),
src = baseUrl + name[0] + nameSuffix + '.' + name[1];
var el = document.querySelector('script[src="' + src + '"]');
if (!el) {
el = document.createElement('script');
el.setAttribute('src', src);
document.head.appendChild(el);
}
}
}
// Create Worker
var worker, tasks = [], sequence = 0;
// Worker will create only for first child process and
// Gost implementation libraries not yet loaded
if (!root.importScripts && !root.gostEngine) {
try {
worker = new Worker(baseUrl + 'gostEngine' + nameSuffix + '.js');
// Result of opertion
worker.onmessage = function (event) {
// Find task
var id = event.data.id;
for (var i = 0, n = tasks.length; i < n; i++)
if (tasks[i].id === id)
break;
if (i < n) {
var task = tasks[i];
tasks.splice(i, 1);
// Reject if error or resolve with result
if (event.data.error)
task.reject(new OperationError(event.data.error));
else
task.resolve(event.data.result);
}
};
// Worker error - reject all waiting tasks
worker.onerror = function (event) {
for (var i = 0, n = tasks.length; i < n; i++)
tasks[i].reject(event.error);
tasks = [];
};
} catch (e) {
// Worker is't supported
worker = false;
}
}
if (!root.importScripts) {
// This procedure emulate load dependents as in Worker
root.importScripts = importScripts;
}
if (!worker) {
// Import main module
// Reason: we are already in worker process or Worker interface is not
// yet supported
root.gostEngine || importScripts('gostEngine.js');
}
// Executor for any method
function execute(algorithm, method, args) {
return new Promise(function (resolve, reject) {
try {
if (worker) {
var id = ++sequence;
tasks.push({
id: id,
resolve: resolve,
reject: reject
});
worker.postMessage({
id: id, algorithm: algorithm,
method: method, args: args
});
} else {
if (root.gostEngine)
resolve(root.gostEngine.execute(algorithm, method, args));
else
reject(new OperationError('Module gostEngine not found'));
}
} catch (error) {
reject(error);
}
});
}
// Self resolver
function call(callback) {
try {
callback();
} catch (e) {
}
}
// </editor-fold>
/*
* WebCrypto common class references
*
*/ // <editor-fold defaultstate="collapsed">
/**
* The Algorithm object is a dictionary object [WebIDL] which is used to
* specify an algorithm and any additional parameters required to fully
* specify the desired operation.<br>
* <pre>
* dictionary Algorithm {
* DOMString name;
* };
* </pre>
* WebCrypto API reference {@link http://www.w3.org/TR/WebCryptoAPI/#algorithm-dictionary}
* @class Algorithm
* @param {DOMString} name The name of the registered algorithm to use.
*/
/**
* AlgorithmIdentifier - Algorithm or DOMString name of algorithm<br>
* <pre>
* typedef (Algorithm or DOMString) AlgorithmIdentifier;
* </pre>
* WebCrypto API reference {@link http://www.w3.org/TR/WebCryptoAPI/#algorithm-dictionary}
* @class AlgorithmIdentifier
*/
/**
* The KeyAlgorithm interface represents information about the contents of a
* given Key object.
* <pre>
* interface KeyAlgorithm {
* readonly attribute DOMString name
* };
* </pre>
* WebCrypto API reference {@link http://www.w3.org/TR/WebCryptoAPI/#key-algorithm-interface}
* @class KeyAlgorithm
* @param {DOMString} name The name of the algorithm used to generate the Key
*/
/**
* The type of a key. The recognized key type values are "public", "private"
* and "secret". Opaque keying material, including that used for symmetric
* algorithms, is represented by "secret", while keys used as part of asymmetric
* algorithms composed of public/private keypairs will be either "public" or "private".
* <pre>
* typedef DOMString KeyType;
* </pre>
* WebCrypto API reference {@link http://www.w3.org/TR/WebCryptoAPI/#key-interface}
* @class KeyType
*/
/**
* Sequence of operation type that may be performed using a key. The recognized
* key usage values are "encrypt", "decrypt", "sign", "verify", "deriveKey",
* "deriveBits", "wrapKey" and "unwrapKey".
* <pre>
* typedef DOMString[] KeyUsages;
* </pre>
* WebCrypto API reference {@link http://www.w3.org/TR/WebCryptoAPI/#key-interface}
* @class KeyUsages
*/
/**
* The Key object represents an opaque reference to keying material that is
* managed by the user agent.<br>
* This specification provides a uniform interface for many different kinds of
* keying material managed by the user agent. This may include keys that have
* been generated by the user agent, derived from other keys by the user agent,
* imported to the user agent through user actions or using this API,
* pre-provisioned within software or hardware to which the user agent has
* access or made available to the user agent in other ways. The term key refers
* broadly to any keying material including actual keys for cryptographic
* operations and secret values obtained within key derivation or exchange operations.<br>
* The Key object is not required to directly interface with the underlying key
* storage mechanism, and may instead simply be a reference for the user agent
* to understand how to obtain the keying material when needed, eg. when performing
* a cryptographic operation.
* <pre>
* interface Key {
* readonly attribute KeyType type;
* readonly attribute boolean extractable;
* readonly attribute KeyAlgorithm algorithm;
* readonly attribute KeyUsages usages;
* };
* </pre>
* WebCrypto API reference {@link http://www.w3.org/TR/WebCryptoAPI/#key-interface}
* @class Key
* @param {KeyType} type The type of a key. The recognized key type values are "public", "private" and "secret".
* @param {boolean} extractable Whether or not the raw keying material may be exported by the application.
* @param {KeyAlgorithm} algorithm The Algorithm used to generate the key.
* @param {KeyUsages} usages Key usage array: type of operation that may be performed using a key.
*/
/**
* The KeyPair interface represents an asymmetric key pair that is comprised of both public and private keys.
* <pre>
* interface KeyPair {
* readonly attribute Key publicKey;
* readonly attribute Key privateKey;
* };
* </pre>
* WebCrypto API reference {@link http://www.w3.org/TR/WebCryptoAPI/#keypair}
* @class KeyPair
* @param {Key} privateKey Private key
* @param {Key} publicKey Public key
*/
/**
* Specifies a serialization format for a key. The recognized key format values are:
* <ul>
* <li>'raw' - An unformatted sequence of bytes. Intended for secret keys.</li>
* <li>'pkcs8' - The DER encoding of the PrivateKeyInfo structure from RFC 5208.</li>
* <li>'spki' - The DER encoding of the SubjectPublicKeyInfo structure from RFC 5280.</li>
* <li>'jwk' - The key is represented as JSON according to the JSON Web Key format.</li>
* </ul>
* <pre>
* typedef DOMString KeyFormat;
* </pre>
* WebCrypto API reference {@link http://www.w3.org/TR/WebCryptoAPI/#key-interface}
* @class KeyFormat
*/
/**
* Binary data
* <pre>
* typedef (ArrayBuffer or ArrayBufferView) CryptoOperationData;
* </pre>
* @class CryptoOperationData
*/
var CryptoOperationData = root.ArrayBuffer;
/**
* DER-encoded ArrayBuffer or PEM-encoded DOMString constains ASN.1 object<br>
* <pre>
* typedef (ArrayBuffer or DOMString) FormatedData;
* </pre>
* @class FormatedData
*/
// </editor-fold>
/**
* The gostCrypto provide general purpose cryptographic functionality for
* GOST standards including a cryptographically strong pseudo-random number
* generator seeded with truly random values.
*
* @namespace gostCrypto
*/
var gostCrypto = {};
/**