forked from square/js-jose
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathjose.js
1712 lines (1531 loc) · 48.4 KB
/
jose.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
(function(exports, crypto, Promise, Error, Uint8Array, undefined){
"use strict";
// supporting Safari and its vendor prefix
if(!crypto.subtle) crypto.subtle = crypto.webkitSubtle;
/*-
* Copyright 2014 Square Inc.
*
* 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 Jose = {};
/**
* Javascript Object Signing and Encryption library.
*
* @author Alok Menghrajani <[email protected]>
*/
/**
* Initializes a JoseJWE object.
*/
var JoseJWE = {};
/**
* Initializes a JoseJWS object.
*/
var JoseJWS = {};
/**
* Checks if we have all the required APIs.
*
* It might make sense to take a Cryptographer and delegate some of the checks
* to the cryptographer. I however wanted to keep things simple, so I put all
* the checks here for now.
*
* This list is generated manually and needs to be kept up-to-date.
*
* Casual testing shows that:
* - things work in Chrome 40.0.2214.115
* - things work in Firefox 35.0.1
* - Safari 7.1.3 doesn't support JWK keys.
* - Internet Explorer doesn't support Promises.
*
* Note: We don't check if the browser supports specific crypto operations.
* I.e. it's possible for this function to return true, but encryption or
* decryption to subsequently fail because the browser does not support a
* given encryption, decryption, key wrapping, key unwrapping or hmac
* operation.
*
* @return bool
*/
Jose.caniuse = function() {
var r = true;
// Promises/A+ (https://promisesaplus.com/)
r = r && (typeof Promise == "function");
r = r && (typeof Promise.reject == "function");
r = r && (typeof Promise.prototype.then == "function");
r = r && (typeof Promise.all == "function");
// Crypto (http://www.w3.org/TR/WebCryptoAPI/)
r = r && (typeof crypto == "object");
r = r && (typeof crypto.subtle == "object");
r = r && (typeof crypto.getRandomValues == "function");
r = r && (typeof crypto.subtle.importKey == "function");
r = r && (typeof crypto.subtle.generateKey == "function");
r = r && (typeof crypto.subtle.exportKey == "function");
r = r && (typeof crypto.subtle.wrapKey == "function");
r = r && (typeof crypto.subtle.unwrapKey == "function");
r = r && (typeof crypto.subtle.encrypt == "function");
r = r && (typeof crypto.subtle.decrypt == "function");
r = r && (typeof crypto.subtle.sign == "function");
// ArrayBuffer (http://people.mozilla.org/~jorendorff/es6-draft.html#sec-arraybuffer-constructor)
r = r && (typeof ArrayBuffer == "function");
r = r && (typeof Uint8Array == "function" || typeof Uint8Array == "object"); // Safari uses "object"
r = r && (typeof Uint32Array == "function" || typeof Uint32Array == "object"); // Safari uses "object"
// skipping Uint32Array.prototype.buffer because https://people.mozilla.org/~jorendorff/es6-draft.html#sec-properties-of-the-%typedarrayprototype%-object
// JSON (http://www.ecma-international.org/ecma-262/5.1/#sec-15.12.3)
r = r && (typeof JSON == "object");
r = r && (typeof JSON.parse == "function");
r = r && (typeof JSON.stringify == "function");
// Base64 (http://www.w3.org/TR/html5/webappapis.html#dom-windowbase64-atob)
r = r && (typeof atob == "function");
r = r && (typeof btoa == "function");
// skipping Array functions (map, join, push, length, etc.)
// skipping String functions (split, charCodeAt, fromCharCode, replace, etc.)
// skipping regexp.test and parseInt
return r;
};
/**
* Feel free to override this function.
*/
Jose.assert = function(expr, msg) {
if (!expr) {
throw new Error(msg);
}
};
exports.Jose = Jose;
exports.JoseJWE = JoseJWE;
exports.JoseJWS = JoseJWS;
/*-
* Copyright 2014 Square Inc.
*
* 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.
*/
/**
* The WebCryptographer uses http://www.w3.org/TR/WebCryptoAPI/ to perform
* various crypto operations. In theory, this should help build the library with
* different underlying crypto APIs. I'm however unclear if we'll run into code
* duplication or callback vs Promise based API issues.
*/
var WebCryptographer = function() {
var that = this;
that.setKeyEncryptionAlgorithm("RSA-OAEP");
that.setContentEncryptionAlgorithm("A256GCM");
that.setContentSignAlgorithm("RS256");
};
Jose.WebCryptographer = WebCryptographer;
/**
* Overrides the default key encryption algorithm
* @param alg string
*/
WebCryptographer.prototype.setKeyEncryptionAlgorithm = function(alg) {
this.key_encryption = getCryptoConfig(alg);
};
WebCryptographer.prototype.getKeyEncryptionAlgorithm = function() {
return this.key_encryption.jwe_name;
};
/**
* Overrides the default content encryption algorithm
* @param alg string
*/
WebCryptographer.prototype.setContentEncryptionAlgorithm = function(alg) {
this.content_encryption = getCryptoConfig(alg);
};
WebCryptographer.prototype.getContentEncryptionAlgorithm = function() {
return this.content_encryption.jwe_name;
};
/**
* Overrides the default content sign algorithm
* @param alg string
*/
WebCryptographer.prototype.setContentSignAlgorithm = function(alg) {
this.content_sign = getSignConfig(alg);
};
WebCryptographer.prototype.getContentSignAlgorithm = function() {
return this.content_sign.jwa_name;
};
/**
* Generates an IV.
* This function mainly exists so that it can be mocked for testing purpose.
*
* @return Uint8Array with random bytes
*/
WebCryptographer.prototype.createIV = function() {
var iv = new Uint8Array(new Array(this.content_encryption.iv_bytes));
return crypto.getRandomValues(iv);
};
/**
* Creates a random content encryption key.
* This function mainly exists so that it can be mocked for testing purpose.
*
* @return Promise<CryptoKey>
*/
WebCryptographer.prototype.createCek = function() {
var hack = getCekWorkaround(this.content_encryption);
return crypto.subtle.generateKey(hack.id, true, hack.enc_op);
};
WebCryptographer.prototype.wrapCek = function(cek, key) {
return crypto.subtle.wrapKey("raw", cek, key, this.key_encryption.id);
};
WebCryptographer.prototype.unwrapCek = function(cek, key) {
var that = this;
var hack = getCekWorkaround(that.content_encryption);
var extractable = (that.content_encryption.specific_cek_bytes > 0);
var key_encryption = that.key_encryption.id;
return crypto.subtle.unwrapKey("raw", cek, key, key_encryption, hack.id, extractable, hack.dec_op);
};
/**
* Returns algorithm and operation needed to create a CEK.
*
* In some cases, e.g. A128CBC-HS256, the CEK gets split into two keys. The Web
* Crypto API does not allow us to generate an arbitrary number of bytes and
* then create a CryptoKey without any associated algorithm. We therefore piggy
* back on AES-CBS and HMAC which allows the creation of CEKs of size 16, 32, 64
* and 128 bytes.
*/
var getCekWorkaround = function(alg) {
var len = alg.specific_cek_bytes;
if (len) {
if (len == 16) {
return {id: {name: "AES-CBC", length: 128}, enc_op: ["encrypt"], dec_op: ["decrypt"]};
} else if (len == 32) {
return {id: {name: "AES-CBC", length: 256}, enc_op: ["encrypt"], dec_op: ["decrypt"]};
} else if (len == 64) {
return {id: {name: "HMAC", hash: {name: "SHA-256"}}, enc_op: ["sign"], dec_op: ["verify"]};
} else if (len == 128) {
return {id: {name: "HMAC", hash: {name: "SHA-384"}}, enc_op: ["sign"], dec_op: ["verify"]};
} else {
Jose.assert(false, "getCekWorkaround: invalid len");
}
}
return {id: alg.id, enc_op: ["encrypt"], dec_op: ["decrypt"]};
};
/**
* Encrypts plain_text with cek.
*
* @param iv Uint8Array
* @param aad Uint8Array
* @param cek_promise Promise<CryptoKey>
* @param plain_text Uint8Array
* @return Promise<json>
*/
WebCryptographer.prototype.encrypt = function(iv, aad, cek_promise, plain_text) {
var config = this.content_encryption;
if (iv.length != config.iv_bytes) {
return Promise.reject(Error("invalid IV length"));
}
if (config.auth.aead) {
var tag_bytes = config.auth.tag_bytes;
var enc = {
name: config.id.name,
iv: iv,
additionalData: aad,
tagLength: tag_bytes * 8
};
return cek_promise.then(function(cek) {
return crypto.subtle.encrypt(enc, cek, plain_text).then(function(cipher_text) {
var offset = cipher_text.byteLength - tag_bytes;
return {
cipher: cipher_text.slice(0, offset),
tag: cipher_text.slice(offset)
};
});
});
} else {
var keys = splitKey(config, cek_promise, ["encrypt"]);
var mac_key_promise = keys[0];
var enc_key_promise = keys[1];
// Encrypt the plain text
var cipher_text_promise = enc_key_promise.then(function(enc_key) {
var enc = {
name: config.id.name,
iv: iv
};
return crypto.subtle.encrypt(enc, enc_key, plain_text);
});
// compute MAC
var mac_promise = cipher_text_promise.then(function(cipher_text) {
return truncatedMac(
config,
mac_key_promise,
aad,
iv,
cipher_text);
});
return Promise.all([cipher_text_promise, mac_promise]).then(function(all) {
var cipher_text = all[0];
var mac = all[1];
return {
cipher: cipher_text,
tag: mac
};
});
}
};
/**
* Decrypts cipher_text with cek. Validates the tag.
*
* @param cek_promise Promise<CryptoKey>
* @param aad protected header
* @param iv IV
* @param cipher_text text to be decrypted
* @param tag to be verified
* @return Promise<string>
*/
WebCryptographer.prototype.decrypt = function(cek_promise, aad, iv, cipher_text, tag) {
/**
* Compares two Uint8Arrays in constant time.
*
* @return Promise<void>
*/
var compare = function(config, mac_key_promise, arr1, arr2) {
Jose.assert(arr1 instanceof Uint8Array, "compare: invalid input");
Jose.assert(arr2 instanceof Uint8Array, "compare: invalid input");
return mac_key_promise.then(function(mac_key) {
var hash1 = crypto.subtle.sign(config.auth.id, mac_key, arr1);
var hash2 = crypto.subtle.sign(config.auth.id, mac_key, arr2);
return Promise.all([hash1, hash2]).then(function(all) {
var hash1 = new Uint8Array(all[0]);
var hash2 = new Uint8Array(all[1]);
if (hash1.length != hash2.length) {
throw new Error("compare failed");
}
for (var i = 0; i < hash1.length; i++) {
if (hash1[i] != hash2[i]) {
throw new Error("compare failed");
}
}
return Promise.accept(null);
});
});
};
if (iv.length != this.content_encryption.iv_bytes) {
return Promise.reject(Error("decryptCiphertext: invalid IV"));
}
var config = this.content_encryption;
if (config.auth.aead) {
var dec = {
name: config.id.name,
iv: iv,
additionalData: aad,
tagLength: config.auth.tag_bytes * 8
};
return cek_promise.then(function(cek) {
var buf = Utils.arrayBufferConcat(cipher_text, tag);
return crypto.subtle.decrypt(dec, cek, buf);
});
} else {
var keys = splitKey(config, cek_promise, ["decrypt"]);
var mac_key_promise = keys[0];
var enc_key_promise = keys[1];
// Validate the MAC
var mac_promise = truncatedMac(
config,
mac_key_promise,
aad,
iv,
cipher_text);
return Promise.all([enc_key_promise, mac_promise]).then(function(all) {
var enc_key = all[0];
var mac = all[1];
return compare(config, mac_key_promise, new Uint8Array(mac), tag).then(function() {
var dec = {
name: config.id.name,
iv: iv
};
return crypto.subtle.decrypt(dec, enc_key, cipher_text);
}).catch(function(err) {
console.log(err);
return Promise.reject(Error("decryptCiphertext: MAC failed."));
});
});
}
};
/**
* Signs plain_text.
*
* @param aad json
* @param key_promise Promise<CryptoKey>
* @param payload String or json
* @return Promise<ArrayBuffer>
*/
WebCryptographer.prototype.sign = function(aad, payload, key_promise) {
var config = this.content_sign;
if (aad.alg) {
config = getSignConfig(aad.alg);
}
// Encrypt the plain text
return key_promise.then(function(key) {
return crypto.subtle.sign(config.id, key, Utils.arrayFromString(Utils.Base64Url.encode(JSON.stringify(aad)) + '.' + Utils.Base64Url.encodeArray(payload)));
});
};
/**
* Verify JWS.
*
* @param payload Base64Url encoded payload
* @param aad String Base64Url encoded JSON representation of the protected JWS header
* @param signature Uint8Array containing the signature
* @param key_promise Promise<CryptoKey>
* @param key_id value of the kid JoseHeader, it'll be passed as part of the result to the returned promise
* @return Promise<json>
*/
WebCryptographer.prototype.verify = function(aad, payload, signature, key_promise, key_id) {
var config = this.content_sign;
return key_promise.then(function(key) {
config = getSignConfig(getJwaNameForSignKey(key));
return crypto.subtle.verify(config.id, key, signature, Utils.arrayFromString(aad + "." + payload)).then(function(res) {
return {kid: key_id, verified: res};
});
});
};
Jose.WebCryptographer.keyId = function(rsa_key) {
return Utils.sha256(rsa_key.n + "+" + rsa_key.d);
};
/**
* Splits a CEK into two pieces: a MAC key and an ENC key.
*
* This code is structured around the fact that the crypto API does not provide
* a way to validate truncated MACs. The MAC key is therefore always imported to
* sign data.
*
* @param config (used for key lengths & algorithms)
* @param cek_promise Promise<CryptoKey> CEK key to split
* @param purpose Array<String> usages of the imported key
* @return [Promise<mac key>, Promise<enc key>]
*/
var splitKey = function(config, cek_promise, purpose) {
// We need to split the CEK key into a MAC and ENC keys
var cek_bytes_promise = cek_promise.then(function(cek) {
return crypto.subtle.exportKey("raw", cek);
});
var mac_key_promise = cek_bytes_promise.then(function(cek_bytes) {
if (cek_bytes.byteLength * 8 != config.id.length + config.auth.key_bytes * 8) {
return Promise.reject(Error("encryptPlainText: incorrect cek length"));
}
var bytes = cek_bytes.slice(0, config.auth.key_bytes);
return crypto.subtle.importKey("raw", bytes, config.auth.id, false, ["sign"]);
});
var enc_key_promise = cek_bytes_promise.then(function(cek_bytes) {
if (cek_bytes.byteLength * 8 != config.id.length + config.auth.key_bytes * 8) {
return Promise.reject(Error("encryptPlainText: incorrect cek length"));
}
var bytes = cek_bytes.slice(config.auth.key_bytes);
return crypto.subtle.importKey("raw", bytes, config.id, false, purpose);
});
return [mac_key_promise, enc_key_promise];
};
/**
* Converts the Jose web algorithms into data which is
* useful for the Web Crypto API.
*
* length = in bits
* bytes = in bytes
*/
var getCryptoConfig = function(alg) {
switch (alg) {
// Key encryption
case "RSA-OAEP":
return {
jwe_name: "RSA-OAEP",
id: {name: "RSA-OAEP", hash: {name: "SHA-1"}}
};
case "RSA-OAEP-256":
return {
jwe_name: "RSA-OAEP-256",
id: {name: "RSA-OAEP", hash: {name: "SHA-256"}}
};
case "A128KW":
return {
jwe_name: "A128KW",
id: {name: "AES-KW", length: 128}
};
case "A256KW":
return {
jwe_name: "A256KW",
id: {name: "AES-KW", length: 256}
};
// Content encryption
case "A128CBC-HS256":
return {
jwe_name: "A128CBC-HS256",
id: {name: "AES-CBC", length: 128},
iv_bytes: 16,
specific_cek_bytes: 32,
auth: {
key_bytes: 16,
id: {name: "HMAC", hash: {name: "SHA-256"}},
truncated_bytes: 16
}
};
case "A256CBC-HS512":
return {
jwe_name: "A256CBC-HS512",
id: {name: "AES-CBC", length: 256},
iv_bytes: 16,
specific_cek_bytes: 64,
auth: {
key_bytes: 32,
id: {name: "HMAC", hash: {name: "SHA-512"}},
truncated_bytes: 32
}
};
case "A128GCM":
return {
jwe_name: "A128GCM",
id: {name: "AES-GCM", length: 128},
iv_bytes: 12,
auth: {
aead: true,
tag_bytes: 16
}
};
case "A256GCM":
return {
jwe_name: "A256GCM",
id: {name: "AES-GCM", length: 256},
iv_bytes: 12,
auth: {
aead: true,
tag_bytes: 16
}
};
default:
throw Error("unsupported algorithm: " + alg);
}
};
/**
* Computes a truncated MAC.
*
* @param config configuration
* @param mac_key_promise Promise<CryptoKey> mac key
* @param aad Uint8Array
* @param iv Uint8Array
* @param cipher_text Uint8Array
* @return Promise<buffer> truncated MAC
*/
var truncatedMac = function(config, mac_key_promise, aad, iv, cipher_text) {
return mac_key_promise.then(function(mac_key) {
var al = new Uint8Array(Utils.arrayFromInt32(aad.length * 8));
var al_full = new Uint8Array(8);
al_full.set(al, 4);
var buf = Utils.arrayBufferConcat(aad, iv, cipher_text, al_full);
return crypto.subtle.sign(config.auth.id, mac_key, buf).then(function(bytes) {
return bytes.slice(0, config.auth.truncated_bytes);
});
});
};
/**
* Converts the Jose web algorithms into data which is
* useful for the Web Crypto API.
*/
var getSignConfig = function(alg) {
switch (alg) {
case "RS256":
return {
jwa_name: "RS256",
id: {name: "RSASSA-PKCS1-v1_5", hash: {name: "SHA-256"}}
};
case "RS384":
return {
jwa_name: "RS384",
id: {name: "RSASSA-PKCS1-v1_5", hash: {name: "SHA-384"}}
};
case "RS512":
return {
jwa_name: "RS512",
id: {name: "RSASSA-PKCS1-v1_5", hash: {name: "SHA-512"}}
};
case "PS256":
return {
jwa_name: "PS256",
id: {name: "RSA-PSS", hash: {name: "SHA-256"}, saltLength: 20}
};
case "PS384":
return {
jwa_name: "PS384",
id: {name: "RSA-PSS", hash: {name: "SHA-384"}, saltLength: 20}
};
case "PS512":
return {
jwa_name: "PS512",
id: {name: "RSA-PSS", hash: {name: "SHA-512"}, saltLength: 20}
};
case "HS256":
return {
jwa_name: "HS256",
id: {name: "HMAC", hash: {name: "SHA-256"}}
};
case "HS384":
return {
jwa_name: "HS384",
id: {name: "HMAC", hash: {name: "SHA-384"}}
};
case "HS512":
return {
jwa_name: "HS512",
id: {name: "HMAC", hash: {name: "SHA-512"}}
};
case "ES256":
return {
jwa_name: "ES256",
id: {name: "ECDSA", hash: {name: "SHA-256"}}
};
case "ES384":
return {
jwa_name: "ES384",
id: {name: "ECDSA", hash: {name: "SHA-384"}}
};
case "ES512":
return {
jwa_name: "ES512",
id: {name: "ECDSA", hash: {name: "SHA-512"}}
};
default:
throw Error("unsupported algorithm: " + alg);
}
};
/**
* Returns JWA name for a given CryptoKey
* @param key CryptoKey
*/
var getJwaNameForSignKey = function(key) {
var rv = "",
sign_algo = key.algorithm.name,
hash_algo = key.algorithm.hash.name;
if(sign_algo == "RSASSA-PKCS1-v1_5") {
rv = "R";
} else if(sign_algo == "RSA-PSS") {
rv = "P";
} else {
throw new Error("unsupported sign/verify algorithm " + sign_algo);
}
if(hash_algo.indexOf("SHA-") === 0) {
rv += "S";
} else {
throw new Error("unsupported hash algorithm " + sign_algo);
}
rv += hash_algo.substring(4);
return rv;
};
/**
* Derives key usage from algorithm's name
*
* @param alg String algorithm name
* @returns {*}
*/
var getKeyUsageByAlg = function(alg) {
switch (alg) {
// signature
case "RS256":
case "RS384":
case "RS512":
case "PS256":
case "PS384":
case "PS512":
case "HS256":
case "HS384":
case "HS512":
case "ES256":
case "ES384":
case "ES512":
return {
publicKey: "verify",
privateKey: "sign"
};
// key encryption
case "RSA-OAEP":
case "RSA-OAEP-256":
case "A128KW":
case "A256KW":
return {
publicKey: "wrapKey",
privateKey: "unwrapKey"
};
default:
throw Error("unsupported algorithm: " + alg);
}
};
/*-
* Copyright 2014 Square Inc.
*
* 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.
*/
Jose.Utils = {};
var Utils = {};
/**
* Converts the output from `openssl x509 -text` or `openssl rsa -text` into a
* CryptoKey which can then be used with RSA-OAEP. Also accepts (and validates)
* JWK keys.
*
* TODO: this code probably belongs in the webcryptographer.
*
* @param rsa_key public RSA key in json format. Parameters can be base64
* encoded, strings or number (for 'e').
* @param alg String, name of the algorithm
* @return Promise<CryptoKey>
*/
Jose.Utils.importRsaPublicKey = function(rsa_key, alg) {
var jwk,
config = null,
rk,
usage;
alg = alg || rsa_key.alg || "RSA-OAEP";
usage = getKeyUsageByAlg(alg);
if (usage.publicKey == "wrapKey") {
if (!rsa_key.alg) {
rsa_key.alg = alg;
}
jwk = Utils.convertRsaKey(rsa_key, ["n", "e"]);
config = getCryptoConfig(alg);
} else {
rk = {};
for (var name in rsa_key) {
if (rsa_key.hasOwnProperty(name)) {
rk[name] = rsa_key[name];
}
}
if (!rk.alg && alg) {
rk.alg = alg;
}
config = getSignConfig(rk.alg);
jwk = Utils.convertRsaKey(rk, ["n", "e"]);
jwk.ext = true;
}
return crypto.subtle.importKey("jwk", jwk, config.id, false, [usage.publicKey]);
};
/**
* Converts the output from `openssl x509 -text` or `openssl rsa -text` into a
* CryptoKey which can then be used with RSA-OAEP and RSA. Also accepts (and validates)
* JWK keys.
*
* TODO: this code probably belongs in the webcryptographer.
*
* @param rsa_key private RSA key in json format. Parameters can be base64
* encoded, strings or number (for 'e').
* @param alg String, name of the algorithm
* @return Promise<CryptoKey>
*/
Jose.Utils.importRsaPrivateKey = function(rsa_key, alg) {
var jwk,
config,
rk,
usage;
alg = alg || rsa_key.alg || "RSA-OAEP";
usage = getKeyUsageByAlg(alg);
if (usage.privateKey == "unwrapKey") {
if (!rsa_key.alg) {
rsa_key.alg = alg;
}
jwk = Utils.convertRsaKey(rsa_key, ["n", "e", "d", "p", "q", "dp", "dq", "qi"]);
config = getCryptoConfig("RSA-OAEP");
} else {
rk = {};
for (var name in rsa_key) {
if (rsa_key.hasOwnProperty(name)) {
rk[name] = rsa_key[name];
}
}
config = getSignConfig(alg);
if (!rk.alg && alg) {
rk.alg = alg;
}
jwk = Utils.convertRsaKey(rk, ["n", "e", "d", "p", "q", "dp", "dq", "qi"]);
jwk.ext = true;
}
return crypto.subtle.importKey("jwk", jwk, config.id, false, [usage.privateKey]);
};
// Private functions
Utils.isString = function(str) {
return ((typeof(str) == "string") || (str instanceof String));
};
/**
* Takes an arrayish (an array, ArrayBuffer or Uint8Array)
* and returns an array or a Uint8Array.
*
* @param arr arrayish
* @return array or Uint8Array
*/
Utils.arrayish = function(arr) {
if (arr instanceof Array) {
return arr;
}
if (arr instanceof Uint8Array) {
return arr;
}
if (arr instanceof ArrayBuffer) {
return new Uint8Array(arr);
}
Jose.assert(false, "arrayish: invalid input");
};
/**
* Checks if an RSA key contains all the expected parameters. Also checks their
* types. Converts hex encoded strings (or numbers) to base64.
*
* @param rsa_key RSA key in json format. Parameters can be base64 encoded,
* strings or number (for 'e').
* @param parameters array<string>
* @return json
*/
Utils.convertRsaKey = function(rsa_key, parameters) {
var r = {},
alg;
// Check that we have all the parameters
var missing = [];
parameters.map(function(p) {
if (rsa_key[p] === undefined) {
missing.push(p);
}
});
if (missing.length > 0) {
Jose.assert(false, "convertRsaKey: Was expecting " + missing.join());
}
// kty is either missing or is set to "RSA"
if (rsa_key.kty !== undefined) {
Jose.assert(rsa_key.kty == "RSA", "convertRsaKey: expecting rsa_key['kty'] to be 'RSA'");
}
r.kty = "RSA";
try {
getSignConfig(rsa_key.alg);
alg = rsa_key.alg;
} catch (err) {
try {
getCryptoConfig(rsa_key.alg);
alg = rsa_key.alg;
} catch (er) {
}
}
Jose.assert(alg, "convertRsaKey: expecting rsa_key['alg'] to have a valid value");
r.alg = alg;
// note: we punt on checking key_ops
var intFromHex = function(e) {
return parseInt(e, 16);
};
for (var i = 0; i < parameters.length; i++) {
var p = parameters[i];
var v = rsa_key[p];
if (p == "e") {
if (typeof(v) == "number") {
v = Utils.Base64Url.encodeArray(Utils.stripLeadingZeros(Utils.arrayFromInt32(v)));
}
} else if (/^([0-9a-fA-F]{2}:)+[0-9a-fA-F]{2}$/.test(v)) {
var arr = v.split(":").map(intFromHex);
v = Utils.Base64Url.encodeArray(Utils.stripLeadingZeros(arr));
} else if (typeof(v) != "string") {
Jose.assert(false, "convertRsaKey: expecting rsa_key['" + p + "'] to be a string");
}
r[p] = v;
}
return r;
};
/**
* Converts a string into an array of ascii codes.
*
* @param str string
* @return Uint8Array
*/
Utils.arrayFromString = function(str) {
Jose.assert(Utils.isString(str), "arrayFromString: invalid input");
var arr = str.split('').map(function(c) {
return c.charCodeAt(0);
});
return new Uint8Array(arr);
};
/**
* Converts an array of ascii codes into a string.
*
* @param arr ArrayBuffer
* @return string
*/
Utils.stringFromArray = function(arr) {
Jose.assert(arr instanceof ArrayBuffer, "stringFromArray: invalid input");
arr = new Uint8Array(arr);
var r = '';
for (var i = 0; i < arr.length; i++) {
r += String.fromCharCode(arr[i]);
}
return r;
};
/**
* Strips leading zero in an array.
*
* @param arr arrayish
* @return array
*/
Utils.stripLeadingZeros = function(arr) {
if (arr instanceof ArrayBuffer) {
arr = new Uint8Array(arr);
}
var is_leading_zero = true;
var r = [];
for (var i = 0; i < arr.length; i++) {
if (is_leading_zero && arr[i] === 0) {
continue;
}
is_leading_zero = false;
r.push(arr[i]);
}
return r;
};
/**
* Converts a number into an array of 4 bytes (big endian).
*
* @param i number
* @return ArrayBuffer
*/
Utils.arrayFromInt32 = function(i) {
Jose.assert(typeof(i) == "number", "arrayFromInt32: invalid input");
Jose.assert(i == i | 0, "arrayFromInt32: out of range");
var buf = new Uint8Array(new Uint32Array([i]).buffer);
var r = new Uint8Array(4);
for (var j = 0; j < 4; j++) {
r[j] = buf[3 - j];
}
return r.buffer;
};