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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
|
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/renderer/webcrypto/webcrypto_impl.h"
#include <cryptohi.h>
#include <pk11pub.h>
#include <sechash.h>
#include <vector>
#include "base/lazy_instance.h"
#include "base/logging.h"
#include "content/renderer/webcrypto/webcrypto_util.h"
#include "crypto/nss_util.h"
#include "crypto/scoped_nss_types.h"
#include "crypto/secure_util.h"
#include "third_party/WebKit/public/platform/WebArrayBuffer.h"
#include "third_party/WebKit/public/platform/WebCryptoAlgorithm.h"
#include "third_party/WebKit/public/platform/WebCryptoAlgorithmParams.h"
#if defined(USE_NSS)
#include <dlfcn.h>
#endif
// At the time of this writing:
// * Windows and Mac builds ship with their own copy of NSS (3.15+)
// * Linux builds use the system's libnss, which is 3.14 on Debian (but 3.15+
// on other distros).
//
// Since NSS provides AES-GCM support starting in version 3.15, it may be
// unavailable for Linux Chrome users.
//
// * !defined(CKM_AES_GCM)
//
// This means that at build time, the NSS header pkcs11t.h is older than
// 3.15. However at runtime support may be present.
//
// * !defined(USE_NSS)
//
// This means that Chrome is being built with an embedded copy of NSS,
// which can be assumed to be >= 3.15. On the other hand if USE_NSS is
// defined, it also implies running on Linux.
//
// TODO(eroman): Simplify this once 3.15+ is required by Linux builds.
#if !defined(CKM_AES_GCM)
#define CKM_AES_GCM 0x00001087
struct CK_GCM_PARAMS {
CK_BYTE_PTR pIv;
CK_ULONG ulIvLen;
CK_BYTE_PTR pAAD;
CK_ULONG ulAADLen;
CK_ULONG ulTagBits;
};
#endif // !defined(CKM_AES_GCM)
// Signature for PK11_Encrypt and PK11_Decrypt.
typedef SECStatus
(*PK11_EncryptDecryptFunction)(
PK11SymKey*, CK_MECHANISM_TYPE, SECItem*,
unsigned char*, unsigned int*, unsigned int,
const unsigned char*, unsigned int);
// Singleton to abstract away dynamically loading libnss3.so
class AesGcmSupport {
public:
bool IsSupported() const {
return pk11_encrypt_func_ && pk11_decrypt_func_;
}
// Returns NULL if unsupported.
PK11_EncryptDecryptFunction pk11_encrypt_func() const {
return pk11_encrypt_func_;
}
// Returns NULL if unsupported.
PK11_EncryptDecryptFunction pk11_decrypt_func() const {
return pk11_decrypt_func_;
}
private:
friend struct base::DefaultLazyInstanceTraits<AesGcmSupport>;
AesGcmSupport() {
#if !defined(USE_NSS)
// Using a bundled version of NSS that is guaranteed to have this symbol.
pk11_encrypt_func_ = PK11_Encrypt;
pk11_decrypt_func_ = PK11_Decrypt;
#else
// Using system NSS libraries and PCKS #11 modules, which may not have the
// necessary function (PK11_Encrypt) or mechanism support (CKM_AES_GCM).
// If PK11_Encrypt() was successfully resolved, then NSS will support
// AES-GCM directly. This was introduced in NSS 3.15.
pk11_encrypt_func_ =
reinterpret_cast<PK11_EncryptDecryptFunction>(
dlsym(RTLD_DEFAULT, "PK11_Encrypt"));
pk11_decrypt_func_ =
reinterpret_cast<PK11_EncryptDecryptFunction>(
dlsym(RTLD_DEFAULT, "PK11_Decrypt"));
#endif
}
PK11_EncryptDecryptFunction pk11_encrypt_func_;
PK11_EncryptDecryptFunction pk11_decrypt_func_;
};
base::LazyInstance<AesGcmSupport>::Leaky g_aes_gcm_support =
LAZY_INSTANCE_INITIALIZER;
namespace content {
using webcrypto::Status;
namespace {
class SymKeyHandle : public blink::WebCryptoKeyHandle {
public:
explicit SymKeyHandle(crypto::ScopedPK11SymKey key) : key_(key.Pass()) {}
PK11SymKey* key() { return key_.get(); }
private:
crypto::ScopedPK11SymKey key_;
DISALLOW_COPY_AND_ASSIGN(SymKeyHandle);
};
class PublicKeyHandle : public blink::WebCryptoKeyHandle {
public:
explicit PublicKeyHandle(crypto::ScopedSECKEYPublicKey key)
: key_(key.Pass()) {}
SECKEYPublicKey* key() { return key_.get(); }
private:
crypto::ScopedSECKEYPublicKey key_;
DISALLOW_COPY_AND_ASSIGN(PublicKeyHandle);
};
class PrivateKeyHandle : public blink::WebCryptoKeyHandle {
public:
explicit PrivateKeyHandle(crypto::ScopedSECKEYPrivateKey key)
: key_(key.Pass()) {}
SECKEYPrivateKey* key() { return key_.get(); }
private:
crypto::ScopedSECKEYPrivateKey key_;
DISALLOW_COPY_AND_ASSIGN(PrivateKeyHandle);
};
HASH_HashType WebCryptoAlgorithmToNSSHashType(
const blink::WebCryptoAlgorithm& algorithm) {
switch (algorithm.id()) {
case blink::WebCryptoAlgorithmIdSha1:
return HASH_AlgSHA1;
case blink::WebCryptoAlgorithmIdSha224:
return HASH_AlgSHA224;
case blink::WebCryptoAlgorithmIdSha256:
return HASH_AlgSHA256;
case blink::WebCryptoAlgorithmIdSha384:
return HASH_AlgSHA384;
case blink::WebCryptoAlgorithmIdSha512:
return HASH_AlgSHA512;
default:
// Not a digest algorithm.
return HASH_AlgNULL;
}
}
CK_MECHANISM_TYPE WebCryptoHashToHMACMechanism(
const blink::WebCryptoAlgorithm& algorithm) {
switch (algorithm.id()) {
case blink::WebCryptoAlgorithmIdSha1:
return CKM_SHA_1_HMAC;
case blink::WebCryptoAlgorithmIdSha224:
return CKM_SHA224_HMAC;
case blink::WebCryptoAlgorithmIdSha256:
return CKM_SHA256_HMAC;
case blink::WebCryptoAlgorithmIdSha384:
return CKM_SHA384_HMAC;
case blink::WebCryptoAlgorithmIdSha512:
return CKM_SHA512_HMAC;
default:
// Not a supported algorithm.
return CKM_INVALID_MECHANISM;
}
}
Status AesCbcEncryptDecrypt(
CK_ATTRIBUTE_TYPE operation,
const blink::WebCryptoAlgorithm& algorithm,
const blink::WebCryptoKey& key,
const unsigned char* data,
unsigned int data_size,
blink::WebArrayBuffer* buffer) {
DCHECK_EQ(blink::WebCryptoAlgorithmIdAesCbc, algorithm.id());
DCHECK_EQ(algorithm.id(), key.algorithm().id());
DCHECK_EQ(blink::WebCryptoKeyTypeSecret, key.type());
DCHECK(operation == CKA_ENCRYPT || operation == CKA_DECRYPT);
SymKeyHandle* sym_key = reinterpret_cast<SymKeyHandle*>(key.handle());
const blink::WebCryptoAesCbcParams* params = algorithm.aesCbcParams();
if (params->iv().size() != AES_BLOCK_SIZE)
return Status::ErrorIncorrectSizeAesCbcIv();
SECItem iv_item;
iv_item.type = siBuffer;
iv_item.data = const_cast<unsigned char*>(params->iv().data());
iv_item.len = params->iv().size();
crypto::ScopedSECItem param(PK11_ParamFromIV(CKM_AES_CBC_PAD, &iv_item));
if (!param)
return Status::Error();
crypto::ScopedPK11Context context(PK11_CreateContextBySymKey(
CKM_AES_CBC_PAD, operation, sym_key->key(), param.get()));
if (!context.get())
return Status::Error();
// Oddly PK11_CipherOp takes input and output lengths as "int" rather than
// "unsigned int". Do some checks now to avoid integer overflowing.
if (data_size >= INT_MAX - AES_BLOCK_SIZE) {
// TODO(eroman): Handle this by chunking the input fed into NSS. Right now
// it doesn't make much difference since the one-shot API would end up
// blowing out the memory and crashing anyway.
return Status::ErrorDataTooLarge();
}
// PK11_CipherOp does an invalid memory access when given empty decryption
// input, or input which is not a multiple of the block size. See also
// https://bugzilla.mozilla.com/show_bug.cgi?id=921687.
if (operation == CKA_DECRYPT &&
(data_size == 0 || (data_size % AES_BLOCK_SIZE != 0))) {
return Status::Error();
}
// TODO(eroman): Refine the output buffer size. It can be computed exactly for
// encryption, and can be smaller for decryption.
unsigned int output_max_len = data_size + AES_BLOCK_SIZE;
CHECK_GT(output_max_len, data_size);
*buffer = blink::WebArrayBuffer::create(output_max_len, 1);
unsigned char* buffer_data = reinterpret_cast<unsigned char*>(buffer->data());
int output_len;
if (SECSuccess != PK11_CipherOp(context.get(),
buffer_data,
&output_len,
buffer->byteLength(),
data,
data_size)) {
return Status::Error();
}
unsigned int final_output_chunk_len;
if (SECSuccess != PK11_DigestFinal(context.get(),
buffer_data + output_len,
&final_output_chunk_len,
output_max_len - output_len)) {
return Status::Error();
}
webcrypto::ShrinkBuffer(buffer, final_output_chunk_len + output_len);
return Status::Success();
}
// Helper to either encrypt or decrypt for AES-GCM. The result of encryption is
// the concatenation of the ciphertext and the authentication tag. Similarly,
// this is the expectation for the input to decryption.
Status AesGcmEncryptDecrypt(
bool encrypt,
const blink::WebCryptoAlgorithm& algorithm,
const blink::WebCryptoKey& key,
const unsigned char* data,
unsigned int data_size,
blink::WebArrayBuffer* buffer) {
DCHECK_EQ(blink::WebCryptoAlgorithmIdAesGcm, algorithm.id());
DCHECK_EQ(algorithm.id(), key.algorithm().id());
DCHECK_EQ(blink::WebCryptoKeyTypeSecret, key.type());
if (!g_aes_gcm_support.Get().IsSupported())
return Status::ErrorUnsupported();
SymKeyHandle* sym_key = reinterpret_cast<SymKeyHandle*>(key.handle());
const blink::WebCryptoAesGcmParams* params = algorithm.aesGcmParams();
if (!params)
return Status::ErrorUnexpected();
// TODO(eroman): The spec doesn't define the default value. Assume 128 for now
// since that is the maximum tag length:
// http://www.w3.org/2012/webcrypto/track/issues/46
unsigned int tag_length_bits = 128;
if (params->hasTagLengthBits())
tag_length_bits = params->optionalTagLengthBits();
if (tag_length_bits > 128 || (tag_length_bits % 8) != 0)
return Status::ErrorInvalidAesGcmTagLength();
unsigned int tag_length_bytes = tag_length_bits / 8;
CK_GCM_PARAMS gcm_params = {0};
gcm_params.pIv =
const_cast<unsigned char*>(algorithm.aesGcmParams()->iv().data());
gcm_params.ulIvLen = algorithm.aesGcmParams()->iv().size();
gcm_params.pAAD =
const_cast<unsigned char*>(params->optionalAdditionalData().data());
gcm_params.ulAADLen = params->optionalAdditionalData().size();
gcm_params.ulTagBits = tag_length_bits;
SECItem param;
param.type = siBuffer;
param.data = reinterpret_cast<unsigned char*>(&gcm_params);
param.len = sizeof(gcm_params);
unsigned int buffer_size = 0;
// Calculate the output buffer size.
if (encrypt) {
// TODO(eroman): This is ugly, abstract away the safe integer arithmetic.
if (data_size > (UINT_MAX - tag_length_bytes))
return Status::ErrorDataTooLarge();
buffer_size = data_size + tag_length_bytes;
} else {
// TODO(eroman): In theory the buffer allocated for the plain text should be
// sized as |data_size - tag_length_bytes|.
//
// However NSS has a bug whereby it will fail if the output buffer size is
// not at least as large as the ciphertext:
//
// https://bugzilla.mozilla.org/show_bug.cgi?id=%20853674
//
// From the analysis of that bug it looks like it might be safe to pass a
// correctly sized buffer but lie about its size. Since resizing the
// WebCryptoArrayBuffer is expensive that hack may be worth looking into.
buffer_size = data_size;
}
*buffer = blink::WebArrayBuffer::create(buffer_size, 1);
unsigned char* buffer_data = reinterpret_cast<unsigned char*>(buffer->data());
PK11_EncryptDecryptFunction func =
encrypt ? g_aes_gcm_support.Get().pk11_encrypt_func() :
g_aes_gcm_support.Get().pk11_decrypt_func();
unsigned int output_len = 0;
SECStatus result = func(sym_key->key(), CKM_AES_GCM, ¶m,
buffer_data, &output_len, buffer->byteLength(),
data, data_size);
if (result != SECSuccess)
return Status::Error();
// Unfortunately the buffer needs to be shrunk for decryption (see the NSS bug
// above).
webcrypto::ShrinkBuffer(buffer, output_len);
return Status::Success();
}
CK_MECHANISM_TYPE WebCryptoAlgorithmToGenMechanism(
const blink::WebCryptoAlgorithm& algorithm) {
switch (algorithm.id()) {
case blink::WebCryptoAlgorithmIdAesCbc:
case blink::WebCryptoAlgorithmIdAesGcm:
case blink::WebCryptoAlgorithmIdAesKw:
return CKM_AES_KEY_GEN;
case blink::WebCryptoAlgorithmIdHmac:
return WebCryptoHashToHMACMechanism(algorithm.hmacKeyParams()->hash());
default:
return CKM_INVALID_MECHANISM;
}
}
// Converts a (big-endian) WebCrypto BigInteger, with or without leading zeros,
// to unsigned long.
bool BigIntegerToLong(const uint8* data,
unsigned int data_size,
unsigned long* result) {
// TODO(padolph): Is it correct to say that empty data is an error, or does it
// mean value 0? See https://www.w3.org/Bugs/Public/show_bug.cgi?id=23655
if (data_size == 0)
return false;
*result = 0;
for (size_t i = 0; i < data_size; ++i) {
size_t reverse_i = data_size - i - 1;
if (reverse_i >= sizeof(unsigned long) && data[i])
return false; // Too large for a long.
*result |= data[i] << 8 * reverse_i;
}
return true;
}
bool IsAlgorithmRsa(const blink::WebCryptoAlgorithm& algorithm) {
return algorithm.id() == blink::WebCryptoAlgorithmIdRsaEsPkcs1v1_5 ||
algorithm.id() == blink::WebCryptoAlgorithmIdRsaOaep ||
algorithm.id() == blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5;
}
Status ImportKeyInternalRaw(
const unsigned char* key_data,
unsigned int key_data_size,
const blink::WebCryptoAlgorithm& algorithm,
bool extractable,
blink::WebCryptoKeyUsageMask usage_mask,
blink::WebCryptoKey* key) {
DCHECK(!algorithm.isNull());
blink::WebCryptoKeyType type;
switch (algorithm.id()) {
case blink::WebCryptoAlgorithmIdHmac:
case blink::WebCryptoAlgorithmIdAesCbc:
case blink::WebCryptoAlgorithmIdAesKw:
case blink::WebCryptoAlgorithmIdAesGcm:
type = blink::WebCryptoKeyTypeSecret;
break;
// TODO(bryaneyler): Support more key types.
default:
return Status::ErrorUnsupported();
}
// TODO(bryaneyler): Need to split handling for symmetric and asymmetric keys.
// Currently only supporting symmetric.
CK_MECHANISM_TYPE mechanism = CKM_INVALID_MECHANISM;
// Flags are verified at the Blink layer; here the flags are set to all
// possible operations for this key type.
CK_FLAGS flags = 0;
switch (algorithm.id()) {
case blink::WebCryptoAlgorithmIdHmac: {
const blink::WebCryptoHmacParams* params = algorithm.hmacParams();
if (!params)
return Status::ErrorUnexpected();
mechanism = WebCryptoHashToHMACMechanism(params->hash());
if (mechanism == CKM_INVALID_MECHANISM)
return Status::ErrorUnsupported();
flags |= CKF_SIGN | CKF_VERIFY;
break;
}
case blink::WebCryptoAlgorithmIdAesCbc: {
mechanism = CKM_AES_CBC;
flags |= CKF_ENCRYPT | CKF_DECRYPT;
break;
}
case blink::WebCryptoAlgorithmIdAesKw: {
mechanism = CKM_NSS_AES_KEY_WRAP;
flags |= CKF_WRAP | CKF_WRAP;
break;
}
case blink::WebCryptoAlgorithmIdAesGcm: {
if (!g_aes_gcm_support.Get().IsSupported())
return Status::ErrorUnsupported();
mechanism = CKM_AES_GCM;
flags |= CKF_ENCRYPT | CKF_DECRYPT;
break;
}
default:
return Status::ErrorUnsupported();
}
DCHECK_NE(CKM_INVALID_MECHANISM, mechanism);
DCHECK_NE(0ul, flags);
SECItem key_item = {
siBuffer,
const_cast<unsigned char*>(key_data),
key_data_size
};
crypto::ScopedPK11Slot slot(PK11_GetInternalSlot());
crypto::ScopedPK11SymKey pk11_sym_key(
PK11_ImportSymKeyWithFlags(slot.get(),
mechanism,
PK11_OriginUnwrap,
CKA_FLAGS_ONLY,
&key_item,
flags,
false,
NULL));
if (!pk11_sym_key.get())
return Status::Error();
*key = blink::WebCryptoKey::create(new SymKeyHandle(pk11_sym_key.Pass()),
type, extractable, algorithm, usage_mask);
return Status::Success();
}
Status ExportKeyInternalRaw(
const blink::WebCryptoKey& key,
blink::WebArrayBuffer* buffer) {
DCHECK(key.handle());
DCHECK(buffer);
if (!key.extractable())
return Status::ErrorKeyNotExtractable();
if (key.type() != blink::WebCryptoKeyTypeSecret)
return Status::ErrorUnexpectedKeyType();
SymKeyHandle* sym_key = reinterpret_cast<SymKeyHandle*>(key.handle());
if (PK11_ExtractKeyValue(sym_key->key()) != SECSuccess)
return Status::Error();
const SECItem* key_data = PK11_GetKeyData(sym_key->key());
if (!key_data)
return Status::Error();
*buffer = webcrypto::CreateArrayBuffer(key_data->data, key_data->len);
return Status::Success();
}
typedef scoped_ptr<CERTSubjectPublicKeyInfo,
crypto::NSSDestroyer<CERTSubjectPublicKeyInfo,
SECKEY_DestroySubjectPublicKeyInfo> >
ScopedCERTSubjectPublicKeyInfo;
// Validates an NSS KeyType against a WebCrypto algorithm. Some NSS KeyTypes
// contain enough information to fabricate a Web Crypto algorithm, which is
// returned if the input algorithm isNull(). This function indicates failure by
// returning a Null algorithm.
blink::WebCryptoAlgorithm ResolveNssKeyTypeWithInputAlgorithm(
KeyType key_type,
const blink::WebCryptoAlgorithm& algorithm_or_null) {
switch (key_type) {
case rsaKey:
// NSS's rsaKey KeyType maps to keys with SEC_OID_PKCS1_RSA_ENCRYPTION and
// according to RFCs 4055/5756 this can be used for both encryption and
// signatures. However, this is not specific enough to build a compatible
// Web Crypto algorithm, since in Web Crypto, RSA encryption and signature
// algorithms are distinct. So if the input algorithm isNull() here, we
// have to fail.
if (!algorithm_or_null.isNull() && IsAlgorithmRsa(algorithm_or_null))
return algorithm_or_null;
break;
case dsaKey:
case ecKey:
case rsaPssKey:
case rsaOaepKey:
// TODO(padolph): Handle other key types.
break;
default:
break;
}
return blink::WebCryptoAlgorithm::createNull();
}
Status ImportKeyInternalSpki(
const unsigned char* key_data,
unsigned int key_data_size,
const blink::WebCryptoAlgorithm& algorithm_or_null,
bool extractable,
blink::WebCryptoKeyUsageMask usage_mask,
blink::WebCryptoKey* key) {
DCHECK(key);
if (!key_data_size)
return Status::ErrorImportEmptyKeyData();
DCHECK(key_data);
// The binary blob 'key_data' is expected to be a DER-encoded ASN.1 Subject
// Public Key Info. Decode this to a CERTSubjectPublicKeyInfo.
SECItem spki_item = {siBuffer, const_cast<uint8*>(key_data), key_data_size};
const ScopedCERTSubjectPublicKeyInfo spki(
SECKEY_DecodeDERSubjectPublicKeyInfo(&spki_item));
if (!spki)
return Status::Error();
crypto::ScopedSECKEYPublicKey sec_public_key(
SECKEY_ExtractPublicKey(spki.get()));
if (!sec_public_key)
return Status::Error();
const KeyType sec_key_type = SECKEY_GetPublicKeyType(sec_public_key.get());
blink::WebCryptoAlgorithm algorithm =
ResolveNssKeyTypeWithInputAlgorithm(sec_key_type, algorithm_or_null);
if (algorithm.isNull())
return Status::Error();
*key = blink::WebCryptoKey::create(
new PublicKeyHandle(sec_public_key.Pass()),
blink::WebCryptoKeyTypePublic,
extractable,
algorithm,
usage_mask);
return Status::Success();
}
Status ExportKeyInternalSpki(
const blink::WebCryptoKey& key,
blink::WebArrayBuffer* buffer) {
DCHECK(key.handle());
DCHECK(buffer);
if (!key.extractable())
return Status::ErrorKeyNotExtractable();
if (key.type() != blink::WebCryptoKeyTypePublic)
return Status::ErrorUnexpectedKeyType();
PublicKeyHandle* const pub_key =
reinterpret_cast<PublicKeyHandle*>(key.handle());
const crypto::ScopedSECItem spki_der(
SECKEY_EncodeDERSubjectPublicKeyInfo(pub_key->key()));
if (!spki_der)
return Status::Error();
DCHECK(spki_der->data);
DCHECK(spki_der->len);
*buffer = webcrypto::CreateArrayBuffer(spki_der->data, spki_der->len);
return Status::Success();
}
Status ImportKeyInternalPkcs8(
const unsigned char* key_data,
unsigned int key_data_size,
const blink::WebCryptoAlgorithm& algorithm_or_null,
bool extractable,
blink::WebCryptoKeyUsageMask usage_mask,
blink::WebCryptoKey* key) {
DCHECK(key);
if (!key_data_size)
return Status::ErrorImportEmptyKeyData();
DCHECK(key_data);
// The binary blob 'key_data' is expected to be a DER-encoded ASN.1 PKCS#8
// private key info object.
SECItem pki_der = {siBuffer, const_cast<uint8*>(key_data), key_data_size};
SECKEYPrivateKey* seckey_private_key = NULL;
crypto::ScopedPK11Slot slot(PK11_GetInternalSlot());
if (PK11_ImportDERPrivateKeyInfoAndReturnKey(
slot.get(),
&pki_der,
NULL, // nickname
NULL, // publicValue
false, // isPerm
false, // isPrivate
KU_ALL, // usage
&seckey_private_key,
NULL) != SECSuccess) {
return Status::Error();
}
DCHECK(seckey_private_key);
crypto::ScopedSECKEYPrivateKey private_key(seckey_private_key);
const KeyType sec_key_type = SECKEY_GetPrivateKeyType(private_key.get());
blink::WebCryptoAlgorithm algorithm =
ResolveNssKeyTypeWithInputAlgorithm(sec_key_type, algorithm_or_null);
if (algorithm.isNull())
return Status::Error();
*key = blink::WebCryptoKey::create(
new PrivateKeyHandle(private_key.Pass()),
blink::WebCryptoKeyTypePrivate,
extractable,
algorithm,
usage_mask);
return Status::Success();
}
// -----------------------------------
// Hmac
// -----------------------------------
Status SignHmac(
const blink::WebCryptoAlgorithm& algorithm,
const blink::WebCryptoKey& key,
const unsigned char* data,
unsigned int data_size,
blink::WebArrayBuffer* buffer) {
DCHECK_EQ(blink::WebCryptoAlgorithmIdHmac, algorithm.id());
const blink::WebCryptoHmacParams* params = algorithm.hmacParams();
if (!params)
return Status::ErrorUnexpected();
SymKeyHandle* sym_key = reinterpret_cast<SymKeyHandle*>(key.handle());
DCHECK_EQ(PK11_GetMechanism(sym_key->key()),
WebCryptoHashToHMACMechanism(params->hash()));
SECItem param_item = { siBuffer, NULL, 0 };
SECItem data_item = {
siBuffer,
const_cast<unsigned char*>(data),
data_size
};
// First call is to figure out the length.
SECItem signature_item = { siBuffer, NULL, 0 };
if (PK11_SignWithSymKey(sym_key->key(),
PK11_GetMechanism(sym_key->key()),
¶m_item,
&signature_item,
&data_item) != SECSuccess) {
return Status::Error();
}
DCHECK_NE(0u, signature_item.len);
*buffer = blink::WebArrayBuffer::create(signature_item.len, 1);
signature_item.data = reinterpret_cast<unsigned char*>(buffer->data());
if (PK11_SignWithSymKey(sym_key->key(),
PK11_GetMechanism(sym_key->key()),
¶m_item,
&signature_item,
&data_item) != SECSuccess) {
return Status::Error();
}
DCHECK_EQ(buffer->byteLength(), signature_item.len);
return Status::Success();
}
Status VerifyHmac(
const blink::WebCryptoAlgorithm& algorithm,
const blink::WebCryptoKey& key,
const unsigned char* signature,
unsigned int signature_size,
const unsigned char* data,
unsigned int data_size,
bool* signature_match) {
DCHECK_EQ(blink::WebCryptoAlgorithmIdHmac, algorithm.id());
blink::WebArrayBuffer result;
Status status = SignHmac(algorithm, key, data, data_size, &result);
if (status.IsError())
return status;
// Handling of truncated signatures is underspecified in the WebCrypto
// spec, so here we fail verification if a truncated signature is being
// verified.
// See https://www.w3.org/Bugs/Public/show_bug.cgi?id=23097
*signature_match =
result.byteLength() == signature_size &&
crypto::SecureMemEqual(result.data(), signature, signature_size);
return Status::Success();
}
// -----------------------------------
// RsaEsPkcs1v1_5
// -----------------------------------
Status EncryptRsaEsPkcs1v1_5(
const blink::WebCryptoAlgorithm& algorithm,
const blink::WebCryptoKey& key,
const unsigned char* data,
unsigned int data_size,
blink::WebArrayBuffer* buffer) {
DCHECK_EQ(blink::WebCryptoAlgorithmIdRsaEsPkcs1v1_5, algorithm.id());
// RSAES encryption does not support empty input
if (!data_size)
return Status::Error();
DCHECK(data);
if (key.type() != blink::WebCryptoKeyTypePublic)
return Status::ErrorUnexpectedKeyType();
PublicKeyHandle* const public_key =
reinterpret_cast<PublicKeyHandle*>(key.handle());
const unsigned int encrypted_length_bytes =
SECKEY_PublicKeyStrength(public_key->key());
// RSAES can operate on messages up to a length of k - 11, where k is the
// octet length of the RSA modulus.
if (encrypted_length_bytes < 11 || encrypted_length_bytes - 11 < data_size)
return Status::ErrorDataTooLarge();
*buffer = blink::WebArrayBuffer::create(encrypted_length_bytes, 1);
unsigned char* const buffer_data =
reinterpret_cast<unsigned char*>(buffer->data());
if (PK11_PubEncryptPKCS1(public_key->key(),
buffer_data,
const_cast<unsigned char*>(data),
data_size,
NULL) != SECSuccess) {
return Status::Error();
}
return Status::Success();
}
Status DecryptRsaEsPkcs1v1_5(
const blink::WebCryptoAlgorithm& algorithm,
const blink::WebCryptoKey& key,
const unsigned char* data,
unsigned int data_size,
blink::WebArrayBuffer* buffer) {
DCHECK_EQ(blink::WebCryptoAlgorithmIdRsaEsPkcs1v1_5, algorithm.id());
// RSAES decryption does not support empty input
if (!data_size)
return Status::Error();
DCHECK(data);
if (key.type() != blink::WebCryptoKeyTypePrivate)
return Status::ErrorUnexpectedKeyType();
PrivateKeyHandle* const private_key =
reinterpret_cast<PrivateKeyHandle*>(key.handle());
const int modulus_length_bytes =
PK11_GetPrivateModulusLen(private_key->key());
if (modulus_length_bytes <= 0)
return Status::ErrorUnexpected();
const unsigned int max_output_length_bytes = modulus_length_bytes;
*buffer = blink::WebArrayBuffer::create(max_output_length_bytes, 1);
unsigned char* const buffer_data =
reinterpret_cast<unsigned char*>(buffer->data());
unsigned int output_length_bytes = 0;
if (PK11_PrivDecryptPKCS1(private_key->key(),
buffer_data,
&output_length_bytes,
max_output_length_bytes,
const_cast<unsigned char*>(data),
data_size) != SECSuccess) {
return Status::Error();
}
DCHECK_LE(output_length_bytes, max_output_length_bytes);
webcrypto::ShrinkBuffer(buffer, output_length_bytes);
return Status::Success();
}
// -----------------------------------
// RsaSsaPkcs1v1_5
// -----------------------------------
Status SignRsaSsaPkcs1v1_5(
const blink::WebCryptoAlgorithm& algorithm,
const blink::WebCryptoKey& key,
const unsigned char* data,
unsigned int data_size,
blink::WebArrayBuffer* buffer) {
DCHECK_EQ(blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5, algorithm.id());
if (key.type() != blink::WebCryptoKeyTypePrivate)
return Status::ErrorUnexpectedKeyType();
if (webcrypto::GetInnerHashAlgorithm(algorithm).isNull())
return Status::ErrorUnexpected();
PrivateKeyHandle* const private_key =
reinterpret_cast<PrivateKeyHandle*>(key.handle());
DCHECK(private_key);
DCHECK(private_key->key());
// Pick the NSS signing algorithm by combining RSA-SSA (RSA PKCS1) and the
// inner hash of the input Web Crypto algorithm.
SECOidTag sign_alg_tag;
switch (webcrypto::GetInnerHashAlgorithm(algorithm).id()) {
case blink::WebCryptoAlgorithmIdSha1:
sign_alg_tag = SEC_OID_PKCS1_SHA1_WITH_RSA_ENCRYPTION;
break;
case blink::WebCryptoAlgorithmIdSha224:
sign_alg_tag = SEC_OID_PKCS1_SHA224_WITH_RSA_ENCRYPTION;
break;
case blink::WebCryptoAlgorithmIdSha256:
sign_alg_tag = SEC_OID_PKCS1_SHA256_WITH_RSA_ENCRYPTION;
break;
case blink::WebCryptoAlgorithmIdSha384:
sign_alg_tag = SEC_OID_PKCS1_SHA384_WITH_RSA_ENCRYPTION;
break;
case blink::WebCryptoAlgorithmIdSha512:
sign_alg_tag = SEC_OID_PKCS1_SHA512_WITH_RSA_ENCRYPTION;
break;
default:
return Status::ErrorUnsupported();
}
crypto::ScopedSECItem signature_item(SECITEM_AllocItem(NULL, NULL, 0));
if (SEC_SignData(signature_item.get(),
data,
data_size,
private_key->key(),
sign_alg_tag) != SECSuccess) {
return Status::Error();
}
*buffer = webcrypto::CreateArrayBuffer(signature_item->data,
signature_item->len);
return Status::Success();
}
Status VerifyRsaSsaPkcs1v1_5(
const blink::WebCryptoAlgorithm& algorithm,
const blink::WebCryptoKey& key,
const unsigned char* signature,
unsigned int signature_size,
const unsigned char* data,
unsigned int data_size,
bool* signature_match) {
DCHECK_EQ(blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5, algorithm.id());
if (key.type() != blink::WebCryptoKeyTypePublic)
return Status::ErrorUnexpectedKeyType();
PublicKeyHandle* const public_key =
reinterpret_cast<PublicKeyHandle*>(key.handle());
DCHECK(public_key);
DCHECK(public_key->key());
const SECItem signature_item = {
siBuffer,
const_cast<unsigned char*>(signature),
signature_size
};
SECOidTag hash_alg_tag;
switch (webcrypto::GetInnerHashAlgorithm(algorithm).id()) {
case blink::WebCryptoAlgorithmIdSha1:
hash_alg_tag = SEC_OID_SHA1;
break;
case blink::WebCryptoAlgorithmIdSha224:
hash_alg_tag = SEC_OID_SHA224;
break;
case blink::WebCryptoAlgorithmIdSha256:
hash_alg_tag = SEC_OID_SHA256;
break;
case blink::WebCryptoAlgorithmIdSha384:
hash_alg_tag = SEC_OID_SHA384;
break;
case blink::WebCryptoAlgorithmIdSha512:
hash_alg_tag = SEC_OID_SHA512;
break;
default:
return Status::ErrorUnsupported();
}
*signature_match =
SECSuccess == VFY_VerifyDataDirect(data,
data_size,
public_key->key(),
&signature_item,
SEC_OID_PKCS1_RSA_ENCRYPTION,
hash_alg_tag,
NULL,
NULL);
return Status::Success();
}
// -----------------------------------
// Key generation
// -----------------------------------
Status GenerateRsaKeyPair(
const blink::WebCryptoAlgorithm& algorithm,
bool extractable,
blink::WebCryptoKeyUsageMask usage_mask,
blink::WebCryptoKey* public_key,
blink::WebCryptoKey* private_key) {
const blink::WebCryptoRsaKeyGenParams* const params =
algorithm.rsaKeyGenParams();
DCHECK(params);
crypto::ScopedPK11Slot slot(PK11_GetInternalKeySlot());
if (!slot)
return Status::Error();
unsigned long public_exponent;
if (!params->modulusLengthBits())
return Status::ErrorGenerateRsaZeroModulus();
if (!BigIntegerToLong(params->publicExponent().data(),
params->publicExponent().size(),
&public_exponent) || !public_exponent) {
return Status::ErrorGenerateKeyPublicExponent();
}
PK11RSAGenParams rsa_gen_params;
rsa_gen_params.keySizeInBits = params->modulusLengthBits();
rsa_gen_params.pe = public_exponent;
// Flags are verified at the Blink layer; here the flags are set to all
// possible operations for the given key type.
CK_FLAGS operation_flags;
switch (algorithm.id()) {
case blink::WebCryptoAlgorithmIdRsaEsPkcs1v1_5:
case blink::WebCryptoAlgorithmIdRsaOaep:
operation_flags = CKF_ENCRYPT | CKF_DECRYPT | CKF_WRAP | CKF_UNWRAP;
break;
case blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5:
operation_flags = CKF_SIGN | CKF_VERIFY;
break;
default:
NOTREACHED();
return Status::ErrorUnexpected();
}
const CK_FLAGS operation_flags_mask = CKF_ENCRYPT | CKF_DECRYPT |
CKF_SIGN | CKF_VERIFY | CKF_WRAP |
CKF_UNWRAP;
const PK11AttrFlags attribute_flags = 0; // Default all PK11_ATTR_ flags.
// Note: NSS does not generate an sec_public_key if the call below fails,
// so there is no danger of a leaked sec_public_key.
SECKEYPublicKey* sec_public_key;
crypto::ScopedSECKEYPrivateKey scoped_sec_private_key(
PK11_GenerateKeyPairWithOpFlags(slot.get(),
CKM_RSA_PKCS_KEY_PAIR_GEN,
&rsa_gen_params,
&sec_public_key,
attribute_flags,
operation_flags,
operation_flags_mask,
NULL));
if (!private_key)
return Status::Error();
*public_key = blink::WebCryptoKey::create(
new PublicKeyHandle(crypto::ScopedSECKEYPublicKey(sec_public_key)),
blink::WebCryptoKeyTypePublic,
true,
algorithm,
usage_mask);
*private_key = blink::WebCryptoKey::create(
new PrivateKeyHandle(scoped_sec_private_key.Pass()),
blink::WebCryptoKeyTypePrivate,
extractable,
algorithm,
usage_mask);
return Status::Success();
}
// Get the secret key length in bytes from generation parameters. This resolves
// any defaults.
Status GetGenerateSecretKeyLength(const blink::WebCryptoAlgorithm& algorithm,
unsigned int* keylen_bytes) {
*keylen_bytes = 0;
switch (algorithm.id()) {
case blink::WebCryptoAlgorithmIdAesCbc:
case blink::WebCryptoAlgorithmIdAesGcm:
case blink::WebCryptoAlgorithmIdAesKw: {
const blink::WebCryptoAesKeyGenParams* params =
algorithm.aesKeyGenParams();
DCHECK(params);
// Ensure the key length is a multiple of 8 bits. Let NSS verify further
// algorithm-specific length restrictions.
if (params->lengthBits() % 8)
return Status::ErrorGenerateKeyLength();
*keylen_bytes = params->lengthBits() / 8;
break;
}
case blink::WebCryptoAlgorithmIdHmac: {
const blink::WebCryptoHmacKeyParams* params = algorithm.hmacKeyParams();
DCHECK(params);
if (params->hasLengthBytes())
*keylen_bytes = params->optionalLengthBytes();
else
*keylen_bytes = webcrypto::ShaBlockSizeBytes(params->hash().id());
break;
}
default:
return Status::ErrorUnsupported();
}
if (*keylen_bytes == 0)
return Status::ErrorGenerateKeyLength();
return Status::Success();
}
} // namespace
void WebCryptoImpl::Init() {
crypto::EnsureNSSInit();
}
Status WebCryptoImpl::EncryptInternal(
const blink::WebCryptoAlgorithm& algorithm,
const blink::WebCryptoKey& key,
const unsigned char* data,
unsigned int data_size,
blink::WebArrayBuffer* buffer) {
DCHECK_EQ(algorithm.id(), key.algorithm().id());
DCHECK(key.handle());
DCHECK(buffer);
switch (algorithm.id()) {
case blink::WebCryptoAlgorithmIdAesCbc:
return AesCbcEncryptDecrypt(
CKA_ENCRYPT, algorithm, key, data, data_size, buffer);
case blink::WebCryptoAlgorithmIdAesGcm:
return AesGcmEncryptDecrypt(
true, algorithm, key, data, data_size, buffer);
case blink::WebCryptoAlgorithmIdRsaEsPkcs1v1_5:
return EncryptRsaEsPkcs1v1_5(algorithm, key, data, data_size, buffer);
default:
return Status::ErrorUnsupported();
}
}
Status WebCryptoImpl::DecryptInternal(
const blink::WebCryptoAlgorithm& algorithm,
const blink::WebCryptoKey& key,
const unsigned char* data,
unsigned int data_size,
blink::WebArrayBuffer* buffer) {
DCHECK_EQ(algorithm.id(), key.algorithm().id());
DCHECK(key.handle());
DCHECK(buffer);
switch (algorithm.id()) {
case blink::WebCryptoAlgorithmIdAesCbc:
return AesCbcEncryptDecrypt(
CKA_DECRYPT, algorithm, key, data, data_size, buffer);
case blink::WebCryptoAlgorithmIdAesGcm:
return AesGcmEncryptDecrypt(
false, algorithm, key, data, data_size, buffer);
case blink::WebCryptoAlgorithmIdRsaEsPkcs1v1_5:
return DecryptRsaEsPkcs1v1_5(algorithm, key, data, data_size, buffer);
default:
return Status::ErrorUnsupported();
}
}
Status WebCryptoImpl::DigestInternal(
const blink::WebCryptoAlgorithm& algorithm,
const unsigned char* data,
unsigned int data_size,
blink::WebArrayBuffer* buffer) {
HASH_HashType hash_type = WebCryptoAlgorithmToNSSHashType(algorithm);
if (hash_type == HASH_AlgNULL)
return Status::ErrorUnsupported();
HASHContext* context = HASH_Create(hash_type);
if (!context)
return Status::Error();
HASH_Begin(context);
HASH_Update(context, data, data_size);
unsigned int hash_result_length = HASH_ResultLenContext(context);
DCHECK_LE(hash_result_length, static_cast<size_t>(HASH_LENGTH_MAX));
*buffer = blink::WebArrayBuffer::create(hash_result_length, 1);
unsigned char* digest = reinterpret_cast<unsigned char*>(buffer->data());
unsigned int result_length = 0;
HASH_End(context, digest, &result_length, hash_result_length);
HASH_Destroy(context);
if (result_length != hash_result_length)
return Status::ErrorUnexpected();
return Status::Success();
}
Status WebCryptoImpl::GenerateSecretKeyInternal(
const blink::WebCryptoAlgorithm& algorithm,
bool extractable,
blink::WebCryptoKeyUsageMask usage_mask,
blink::WebCryptoKey* key) {
CK_MECHANISM_TYPE mech = WebCryptoAlgorithmToGenMechanism(algorithm);
blink::WebCryptoKeyType key_type = blink::WebCryptoKeyTypeSecret;
if (mech == CKM_INVALID_MECHANISM)
return Status::ErrorUnsupported();
unsigned int keylen_bytes = 0;
Status status = GetGenerateSecretKeyLength(algorithm, &keylen_bytes);
if (status.IsError())
return status;
crypto::ScopedPK11Slot slot(PK11_GetInternalKeySlot());
if (!slot)
return Status::Error();
crypto::ScopedPK11SymKey pk11_key(
PK11_KeyGen(slot.get(), mech, NULL, keylen_bytes, NULL));
if (!pk11_key)
return Status::Error();
*key = blink::WebCryptoKey::create(
new SymKeyHandle(pk11_key.Pass()),
key_type, extractable, algorithm, usage_mask);
return Status::Success();
}
Status WebCryptoImpl::GenerateKeyPairInternal(
const blink::WebCryptoAlgorithm& algorithm,
bool extractable,
blink::WebCryptoKeyUsageMask usage_mask,
blink::WebCryptoKey* public_key,
blink::WebCryptoKey* private_key) {
// TODO(padolph): Handle other asymmetric algorithm key generation.
switch (algorithm.id()) {
case blink::WebCryptoAlgorithmIdRsaEsPkcs1v1_5:
case blink::WebCryptoAlgorithmIdRsaOaep:
case blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5:
return GenerateRsaKeyPair(algorithm, extractable, usage_mask,
public_key, private_key);
default:
return Status::ErrorUnsupported();
}
}
Status WebCryptoImpl::ImportKeyInternal(
blink::WebCryptoKeyFormat format,
const unsigned char* key_data,
unsigned int key_data_size,
const blink::WebCryptoAlgorithm& algorithm_or_null,
bool extractable,
blink::WebCryptoKeyUsageMask usage_mask,
blink::WebCryptoKey* key) {
switch (format) {
case blink::WebCryptoKeyFormatRaw:
// A 'raw'-formatted key import requires an input algorithm.
if (algorithm_or_null.isNull())
return Status::ErrorMissingAlgorithmImportRawKey();
return ImportKeyInternalRaw(key_data,
key_data_size,
algorithm_or_null,
extractable,
usage_mask,
key);
case blink::WebCryptoKeyFormatSpki:
return ImportKeyInternalSpki(key_data,
key_data_size,
algorithm_or_null,
extractable,
usage_mask,
key);
case blink::WebCryptoKeyFormatPkcs8:
return ImportKeyInternalPkcs8(key_data,
key_data_size,
algorithm_or_null,
extractable,
usage_mask,
key);
default:
// NOTE: blink::WebCryptoKeyFormatJwk is handled one level above.
return Status::ErrorUnsupported();
}
}
Status WebCryptoImpl::ExportKeyInternal(
blink::WebCryptoKeyFormat format,
const blink::WebCryptoKey& key,
blink::WebArrayBuffer* buffer) {
switch (format) {
case blink::WebCryptoKeyFormatRaw:
return ExportKeyInternalRaw(key, buffer);
case blink::WebCryptoKeyFormatSpki:
return ExportKeyInternalSpki(key, buffer);
case blink::WebCryptoKeyFormatPkcs8:
// TODO(padolph): Implement pkcs8 export
return Status::ErrorUnsupported();
default:
return Status::ErrorUnsupported();
}
}
Status WebCryptoImpl::SignInternal(
const blink::WebCryptoAlgorithm& algorithm,
const blink::WebCryptoKey& key,
const unsigned char* data,
unsigned int data_size,
blink::WebArrayBuffer* buffer) {
// Note: It is not an error to sign empty data.
DCHECK(buffer);
DCHECK_NE(0, key.usages() & blink::WebCryptoKeyUsageSign);
switch (algorithm.id()) {
case blink::WebCryptoAlgorithmIdHmac:
return SignHmac(algorithm, key, data, data_size, buffer);
case blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5:
return SignRsaSsaPkcs1v1_5(algorithm, key, data, data_size, buffer);
default:
return Status::ErrorUnsupported();
}
}
Status WebCryptoImpl::VerifySignatureInternal(
const blink::WebCryptoAlgorithm& algorithm,
const blink::WebCryptoKey& key,
const unsigned char* signature,
unsigned int signature_size,
const unsigned char* data,
unsigned int data_size,
bool* signature_match) {
if (!signature_size) {
// None of the algorithms generate valid zero-length signatures so this
// will necessarily fail verification. Early return to protect
// implementations from dealing with a NULL signature pointer.
*signature_match = false;
return Status::Success();
}
DCHECK(signature);
switch (algorithm.id()) {
case blink::WebCryptoAlgorithmIdHmac:
return VerifyHmac(algorithm, key, signature, signature_size,
data, data_size, signature_match);
case blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5:
return VerifyRsaSsaPkcs1v1_5(algorithm, key, signature, signature_size,
data, data_size, signature_match);
default:
return Status::ErrorUnsupported();
}
}
Status WebCryptoImpl::ImportRsaPublicKeyInternal(
const unsigned char* modulus_data,
unsigned int modulus_size,
const unsigned char* exponent_data,
unsigned int exponent_size,
const blink::WebCryptoAlgorithm& algorithm,
bool extractable,
blink::WebCryptoKeyUsageMask usage_mask,
blink::WebCryptoKey* key) {
if (!modulus_size)
return Status::ErrorImportRsaEmptyModulus();
if (!exponent_size)
return Status::ErrorImportRsaEmptyExponent();
DCHECK(modulus_data);
DCHECK(exponent_data);
// NSS does not provide a way to create an RSA public key directly from the
// modulus and exponent values, but it can import an DER-encoded ASN.1 blob
// with these values and create the public key from that. The code below
// follows the recommendation described in
// https://developer.mozilla.org/en-US/docs/NSS/NSS_Tech_Notes/nss_tech_note7
// Pack the input values into a struct compatible with NSS ASN.1 encoding, and
// set up an ASN.1 encoder template for it.
struct RsaPublicKeyData {
SECItem modulus;
SECItem exponent;
};
const RsaPublicKeyData pubkey_in = {
{siUnsignedInteger, const_cast<unsigned char*>(modulus_data),
modulus_size},
{siUnsignedInteger, const_cast<unsigned char*>(exponent_data),
exponent_size}};
const SEC_ASN1Template rsa_public_key_template[] = {
{SEC_ASN1_SEQUENCE, 0, NULL, sizeof(RsaPublicKeyData)},
{SEC_ASN1_INTEGER, offsetof(RsaPublicKeyData, modulus), },
{SEC_ASN1_INTEGER, offsetof(RsaPublicKeyData, exponent), },
{0, }};
// DER-encode the public key.
crypto::ScopedSECItem pubkey_der(SEC_ASN1EncodeItem(
NULL, NULL, &pubkey_in, rsa_public_key_template));
if (!pubkey_der)
return Status::Error();
// Import the DER-encoded public key to create an RSA SECKEYPublicKey.
crypto::ScopedSECKEYPublicKey pubkey(
SECKEY_ImportDERPublicKey(pubkey_der.get(), CKK_RSA));
if (!pubkey)
return Status::Error();
*key = blink::WebCryptoKey::create(new PublicKeyHandle(pubkey.Pass()),
blink::WebCryptoKeyTypePublic,
extractable,
algorithm,
usage_mask);
return Status::Success();
}
} // namespace content
|