forked from kevlened/msrCrypto
-
Notifications
You must be signed in to change notification settings - Fork 7
/
msrcrypto.js
executable file
·9652 lines (7472 loc) · 349 KB
/
msrcrypto.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
//*******************************************************************************
//
// Copyright 2018 Microsoft
//
// 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.
//
//*******************************************************************************
var msrCryptoVersion = "1.5.6";
var msrCrypto = msrCrypto || (function () {
"use strict";
var operations = {};
operations.register = function (operationType, algorithmName, functionToCall) {
if (!operations[operationType]) {
operations[operationType] = {};
}
var op = operations[operationType];
if (!op[algorithmName]) {
op[algorithmName] = functionToCall;
}
};
operations.exists = function (operationType, algorithmName) {
if (!operations[operationType]) {
return false;
}
return (operations[operationType][algorithmName]) ? true : false;
};
/// Store the URL for this script. We will need this later to instantiate
/// new web workers (if supported).
var scriptUrl = (function () {
if (typeof document !== "undefined") {
// Use error.stack to find out the name of this script
try {
throw new Error();
} catch (e) {
if (e.stack) {
var match = /\w+:\/\/(.+?\/)*.+\.js/.exec(e.stack);
return (match && match.length > 0) ? match[0] : null;
}
}
} else if (typeof self !== "undefined") {
// If this script is being run in a WebWorker, 'document' will not exist
// but we can use self.
return self.location.href;
}
// We must be running in an environment without document or self.
return null;
})();
// Indication if the user provided entropy into the entropy pool.
var fprngEntropyProvided = false;
// Support for webWorkers IE10+.
var webWorkerSupport = (typeof Worker !== "undefined");
// Is this script running in an instance of a webWorker?
var runningInWorkerInstance = (typeof importScripts !== "undefined");
// Typed Arrays support?
var typedArraySupport = (typeof Uint8Array !== "undefined");
// Property setter/getter support IE9+.
var setterSupport = (function () {
try {
Object.defineProperty({}, "oncomplete", {});
return true;
} catch (ex) {
return false;
}
}());
// Run in async mode (requires web workers) and user can override to sync mode
// by setting the .forceSync property to true on the subtle interface
// this can be changes 'on the fly'.
var asyncMode = webWorkerSupport;
var createProperty = function (parentObject, propertyName, initialValue, getterFunction, setterFunction) {
/// <param name="parentObject" type="Object"/>
/// <param name="propertyName" type="String"/>
/// <param name="initialValue" type="Object"/>
/// <param name="getterFunction" type="Function"/>
/// <param name="setterFunction" type="Function" optional="true"/>
if (!setterSupport) {
parentObject[propertyName] = initialValue;
return;
}
var setGet = {};
getterFunction && (setGet.get = getterFunction);
setterFunction && (setGet.set = setterFunction);
Object.defineProperty(
parentObject,
propertyName, setGet);
};
// Collection of hash functions for global availability.
// Each hashfunction will add itself to the collection as it is evaluated.
var msrcryptoHashFunctions = {};
var msrcryptoUtilities = (function () {
var encodingChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
var btoaSupport = (typeof btoa !== "undefined");
function toBase64(data, base64Url) {
/// <signature>
/// <summary>Converts byte data to Base64 string</summary>
/// <param name="data" type="Array">An array of bytes values (numbers from 0-255)</param>
/// <param name="base64Url" type="Boolean" optional="true">Converts to a Base64Url string if True (default = false)</param>
/// <returns type="String" />
/// </signature>
/// <signature>
/// <summary>Converts byte data to Base64 string</summary>
/// <param name="data" type="UInt8Array">A UInt8Array</param>
/// <param name="base64Url" type="Boolean" optional="true">Converts to a Base64Url string if True (default = false)</param>
/// <returns type="String" />
/// </signature>
/// <signature>
/// <summary>Converts text to Base64 string</summary>
/// <param name="data" type="String">Text string</param>
/// <param name="base64Url" type="Boolean" optional="true">Converts to a Base64Url string if True (default = false)</param>
/// <returns type="String" />
/// </signature>
var output = "";
if (!base64Url) {
base64Url = false;
}
// If the input is an array type, convert it to a string.
// The built-in btoa takes strings.
if (data.pop || data.subarray) {
data = String.fromCharCode.apply(null, data);
}
if (btoaSupport) {
output = btoa(data);
} else {
var char1, char2, char3, enc1, enc2, enc3, enc4;
var i;
for (i = 0; i < data.length; i += 3) {
// Get the next three chars.
char1 = data.charCodeAt(i);
char2 = data.charCodeAt(i + 1);
char3 = data.charCodeAt(i + 2);
// Encode three bytes over four 6-bit values.
// [A7,A6,A5,A4,A3,A2,A1,A0][B7,B6,B5,B4,B3,B2,B1,B0][C7,C6,C5,C4,C3,C2,C1,C0].
// [A7,A6,A5,A4,A3,A2][A1,A0,B7,B6,B5,B4][B3,B2,B1,B0,C7,C6][C5,C4,C3,C2,C1,C0].
// 'enc1' = high 6-bits from char1
enc1 = char1 >> 2;
// 'enc2' = 2 low-bits of char1 + 4 high-bits of char2
enc2 = ((char1 & 0x3) << 4) | (char2 >> 4);
// 'enc3' = 4 low-bits of char2 + 2 high-bits of char3
enc3 = ((char2 & 0xF) << 2) | (char3 >> 6);
// 'enc4' = 6 low-bits of char3
enc4 = char3 & 0x3F;
// 'char2' could be 'nothing' if there is only one char left to encode
// if so, set enc3 & enc4 to 64 as padding.
if (isNaN(char2)) {
enc3 = enc4 = 64;
// If there was only two chars to encode char3 will be 'nothing'
// set enc4 to 64 as padding.
} else if (isNaN(char3)) {
enc4 = 64;
}
// Lookup the base-64 value for each encoding.
output = output +
encodingChars.charAt(enc1) +
encodingChars.charAt(enc2) +
encodingChars.charAt(enc3) +
encodingChars.charAt(enc4);
}
}
if (base64Url) {
return output.replace(/\+/g, "-").replace(/\//g, "_").replace(/\=/g, "");
}
return output;
}
function base64ToString(encodedString) {
/// <signature>
/// <summary>Converts a Base64/Base64Url string to a text</summary>
/// <param name="encodedString" type="String">A Base64/Base64Url encoded string</param>
/// <returns type="String" />
/// </signature>
if (btoaSupport) {
// This could be encoded as base64url (different from base64)
encodedString = encodedString.replace(/-/g, "+").replace(/_/g, "/");
// In case the padding is missing, add some.
while (encodedString.length % 4 !== 0) {
encodedString += "=";
}
return atob(encodedString);
}
return String.fromCharCode.apply(null, base64ToBytes(encodedString));
}
function base64ToBytes(encodedString) {
/// <signature>
/// <summary>Converts a Base64/Base64Url string to an Array</summary>
/// <param name="encodedString" type="String">A Base64/Base64Url encoded string</param>
/// <returns type="Array" />
/// </signature>
// This could be encoded as base64url (different from base64)
encodedString = encodedString.replace(/-/g, "+").replace(/_/g, "/");
// In case the padding is missing, add some.
while (encodedString.length % 4 !== 0) {
encodedString += "=";
}
var output = [];
var char1, char2, char3;
var enc1, enc2, enc3, enc4;
var i;
// Remove any chars not in the base-64 space.
encodedString = encodedString.replace(/[^A-Za-z0-9\+\/\=]/g, "");
for (i = 0; i < encodedString.length; i += 4) {
// Get 4 characters from the encoded string.
enc1 = encodingChars.indexOf(encodedString.charAt(i));
enc2 = encodingChars.indexOf(encodedString.charAt(i + 1));
enc3 = encodingChars.indexOf(encodedString.charAt(i + 2));
enc4 = encodingChars.indexOf(encodedString.charAt(i + 3));
// Convert four 6-bit values to three characters.
// [A7,A6,A5,A4,A3,A2][A1,A0,B7,B6,B5,B4][B3,B2,B1,B0,C7,C6][C5,C4,C3,C2,C1,C0].
// [A7,A6,A5,A4,A3,A2,A1,A0][B7,B6,B5,B4,B3,B2,B1,B0][C7,C6,C5,C4,C3,C2,C1,C0].
// 'char1' = all 6 bits of enc1 + 2 high-bits of enc2.
char1 = (enc1 << 2) | (enc2 >> 4);
// 'char2' = 4 low-bits of enc2 + 4 high-bits of enc3.
char2 = ((enc2 & 15) << 4) | (enc3 >> 2);
// 'char3' = 2 low-bits of enc3 + all 6 bits of enc4.
char3 = ((enc3 & 3) << 6) | enc4;
// Convert char1 to string character and append to output
output.push(char1);
// 'enc3' could be padding
// if so, 'char2' is ignored.
if (enc3 !== 64) {
output.push(char2);
}
// 'enc4' could be padding
// if so, 'char3' is ignored.
if (enc4 !== 64) {
output.push(char3);
}
}
return output;
}
function getObjectType(object) {
/// <signature>
/// <summary>Returns the name of an object type</summary>
/// <param name="object" type="Object"></param>
/// <returns type="String" />
/// </signature>
return Object.prototype.toString.call(object).slice(8, -1);
}
function bytesToHexString(bytes, separate) {
/// <signature>
/// <summary>Converts an Array of bytes values (0-255) to a Hex string</summary>
/// <param name="bytes" type="Array"/>
/// <param name="separate" type="Boolean" optional="true">Inserts a separator for display purposes (default = false)</param>
/// <returns type="String" />
/// </signature>
var result = "";
if (typeof separate === "undefined") {
separate = false;
}
for (var i = 0; i < bytes.length; i++) {
if (separate && (i % 4 === 0) && i !== 0) {
result += "-";
}
var hexval = bytes[i].toString(16).toUpperCase();
// Add a leading zero if needed.
if (hexval.length === 1) {
result += "0";
}
result += hexval;
}
return result;
}
function bytesToInt32(bytes, index) {
/// <summary>
/// Converts four bytes to a 32-bit int
/// </summary>
/// <param name="bytes">The bytes to convert</param>
/// <param name="index" optional="true">Optional starting point</param>
/// <returns type="Number">32-bit number</returns>
index = (index || 0);
return (bytes[index] << 24) |
(bytes[index + 1] << 16) |
(bytes[index + 2] << 8) |
bytes[index + 3];
}
function stringToBytes(messageString) {
/// <signature>
/// <summary>Converts a String to an Array of byte values (0-255)</summary>
/// <param name="messageString" type="String"/>
/// <returns type="Array" />
/// </signature>
var bytes = new Array(messageString.length);
for (var i = 0; i < bytes.length; i++) {
bytes[i] = messageString.charCodeAt(i);
}
return bytes;
}
function hexToBytesArray(hexString) {
/// <signature>
/// <summary>Converts a Hex-String to an Array of byte values (0-255)</summary>
/// <param name="hexString" type="String"/>
/// <returns type="Array" />
/// </signature>
hexString = hexString.replace(/\-/g, "");
var result = [];
while (hexString.length >= 2) {
result.push(parseInt(hexString.substring(0, 2), 16));
hexString = hexString.substring(2, hexString.length);
}
return result;
}
function clone(object) {
/// <signature>
/// <summary>Creates a shallow clone of an Object</summary>
/// <param name="object" type="Object"/>
/// <returns type="Object" />
/// </signature>
var newObject = {};
for (var propertyName in object) {
if (object.hasOwnProperty(propertyName)) {
newObject[propertyName] = object[propertyName];
}
}
return newObject;
}
function unpackData(base64String, arraySize, toUint32s) {
/// <signature>
/// <summary>Unpacks Base64 encoded data into arrays of data.</summary>
/// <param name="base64String" type="String">Base64 encoded data</param>
/// <param name="arraySize" type="Number" optional="true">Break data into sub-arrays of a given length</param>
/// <param name="toUint32s" type="Boolean" optional="true">Treat data as 32-bit data instead of byte data</param>
/// <returns type="Array" />
/// </signature>
var bytes = base64ToBytes(base64String),
data = [],
i;
if (isNaN(arraySize)) {
return bytes;
} else {
for (i = 0; i < bytes.length; i += arraySize) {
data.push(bytes.slice(i, i + arraySize));
}
}
if (toUint32s) {
for (i = 0; i < data.length; i++) {
data[i] = (data[i][0] << 24) + (data[i][1] << 16) + (data[i][2] << 8) + data[i][3];
}
}
return data;
}
function int32ToBytes(int32) {
/// <signature>
/// <summary>Converts a 32-bit number to an Array of 4 bytes</summary>
/// <param name="int32" type="Number">32-bit number</param>
/// <returns type="Array" />
/// </signature>
return [(int32 >>> 24) & 255, (int32 >>> 16) & 255, (int32 >>> 8) & 255, int32 & 255];
}
function int32ArrayToBytes(int32Array) {
/// <signature>
/// <summary>Converts an Array 32-bit numbers to an Array bytes</summary>
/// <param name="int32Array" type="Array">Array of 32-bit numbers</param>
/// <returns type="Array" />
/// </signature>
var result = [];
for (var i = 0; i < int32Array.length; i++) {
result = result.concat(int32ToBytes(int32Array[i]));
}
return result;
}
function xorVectors(a, b) {
/// <signature>
/// <summary>Exclusive OR (XOR) two arrays.</summary>
/// <param name="a" type="Array">Input array.</param>
/// <param name="b" type="Array">Input array.</param>
/// <returns type="Array">XOR of the two arrays. The length is minimum of the two input array lengths.</returns>
/// </signature>
var length = Math.min(a.length, b.length),
res = new Array(length);
for (var i = 0 ; i < length ; i += 1) {
res[i] = a[i] ^ b[i];
}
return res;
}
function getVector(length, fillValue) {
/// <signature>
/// <summary>Get an array filled with zeroes (or optional fillValue.)</summary>
/// <param name="length" type="Number">Requested array length.</param>
/// <param name="fillValue" type="Number" optional="true"></param>
/// <returns type="Array"></returns>
/// </signature>
// Use a default value of zero
fillValue || (fillValue = 0);
var res = new Array(length);
for (var i = 0; i < length; i += 1) {
res[i] = fillValue;
}
return res;
}
function toArray(typedArray) {
/// <signature>
/// <summary>Converts a UInt8Array to a regular JavaScript Array</summary>
/// <param name="typedArray" type="UInt8Array"></param>
/// <returns type="Array"></returns>
/// </signature>
// If undefined or null return an empty array
if (!typedArray) {
return [];
}
// If already an Array return it
if (typedArray.pop) {
return typedArray;
}
// If it's an ArrayBuffer, convert it to a Uint8Array first
if (typedArray.isView || getObjectType(typedArray) === "ArrayBuffer") {
typedArray = new Uint8Array(typedArray);
}
// A single element array will cause a new Array to be created with the length
// equal to the value of the single element. Not what we want.
// We'll return a new single element array with the single value.
return (typedArray.length === 1) ? [typedArray[0]] : Array.apply(null, typedArray);
}
function padEnd(array, value, finalLength) {
/// <signature>
/// <summary>Pads the end of an array with a specified value</summary>
/// <param name="array" type="Array"></param>
/// <param name="value" type="Number">The value to pad to the array</param>
/// <param name="finalLength" type="Number">The final resulting length with padding</param>
/// <returns type="Array"></returns>
/// </signature>
while (array.length < finalLength) {
array.push(value);
}
return array;
}
function padFront(array, value, finalLength) {
/// <signature>
/// <summary>Pads the front of an array with a specified value</summary>
/// <param name="array" type="Array"></param>
/// <param name="value" type="Number">The value to pad to the array</param>
/// <param name="finalLength" type="Number">The final resulting length with padding</param>
/// <returns type="Array"></returns>
/// </signature>
while (array.length < finalLength) {
array.unshift(value);
}
return array;
}
function arraysEqual(array1, array2) {
/// <signature>
/// <summary>Checks if two Arrays are equal by comparing their values.</summary>
/// <param name="array1" type="Array"></param>
/// <param name="array2" type="Array"></param>
/// <returns type="Array"></returns>
/// </signature>
var result = true;
if (array1.length !== array2.length) {
result = false;
}
for (var i = 0; i < array1.length; i++) {
if (array1[i] !== array2[i]) {
result = false;
}
}
return result;
}
function verifyByteArray(array) {
/// <signature>
/// <summary>Verify that an Array contains only byte values (0-255)</summary>
/// <param name="array" type="Array"></param>
/// <returns type="Boolean">Returns true if all values are 0-255</returns>
/// </signature>
if (getObjectType(array) !== "Array") {
return false;
}
var element;
for (var i = 0; i < array.length; i++) {
element = array[i];
if (isNaN(element) || element < 0 || element > 255) {
return false;
}
}
return true;
}
return {
toBase64: toBase64,
base64ToString: base64ToString,
base64ToBytes: base64ToBytes,
getObjectType: getObjectType,
bytesToHexString: bytesToHexString,
bytesToInt32: bytesToInt32,
stringToBytes: stringToBytes,
unpackData: unpackData,
hexToBytesArray: hexToBytesArray,
int32ToBytes: int32ToBytes,
int32ArrayToBytes: int32ArrayToBytes,
toArray: toArray,
arraysEqual: arraysEqual,
clone: clone,
xorVectors: xorVectors,
padEnd: padEnd,
padFront: padFront,
getVector: getVector,
verifyByteArray: verifyByteArray
};
})();
var msrcryptoWorker = (function () {
// If we're running in a webworker we need to postMessage to return our result
// otherwise just return the value as normal.
function returnResult(result) {
if (runningInWorkerInstance) {
self.postMessage(result);
}
return result;
}
return {
jsCryptoRunner: function ( e) {
var operation = e.data.operationType;
var result;
if (!operations.exists(operation, e.data.algorithm.name)) {
throw new Error("unregistered algorithm.");
}
var func = operations[operation][e.data.algorithm.name];
var p = e.data;
if (p.operationSubType === "process") {
func(p);
result = returnResult({ type: "process" });
} else {
result = returnResult(func(p));
}
return result;
}
};
})();
// If this is running in a webworker we need self.onmessage to receive messages from
// the calling script.
// If we are in 'synchronous mode' (everything running in one script)
// we don't want to override self.onmessage.
if (runningInWorkerInstance) {
self.onmessage = function ( e) {
// When this worker first gets instantiated we will receive seed data
// for this workers prng.
if (e.data.prngSeed) {
var entropy = e.data.prngSeed;
msrcryptoPseudoRandom.init(entropy);
return;
}
// Process the crypto operation
msrcryptoWorker.jsCryptoRunner(e);
};
}
var msrcryptoJwk = (function () {
var utils = msrcryptoUtilities;
function stringToArray(stringData) {
var result = [];
for (var i = 0; i < stringData.length; i++) {
result[i] = stringData.charCodeAt(i);
}
if (result[result.length - 1] === 0) {
result.pop();
}
return result;
}
function getKeyType(keyHandle) {
var algType = keyHandle.algorithm.name.slice(0, 3).toLowerCase();
if (algType === "rsa") {
return "RSA";
}
if (algType === "ecd") {
return "EC";
}
return "oct";
}
var algorithmMap = {
hmac : function(algorithm) {
return "HS" + algorithm.hash.name.substring(algorithm.hash.name.indexOf('-') + 1);
},
"aes-cbc" : function(algorithm) {
return "A" + algorithm.length.toString() + "CBC";
},
"aes-gcm" : function(algorithm) {
return "A" + algorithm.length.toString() + "GCM";
},
"rsaes-pkcs1-v1_5": function (algorithm) {
return "RSA1_5";
},
"rsassa-pkcs1-v1_5": function (algorithm) {
return "RS" + algorithm.hash.name.substring(algorithm.hash.name.indexOf('-') + 1);
},
"rsa-oaep": function (algorithm) {
return "RS-OAEP-" + algorithm.hash.name.substring(algorithm.hash.name.indexOf('-') + 1);
},
"rsa-pss": function (algorithm) {
return "PS" + algorithm.hash.name.substring(algorithm.hash.name.indexOf('-') + 1);
},
"ecdsa": function (algorithm) {
return "EC-" + algorithm.namedCurve.substring(algorithm.namedCurve.indexOf('-') + 1);
},
"ecdh": function (algorithm) {
return "EC-" + algorithm.namedCurve.substring(algorithm.namedCurve.indexOf('-') + 1);
}
};
function keyToJwk(keyHandle, keyData) {
var key = {};
key.kty = getKeyType(keyHandle);
key.ext = keyHandle.extractable;
key.alg = algorithmMap[keyHandle.algorithm.name.toLowerCase()](keyHandle.algorithm);
key.key_ops = keyHandle.keyUsage;
// Using .pop to determine if a property value is an array.
if (keyData.pop) {
key.k = utils.toBase64(keyData, true);
} else {
// Convert the base64Url properties to byte arrays
for (var property in keyData) {
if (keyData[property].pop) {
key[property] = utils.toBase64(keyData[property], true);
}
}
}
if (keyHandle.algorithm.namedCurve) {
key["crv"] = keyHandle.algorithm.namedCurve;
}
return key;
}
function keyToJwkOld(keyHandle, keyData) {
var key = {};
key.kty = getKeyType(keyHandle);
key.extractable = keyHandle.extractable;
// Using .pop to determine if a property value is an array.
if (keyData.pop) {
key.k = utils.toBase64(keyData, true);
} else {
// Convert the base64Url properties to byte arrays
for (var property in keyData) {
if (keyData[property].pop) {
key[property] = utils.toBase64(keyData[property], true);
}
}
}
if (keyHandle.algorithm.namedCurve) {
key["crv"] = keyHandle.algorithm.namedCurve;
}
var stringData = JSON.stringify(key, null, '\t');
return stringToArray(stringData);
}
// 'jwkKeyData' is an array of bytes. Each byte is a charCode for a json key string
function jwkToKey(keyData, algorithm, propsToArray) {
// Convert the json string to an object
var jsonKeyObject = JSON.parse(JSON.stringify(keyData)); //JSON.parse(jsonString);
// Convert the base64url encoded properties to byte arrays
for (var i = 0; i < propsToArray.length; i += 1) {
var propValue = jsonKeyObject[propsToArray[i]];
if (propValue) {
jsonKeyObject[propsToArray[i]] =
utils.base64ToBytes(propValue);
}
}
return jsonKeyObject;
}
return {
keyToJwkOld: keyToJwkOld,
keyToJwk: keyToJwk,
jwkToKey: jwkToKey
};
})();
function msrcryptoMath() {
// 'number' of bits per digit. Must be even.
var DIGIT_BITS = 24;
// 'number' of bytes per digit.
var DIGIT_NUM_BYTES = Math.floor(DIGIT_BITS / 8);
// digit mask.
var DIGIT_MASK = (1 << DIGIT_BITS) - 1;
// digit base.
var DIGIT_BASE = (1 << DIGIT_BITS);
// max digit value, unsigned
var DIGIT_MAX = DIGIT_MASK;
// Construct scaler for DIGIT_NUM_BYTES, so I don't have to multiply in the loop
var DIGIT_SCALER = [1, 256];
for (var i = 2; i <= DIGIT_NUM_BYTES; i++) {
DIGIT_SCALER[i] = DIGIT_SCALER[i - 1] * 256;
}
// Number of trailing zero bits in numbers 0..15 (4 bits). [0] is for 0, [15] is for 15.
var Zero = [0];
var One = [1];
// Create an array, mimics the constructors for typed arrays.
function createArray( parameter) {
var i, array = null;
if (!arguments.length || typeof arguments[0] === "number") {
// A number.
array = new Array(parameter);
for (i = 0; i < parameter; i += 1) {
array[i] = 0;
}
} else if (typeof arguments[0] === "object") {
// An array or other index-able object
array = new Array(parameter.length);
for (i = 0; i < parameter.length; i += 1) {
array[i] = parameter[i];
}
}
return array;
}
function swapEndianness(bytes) {
/// <summary>Swap big endian bytes to little endian bytes.</summary>
/// <param name="bytes" type="Bytes">UInt8Array - representing a big-integer.</param>
/// <returns type="Bytes">UInt8Array - the number with endianness swapped.</returns>
var out = new Array(bytes.length);
var i = 0;
while (i < bytes.length) {
out[i] = bytes[bytes.length - i - 1];
i += 1;
}
return out;
}
function stringToDigits(number, radix) {
/// <summary>Parse a String in a given base into a little endian digit array.</summary>
/// <param name="number" type="String">Input unsigned integer in a string.</param>
/// <param name="radix" optional="true" integer="true">
/// <![CDATA[ Radix of the input. Must be >=2 and <=36. Default = 10. ]]>
/// </param>
/// <returns type="Array">Array of digits in little endian; [0] is LSW.</returns>
// skip leading and trailing whitespace.
number = number.replace(/^\s+|\s+$/g, '');
var num = [0];
var buffer = [0];
radix = radix || 10; // default radix is 10
for (var i = 0; i < number.length; i += 1) {
// Extract character
var char = parseInt(number[i], radix);
if (isNaN(char)) {
throw new Error("Failed to convert string to integer in radix " + radix.toString());
}
// 'buffer' = 'num' * 'radix'
multiply(num, radix, buffer);
// 'num' = 'buffer' + 'char'
add(buffer, [ char], num);
normalizeDigitArray(num);
}
return num;
}
function digitsToString(digits, radix) {
/// <summary>Convert a big-endian byte array to a number in string in radix.</summary>
/// <param name="digits" type="Digits">A big integer as a little-endian digit array.</param>
/// <param name="radix" optional="true" integer="true">Radix from 2 to 26. Default = 10.</param>
/// <returns type="String">The number in base radix as a string.</returns>
radix = radix || 10;
if (DIGIT_BASE <= radix) {
throw new Error("DIGIT_BASE is smaller than RADIX; cannot convert.");
}
var wordLength = digits.length;
var quotient = [];
var remainder = [];
var temp1 = [];
var temp2 = [];
var divisor = [];
var a = [];
var i;
// Find the largest divisor that fits in a digit in radix
//divisor[0] = 10000; // Largest power of ten fitting in a digit
var sb = "";
var pad = "0";
divisor[0] = radix;
while (Math.floor(DIGIT_BASE / divisor[0]) >= radix) {
divisor[0] = divisor[0] * radix;
pad = pad.concat("0");
}
for (i = 0; i < wordLength; i += 1) {
a[i] = digits[i];
}
do {
var allZeros = true;
for (i = 0; i < a.length; i += 1) {
if (a[i] !== 0) {
allZeros = false;
break;
}
}
if (allZeros) {
break;
}
divRem(a, divisor, quotient, remainder, temp1, temp2);
normalizeDigitArray(quotient, a.length, true);
var newDigits = remainder[0].toString(radix);
sb = pad.substring(0, pad.length - newDigits.length) + newDigits + sb;
var swap = a;
a = quotient;
quotient = swap;
} while (true);
// Trim leading zeros
while (sb.length !== 0 && sb[0] === "0") {