Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(9)

Side by Side Diff: content/child/webcrypto/jwk.cc

Issue 184043021: [webcrypto] JWK: Updated import(ext, key_ops) and added export of symmetric keys (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@wcAesKw_nss1
Patch Set: fixes for eroman and rsleevi Created 6 years, 9 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « no previous file | content/child/webcrypto/shared_crypto.h » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 // Copyright 2014 The Chromium Authors. All rights reserved. 1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include <algorithm> 5 #include <algorithm>
6 #include <functional> 6 #include <functional>
7 #include <map> 7 #include <map>
8 #include "base/base64.h"
eroman 2014/03/11 03:22:47 Is this header necessary?
padolph 2014/03/11 15:34:24 Done.
8 #include "base/json/json_reader.h" 9 #include "base/json/json_reader.h"
10 #include "base/json/json_writer.h"
9 #include "base/lazy_instance.h" 11 #include "base/lazy_instance.h"
10 #include "base/logging.h" 12 #include "base/logging.h"
11 #include "base/memory/scoped_ptr.h" 13 #include "base/memory/scoped_ptr.h"
12 #include "base/strings/string_piece.h" 14 #include "base/strings/string_piece.h"
13 #include "base/values.h" 15 #include "base/strings/stringprintf.h"
14 #include "content/child/webcrypto/crypto_data.h" 16 #include "content/child/webcrypto/crypto_data.h"
15 #include "content/child/webcrypto/platform_crypto.h" 17 #include "content/child/webcrypto/platform_crypto.h"
16 #include "content/child/webcrypto/shared_crypto.h" 18 #include "content/child/webcrypto/shared_crypto.h"
17 #include "content/child/webcrypto/webcrypto_util.h" 19 #include "content/child/webcrypto/webcrypto_util.h"
20 #include "third_party/WebKit/public/platform/WebCryptoKeyAlgorithm.h"
18 21
19 namespace content { 22 namespace content {
20 23
21 namespace webcrypto { 24 namespace webcrypto {
22 25
23 namespace { 26 namespace {
24 27
28 // Web Crypto equivalent usage mask for JWK 'use' = 'enc'.
29 // TODO(padolph): Add 'deriveBits' once supported by Blink.
30 const blink::WebCryptoKeyUsageMask kJwkEncUsage =
31 blink::WebCryptoKeyUsageEncrypt | blink::WebCryptoKeyUsageDecrypt |
32 blink::WebCryptoKeyUsageWrapKey | blink::WebCryptoKeyUsageUnwrapKey |
33 blink::WebCryptoKeyUsageDeriveKey;
34 // Web Crypto equivalent usage mask for JWK 'use' = 'sig'.
35 const blink::WebCryptoKeyUsageMask kJwkSigUsage =
36 blink::WebCryptoKeyUsageSign | blink::WebCryptoKeyUsageVerify;
37
25 typedef blink::WebCryptoAlgorithm (*AlgorithmCreationFunc)(); 38 typedef blink::WebCryptoAlgorithm (*AlgorithmCreationFunc)();
26 39
27 class JwkAlgorithmInfo { 40 class JwkAlgorithmInfo {
28 public: 41 public:
29 JwkAlgorithmInfo() 42 JwkAlgorithmInfo()
30 : creation_func_(NULL), 43 : creation_func_(NULL),
31 required_key_length_bytes_(NO_KEY_SIZE_REQUIREMENT) {} 44 required_key_length_bytes_(NO_KEY_SIZE_REQUIREMENT) {}
32 45
33 explicit JwkAlgorithmInfo(AlgorithmCreationFunc algorithm_creation_func) 46 explicit JwkAlgorithmInfo(AlgorithmCreationFunc algorithm_creation_func)
34 : creation_func_(algorithm_creation_func), 47 : creation_func_(algorithm_creation_func),
(...skipping 28 matching lines...) Expand all
63 76
64 typedef std::map<std::string, JwkAlgorithmInfo> JwkAlgorithmInfoMap; 77 typedef std::map<std::string, JwkAlgorithmInfo> JwkAlgorithmInfoMap;
65 78
66 class JwkAlgorithmRegistry { 79 class JwkAlgorithmRegistry {
67 public: 80 public:
68 JwkAlgorithmRegistry() { 81 JwkAlgorithmRegistry() {
69 // TODO(eroman): 82 // TODO(eroman):
70 // http://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-20 83 // http://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-20
71 // says HMAC with SHA-2 should have a key size at least as large as the 84 // says HMAC with SHA-2 should have a key size at least as large as the
72 // hash output. 85 // hash output.
86 alg_to_info_["HS1"] =
87 JwkAlgorithmInfo(&BindAlgorithmId<CreateHmacImportAlgorithm,
88 blink::WebCryptoAlgorithmIdSha1>);
73 alg_to_info_["HS256"] = 89 alg_to_info_["HS256"] =
74 JwkAlgorithmInfo(&BindAlgorithmId<CreateHmacImportAlgorithm, 90 JwkAlgorithmInfo(&BindAlgorithmId<CreateHmacImportAlgorithm,
75 blink::WebCryptoAlgorithmIdSha256>); 91 blink::WebCryptoAlgorithmIdSha256>);
76 alg_to_info_["HS384"] = 92 alg_to_info_["HS384"] =
77 JwkAlgorithmInfo(&BindAlgorithmId<CreateHmacImportAlgorithm, 93 JwkAlgorithmInfo(&BindAlgorithmId<CreateHmacImportAlgorithm,
78 blink::WebCryptoAlgorithmIdSha384>); 94 blink::WebCryptoAlgorithmIdSha384>);
79 alg_to_info_["HS512"] = 95 alg_to_info_["HS512"] =
80 JwkAlgorithmInfo(&BindAlgorithmId<CreateHmacImportAlgorithm, 96 JwkAlgorithmInfo(&BindAlgorithmId<CreateHmacImportAlgorithm,
81 blink::WebCryptoAlgorithmIdSha512>); 97 blink::WebCryptoAlgorithmIdSha512>);
82 alg_to_info_["RS256"] = 98 alg_to_info_["RS256"] =
83 JwkAlgorithmInfo(&BindAlgorithmId<CreateRsaSsaImportAlgorithm, 99 JwkAlgorithmInfo(&BindAlgorithmId<CreateRsaSsaImportAlgorithm,
84 blink::WebCryptoAlgorithmIdSha256>); 100 blink::WebCryptoAlgorithmIdSha256>);
85 alg_to_info_["RS384"] = 101 alg_to_info_["RS384"] =
86 JwkAlgorithmInfo(&BindAlgorithmId<CreateRsaSsaImportAlgorithm, 102 JwkAlgorithmInfo(&BindAlgorithmId<CreateRsaSsaImportAlgorithm,
87 blink::WebCryptoAlgorithmIdSha384>); 103 blink::WebCryptoAlgorithmIdSha384>);
88 alg_to_info_["RS512"] = 104 alg_to_info_["RS512"] =
89 JwkAlgorithmInfo(&BindAlgorithmId<CreateRsaSsaImportAlgorithm, 105 JwkAlgorithmInfo(&BindAlgorithmId<CreateRsaSsaImportAlgorithm,
90 blink::WebCryptoAlgorithmIdSha512>); 106 blink::WebCryptoAlgorithmIdSha512>);
91 alg_to_info_["RSA1_5"] = JwkAlgorithmInfo( 107 alg_to_info_["RSA1_5"] = JwkAlgorithmInfo(
92 &BindAlgorithmId<CreateAlgorithm, 108 &BindAlgorithmId<CreateAlgorithm,
93 blink::WebCryptoAlgorithmIdRsaEsPkcs1v1_5>); 109 blink::WebCryptoAlgorithmIdRsaEsPkcs1v1_5>);
94 alg_to_info_["RSA-OAEP"] = 110 alg_to_info_["RSA-OAEP"] =
95 JwkAlgorithmInfo(&BindAlgorithmId<CreateRsaOaepImportAlgorithm, 111 JwkAlgorithmInfo(&BindAlgorithmId<CreateRsaOaepImportAlgorithm,
96 blink::WebCryptoAlgorithmIdSha1>); 112 blink::WebCryptoAlgorithmIdSha1>);
97 // TODO(padolph): The Web Crypto spec does not enumerate AES-KW 128 yet 113 alg_to_info_["A128KW"] = JwkAlgorithmInfo(
98 alg_to_info_["A128KW"] = 114 &BindAlgorithmId<CreateAlgorithm, blink::WebCryptoAlgorithmIdAesKw>,
99 JwkAlgorithmInfo(&blink::WebCryptoAlgorithm::createNull, 128); 115 128);
100 // TODO(padolph): The Web Crypto spec does not enumerate AES-KW 256 yet 116 alg_to_info_["A192KW"] = JwkAlgorithmInfo(
101 alg_to_info_["A256KW"] = 117 &BindAlgorithmId<CreateAlgorithm, blink::WebCryptoAlgorithmIdAesKw>,
102 JwkAlgorithmInfo(&blink::WebCryptoAlgorithm::createNull, 256); 118 192);
119 alg_to_info_["A256KW"] = JwkAlgorithmInfo(
120 &BindAlgorithmId<CreateAlgorithm, blink::WebCryptoAlgorithmIdAesKw>,
121 256);
103 alg_to_info_["A128GCM"] = JwkAlgorithmInfo( 122 alg_to_info_["A128GCM"] = JwkAlgorithmInfo(
104 &BindAlgorithmId<CreateAlgorithm, blink::WebCryptoAlgorithmIdAesGcm>, 123 &BindAlgorithmId<CreateAlgorithm, blink::WebCryptoAlgorithmIdAesGcm>,
105 128); 124 128);
125 alg_to_info_["A192GCM"] = JwkAlgorithmInfo(
126 &BindAlgorithmId<CreateAlgorithm, blink::WebCryptoAlgorithmIdAesGcm>,
127 192);
106 alg_to_info_["A256GCM"] = JwkAlgorithmInfo( 128 alg_to_info_["A256GCM"] = JwkAlgorithmInfo(
107 &BindAlgorithmId<CreateAlgorithm, blink::WebCryptoAlgorithmIdAesGcm>, 129 &BindAlgorithmId<CreateAlgorithm, blink::WebCryptoAlgorithmIdAesGcm>,
108 256); 130 256);
109 alg_to_info_["A128CBC"] = JwkAlgorithmInfo( 131 alg_to_info_["A128CBC"] = JwkAlgorithmInfo(
110 &BindAlgorithmId<CreateAlgorithm, blink::WebCryptoAlgorithmIdAesCbc>, 132 &BindAlgorithmId<CreateAlgorithm, blink::WebCryptoAlgorithmIdAesCbc>,
111 128); 133 128);
112 alg_to_info_["A192CBC"] = JwkAlgorithmInfo( 134 alg_to_info_["A192CBC"] = JwkAlgorithmInfo(
113 &BindAlgorithmId<CreateAlgorithm, blink::WebCryptoAlgorithmIdAesCbc>, 135 &BindAlgorithmId<CreateAlgorithm, blink::WebCryptoAlgorithmIdAesCbc>,
114 192); 136 192);
115 alg_to_info_["A256CBC"] = JwkAlgorithmInfo( 137 alg_to_info_["A256CBC"] = JwkAlgorithmInfo(
(...skipping 74 matching lines...) Expand 10 before | Expand all | Expand 10 after
190 if (!dict->Get(path, &value)) 212 if (!dict->Get(path, &value))
191 return Status::Success(); 213 return Status::Success();
192 214
193 if (!value->GetAsString(result)) 215 if (!value->GetAsString(result))
194 return Status::ErrorJwkPropertyWrongType(path, "string"); 216 return Status::ErrorJwkPropertyWrongType(path, "string");
195 217
196 *property_exists = true; 218 *property_exists = true;
197 return Status::Success(); 219 return Status::Success();
198 } 220 }
199 221
222 // Extracts the optional array property with key |path| from |dict| and saves
223 // the result to |*result| if it was found. If the property exists and is not an
224 // array, returns an error. Otherwise returns success, and sets
225 // |*property_exists| if it was found. Note that |*result| is owned by |dict|.
226 Status GetOptionalJwkList(base::DictionaryValue* dict,
227 const std::string& path,
228 base::ListValue** result,
229 bool* property_exists) {
230 *property_exists = false;
231 base::Value* value = NULL;
232 if (!dict->Get(path, &value))
233 return Status::Success();
234
235 if (!value->GetAsList(result))
236 return Status::ErrorJwkPropertyWrongType(path, "list");
237
238 *property_exists = true;
239 return Status::Success();
240 }
241
200 // Extracts the required string property with key |path| from |dict| and saves 242 // Extracts the required string property with key |path| from |dict| and saves
201 // the base64-decoded bytes to |*result|. If the property does not exist or is 243 // the base64url-decoded bytes to |*result|. If the property does not exist or
202 // not a string, or could not be base64-decoded, returns an error. 244 // is not a string, or could not be base64url-decoded, returns an error.
203 Status GetJwkBytes(base::DictionaryValue* dict, 245 Status GetJwkBytes(base::DictionaryValue* dict,
204 const std::string& path, 246 const std::string& path,
205 std::string* result) { 247 std::string* result) {
206 std::string base64_string; 248 std::string base64_string;
207 Status status = GetJwkString(dict, path, &base64_string); 249 Status status = GetJwkString(dict, path, &base64_string);
208 if (status.IsError()) 250 if (status.IsError())
209 return status; 251 return status;
210 252
211 if (!Base64DecodeUrlSafe(base64_string, result)) 253 if (!Base64DecodeUrlSafe(base64_string, result))
212 return Status::ErrorJwkBase64Decode(path); 254 return Status::ErrorJwkBase64Decode(path);
(...skipping 14 matching lines...) Expand all
227 if (!dict->Get(path, &value)) 269 if (!dict->Get(path, &value))
228 return Status::Success(); 270 return Status::Success();
229 271
230 if (!value->GetAsBoolean(result)) 272 if (!value->GetAsBoolean(result))
231 return Status::ErrorJwkPropertyWrongType(path, "boolean"); 273 return Status::ErrorJwkPropertyWrongType(path, "boolean");
232 274
233 *property_exists = true; 275 *property_exists = true;
234 return Status::Success(); 276 return Status::Success();
235 } 277 }
236 278
279 // Returns true if the set bits in b make up a subset of the set bits in a.
280 bool ContainsKeyUsages(blink::WebCryptoKeyUsageMask a,
281 blink::WebCryptoKeyUsageMask b) {
282 return (a & b) == b;
283 }
284
285 // Writes a secret/symmetric key to a JWK dictionary.
286 void WriteSecretKey(const blink::WebArrayBuffer& raw_key,
287 base::DictionaryValue* jwk_dict) {
288 DCHECK(jwk_dict);
289 jwk_dict->SetString("kty", "oct");
290 // For a secret/symmetric key, the only extra JWK field is 'k', containing the
291 // base64url encoding of the raw key.
292 DCHECK(!raw_key.isNull());
293 DCHECK(raw_key.data());
294 DCHECK(raw_key.byteLength());
295 unsigned int key_length_bytes = raw_key.byteLength();
296 const base::StringPiece key_str(static_cast<const char*>(raw_key.data()),
297 key_length_bytes);
298 jwk_dict->SetString("k", Base64EncodeUrlSafe(key_str));
299 }
300
301 // Writes a Web Crypto usage mask to a JWK dictionary.
302 void WriteKeyOps(blink::WebCryptoKeyUsageMask key_usages,
303 base::DictionaryValue* jwk_dict) {
304 jwk_dict->Set("key_ops", CreateJwkKeyOpsFromWebCryptoUsages(key_usages));
305 }
306
307 // Writes a Web Crypto extractable value to a JWK dictionary.
308 void WriteExt(bool extractable, base::DictionaryValue* jwk_dict) {
309 jwk_dict->SetBoolean("ext", extractable);
310 }
311
312 // Writes a Web Crypto algorithm to a JWK dictionary.
313 Status WriteAlg(const blink::WebCryptoKeyAlgorithm& algorithm,
314 unsigned int raw_key_length_bytes,
315 base::DictionaryValue* jwk_dict) {
316 switch (algorithm.paramsType()) {
317 case blink::WebCryptoKeyAlgorithmParamsTypeAes: {
318 const char* aes_prefix = "";
319 switch (raw_key_length_bytes) {
320 case 16:
321 aes_prefix = "A128";
322 break;
323 case 24:
324 aes_prefix = "A192";
325 break;
326 case 32:
327 aes_prefix = "A256";
328 break;
329 default:
330 NOTREACHED(); // bad key length means algorithm was built improperly
331 return Status::ErrorUnexpected();
332 }
333 const char* aes_suffix = "";
334 switch (algorithm.id()) {
335 case blink::WebCryptoAlgorithmIdAesCbc:
336 aes_suffix = "CBC";
337 break;
338 case blink::WebCryptoAlgorithmIdAesCtr:
339 aes_suffix = "CTR";
340 break;
341 case blink::WebCryptoAlgorithmIdAesGcm:
342 aes_suffix = "GCM";
343 break;
344 case blink::WebCryptoAlgorithmIdAesKw:
345 aes_suffix = "KW";
346 break;
347 default:
348 return Status::ErrorUnsupported();
349 }
350 jwk_dict->SetString("alg",
351 base::StringPrintf("%s%s", aes_prefix, aes_suffix));
352 break;
353 }
354 case blink::WebCryptoKeyAlgorithmParamsTypeHmac: {
355 DCHECK(algorithm.hmacParams());
356 switch (algorithm.hmacParams()->hash().id()) {
357 case blink::WebCryptoAlgorithmIdSha1:
358 jwk_dict->SetString("alg", "HS1");
359 break;
360 case blink::WebCryptoAlgorithmIdSha224:
361 jwk_dict->SetString("alg", "HS224");
362 break;
363 case blink::WebCryptoAlgorithmIdSha256:
364 jwk_dict->SetString("alg", "HS256");
365 break;
366 case blink::WebCryptoAlgorithmIdSha384:
367 jwk_dict->SetString("alg", "HS384");
368 break;
369 case blink::WebCryptoAlgorithmIdSha512:
370 jwk_dict->SetString("alg", "HS512");
371 break;
372 default:
373 NOTREACHED();
374 return Status::ErrorUnexpected();
375 }
376 break;
377 }
378 case blink::WebCryptoKeyAlgorithmParamsTypeRsa:
379 case blink::WebCryptoKeyAlgorithmParamsTypeRsaHashed:
380 // TODO(padolph): Handle RSA key
381 return Status::ErrorUnsupported();
382 default:
383 return Status::ErrorUnsupported();
384 }
385 return Status::Success();
386 }
387
237 } // namespace 388 } // namespace
238 389
239 Status ImportKeyJwk(const CryptoData& key_data, 390 Status ImportKeyJwk(const CryptoData& key_data,
240 const blink::WebCryptoAlgorithm& algorithm_or_null, 391 const blink::WebCryptoAlgorithm& algorithm_or_null,
241 bool extractable, 392 bool extractable,
242 blink::WebCryptoKeyUsageMask usage_mask, 393 blink::WebCryptoKeyUsageMask usage_mask,
243 blink::WebCryptoKey* key) { 394 blink::WebCryptoKey* key) {
244 395
396 // TODO(padolph): Generalize this comment to include export, and move to top
397 // of file.
398
245 // The goal of this method is to extract key material and meta data from the 399 // The goal of this method is to extract key material and meta data from the
246 // incoming JWK, combine them with the input parameters, and ultimately import 400 // incoming JWK, combine them with the input parameters, and ultimately import
247 // a Web Crypto Key. 401 // a Web Crypto Key.
248 // 402 //
249 // JSON Web Key Format (JWK) 403 // JSON Web Key Format (JWK)
250 // http://tools.ietf.org/html/draft-ietf-jose-json-web-key-16 404 // http://tools.ietf.org/html/draft-ietf-jose-json-web-key-21
251 // TODO(padolph): Not all possible values are handled by this code right now
252 // 405 //
253 // A JWK is a simple JSON dictionary with the following entries 406 // A JWK is a simple JSON dictionary with the following entries
254 // - "kty" (Key Type) Parameter, REQUIRED 407 // - "kty" (Key Type) Parameter, REQUIRED
255 // - <kty-specific parameters, see below>, REQUIRED 408 // - <kty-specific parameters, see below>, REQUIRED
256 // - "use" (Key Use) Parameter, OPTIONAL 409 // - "use" (Key Use) Parameter, OPTIONAL
410 // - "key_ops" (Key Operations) Parameter, OPTIONAL
257 // - "alg" (Algorithm) Parameter, OPTIONAL 411 // - "alg" (Algorithm) Parameter, OPTIONAL
258 // - "extractable" (Key Exportability), OPTIONAL [NOTE: not yet part of JOSE, 412 // - "ext" (Key Exportability), OPTIONAL
259 // see https://www.w3.org/Bugs/Public/show_bug.cgi?id=23796]
260 // (all other entries are ignored) 413 // (all other entries are ignored)
261 // 414 //
262 // OPTIONAL here means that this code does not require the entry to be present 415 // OPTIONAL here means that this code does not require the entry to be present
263 // in the incoming JWK, because the method input parameters contain similar 416 // in the incoming JWK, because the method input parameters contain similar
264 // information. If the optional JWK entry is present, it will be validated 417 // information. If the optional JWK entry is present, it will be validated
265 // against the corresponding input parameter for consistency and combined with 418 // against the corresponding input parameter for consistency and combined with
266 // it according to rules defined below. A special case is that the method 419 // it according to rules defined below. A special case is that the method
267 // input parameter 'algorithm' is also optional. If it is null, the JWK 'alg' 420 // input parameter 'algorithm' is also optional. If it is null, the JWK 'alg'
268 // value (if present) is used as a fallback. 421 // value (if present) is used as a fallback.
269 // 422 //
270 // Input 'key_data' contains the JWK. To build a Web Crypto Key, the JWK 423 // Input 'key_data' contains the JWK. To build a Web Crypto Key, the JWK
271 // values are parsed out and combined with the method input parameters to 424 // values are parsed out and combined with the method input parameters to
272 // build a Web Crypto Key: 425 // build a Web Crypto Key:
273 // Web Crypto Key type <-- (deduced) 426 // Web Crypto Key type <-- (deduced)
274 // Web Crypto Key extractable <-- JWK extractable + input extractable 427 // Web Crypto Key extractable <-- JWK ext + input extractable
275 // Web Crypto Key algorithm <-- JWK alg + input algorithm 428 // Web Crypto Key algorithm <-- JWK alg + input algorithm
276 // Web Crypto Key keyUsage <-- JWK use + input usage_mask 429 // Web Crypto Key keyUsage <-- JWK use, key_ops + input usage_mask
277 // Web Crypto Key keying material <-- kty-specific parameters 430 // Web Crypto Key keying material <-- kty-specific parameters
278 // 431 //
279 // Values for each JWK entry are case-sensitive and defined in 432 // Values for each JWK entry are case-sensitive and defined in
280 // http://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-16. 433 // http://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-18.
281 // Note that not all values specified by JOSE are handled by this code. Only 434 // Note that not all values specified by JOSE are handled by this code. Only
282 // handled values are listed. 435 // handled values are listed.
283 // - kty (Key Type) 436 // - kty (Key Type)
284 // +-------+--------------------------------------------------------------+ 437 // +-------+--------------------------------------------------------------+
285 // | "RSA" | RSA [RFC3447] | 438 // | "RSA" | RSA [RFC3447] |
286 // | "oct" | Octet sequence (used to represent symmetric keys) | 439 // | "oct" | Octet sequence (used to represent symmetric keys) |
287 // +-------+--------------------------------------------------------------+ 440 // +-------+--------------------------------------------------------------+
441 //
442 // - key_ops (Key Use Details)
443 // The key_ops field is an array that contains one or more strings from
444 // the table below, and describes the operations for which this key may be
445 // used.
446 // +-------+--------------------------------------------------------------+
447 // | "encrypt" | encrypt operations |
448 // | "decrypt" | decrypt operations |
449 // | "sign" | sign (MAC) operations |
450 // | "verify" | verify (MAC) operations |
451 // | "wrapKey" | key wrap |
452 // | "unwrapKey" | key unwrap |
453 // | "deriveKey" | key derivation |
454 // | "deriveBits" | key derivation TODO(padolph): not currently supported |
455 // +-------+--------------------------------------------------------------+
456 //
288 // - use (Key Use) 457 // - use (Key Use)
458 // The use field contains a single entry from the table below.
289 // +-------+--------------------------------------------------------------+ 459 // +-------+--------------------------------------------------------------+
290 // | "enc" | encrypt and decrypt operations | 460 // | "sig" | equivalent to key_ops of [sign, verify] |
291 // | "sig" | sign and verify (MAC) operations | 461 // | "enc" | equivalent to key_ops of [encrypt, decrypt, wrapKey, |
292 // | "wrap"| key wrap and unwrap [not yet part of JOSE] | 462 // | | unwrapKey, deriveKey, deriveBits] |
293 // +-------+--------------------------------------------------------------+ 463 // +-------+--------------------------------------------------------------+
294 // - extractable (Key Exportability) 464 //
465 // NOTE: If both "use" and "key_ops" JWK members are present, the usages
466 // specified by them MUST be consistent. In particular, the "use" value
467 // "sig" corresponds to "sign" and/or "verify". The "use" value "enc"
468 // corresponds to all other values defined above. If "key_ops" values
469 // corresponding to both "sig" and "enc" "use" values are present, the "use"
470 // member SHOULD NOT be present, and if present, its value MUST NOT be
471 // either "sig" or "enc".
472 //
473 // - ext (Key Exportability)
295 // +-------+--------------------------------------------------------------+ 474 // +-------+--------------------------------------------------------------+
296 // | true | Key may be exported from the trusted environment | 475 // | true | Key may be exported from the trusted environment |
297 // | false | Key cannot exit the trusted environment | 476 // | false | Key cannot exit the trusted environment |
298 // +-------+--------------------------------------------------------------+ 477 // +-------+--------------------------------------------------------------+
478 //
299 // - alg (Algorithm) 479 // - alg (Algorithm)
300 // See http://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-16 480 // See http://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-18
301 // +--------------+-------------------------------------------------------+ 481 // +--------------+-------------------------------------------------------+
302 // | Digital Signature or MAC Algorithm | 482 // | Digital Signature or MAC Algorithm |
303 // +--------------+-------------------------------------------------------+ 483 // +--------------+-------------------------------------------------------+
484 // | "HS1" | HMAC using SHA-1 hash algorithm |
304 // | "HS256" | HMAC using SHA-256 hash algorithm | 485 // | "HS256" | HMAC using SHA-256 hash algorithm |
305 // | "HS384" | HMAC using SHA-384 hash algorithm | 486 // | "HS384" | HMAC using SHA-384 hash algorithm |
306 // | "HS512" | HMAC using SHA-512 hash algorithm | 487 // | "HS512" | HMAC using SHA-512 hash algorithm |
307 // | "RS256" | RSASSA using SHA-256 hash algorithm | 488 // | "RS256" | RSASSA using SHA-256 hash algorithm |
308 // | "RS384" | RSASSA using SHA-384 hash algorithm | 489 // | "RS384" | RSASSA using SHA-384 hash algorithm |
309 // | "RS512" | RSASSA using SHA-512 hash algorithm | 490 // | "RS512" | RSASSA using SHA-512 hash algorithm |
310 // +--------------+-------------------------------------------------------| 491 // +--------------+-------------------------------------------------------|
311 // | Key Management Algorithm | 492 // | Key Management Algorithm |
312 // +--------------+-------------------------------------------------------+ 493 // +--------------+-------------------------------------------------------+
313 // | "RSA1_5" | RSAES-PKCS1-V1_5 [RFC3447] | 494 // | "RSA1_5" | RSAES-PKCS1-V1_5 [RFC3447] |
314 // | "RSA-OAEP" | RSAES using Optimal Asymmetric Encryption Padding | 495 // | "RSA-OAEP" | RSAES using Optimal Asymmetric Encryption Padding |
315 // | | (OAEP) [RFC3447], with the default parameters | 496 // | | (OAEP) [RFC3447], with the default parameters |
316 // | | specified by RFC3447 in Section A.2.1 | 497 // | | specified by RFC3447 in Section A.2.1 |
317 // | "A128KW" | Advanced Encryption Standard (AES) Key Wrap Algorithm | 498 // | "A128KW" | Advanced Encryption Standard (AES) Key Wrap Algorithm |
318 // | | [RFC3394] using 128 bit keys | 499 // | | [RFC3394] using 128 bit keys |
500 // | "A192KW" | AES Key Wrap Algorithm using 192 bit keys |
319 // | "A256KW" | AES Key Wrap Algorithm using 256 bit keys | 501 // | "A256KW" | AES Key Wrap Algorithm using 256 bit keys |
320 // | "A128GCM" | AES in Galois/Counter Mode (GCM) [NIST.800-38D] using | 502 // | "A128GCM" | AES in Galois/Counter Mode (GCM) [NIST.800-38D] using |
321 // | | 128 bit keys | 503 // | | 128 bit keys |
504 // | "A192GCM" | AES GCM using 192 bit keys |
322 // | "A256GCM" | AES GCM using 256 bit keys | 505 // | "A256GCM" | AES GCM using 256 bit keys |
323 // | "A128CBC" | AES in Cipher Block Chaining Mode (CBC) with PKCS #5 | 506 // | "A128CBC" | AES in Cipher Block Chaining Mode (CBC) with PKCS #5 |
324 // | | padding [NIST.800-38A] [not yet part of JOSE, see | 507 // | | padding [NIST.800-38A] |
325 // | | https://www.w3.org/Bugs/Public/show_bug.cgi?id=23796 | 508 // | "A192CBC" | AES CBC using 192 bit keys |
326 // | "A192CBC" | AES CBC using 192 bit keys [not yet part of JOSE] | 509 // | "A256CBC" | AES CBC using 256 bit keys |
327 // | "A256CBC" | AES CBC using 256 bit keys [not yet part of JOSE] |
328 // +--------------+-------------------------------------------------------+ 510 // +--------------+-------------------------------------------------------+
329 // 511 //
330 // kty-specific parameters 512 // kty-specific parameters
331 // The value of kty determines the type and content of the keying material 513 // The value of kty determines the type and content of the keying material
332 // carried in the JWK to be imported. Currently only two possibilities are 514 // carried in the JWK to be imported. Currently only two possibilities are
333 // supported: a raw key or an RSA public key. RSA private keys are not 515 // supported: a raw key or an RSA public key. RSA private keys are not
334 // supported because typical applications seldom need to import a private key, 516 // supported because typical applications seldom need to import a private key,
335 // and the large number of JWK parameters required to describe one. 517 // and the large number of JWK parameters required to describe one.
336 // - kty == "oct" (symmetric or other raw key) 518 // - kty == "oct" (symmetric or other raw key)
337 // +-------+--------------------------------------------------------------+ 519 // +-------+--------------------------------------------------------------+
(...skipping 21 matching lines...) Expand all
359 // 541 //
360 // algorithm 542 // algorithm
361 // If an algorithm is provided by both the input parameter and the JWK, 543 // If an algorithm is provided by both the input parameter and the JWK,
362 // consistency between the two is based only on algorithm ID's (including an 544 // consistency between the two is based only on algorithm ID's (including an
363 // inner hash algorithm if present). In this case if the consistency 545 // inner hash algorithm if present). In this case if the consistency
364 // check is passed, the input algorithm is used. If only one of either the 546 // check is passed, the input algorithm is used. If only one of either the
365 // input algorithm and JWK alg is provided, it is used as the final 547 // input algorithm and JWK alg is provided, it is used as the final
366 // algorithm. 548 // algorithm.
367 // 549 //
368 // extractable 550 // extractable
369 // If the JWK extractable is true but the input parameter is false, make the 551 // If the JWK ext field is true but the input parameter is false, make the
370 // Web Crypto Key non-extractable. Conversely, if the JWK extractable is 552 // Web Crypto Key non-extractable. Conversely, if the JWK ext field is
371 // false but the input parameter is true, it is an inconsistency. If both 553 // false but the input parameter is true, it is an inconsistency. If both
372 // are true or both are false, use that value. 554 // are true or both are false, use that value.
373 // 555 //
374 // usage_mask 556 // usage_mask
375 // The input usage_mask must be a strict subset of the interpreted JWK use 557 // The input usage_mask must be a strict subset of the interpreted JWK use
376 // value, else it is judged inconsistent. In all cases the input usage_mask 558 // value, else it is judged inconsistent. In all cases the input usage_mask
377 // is used as the final usage_mask. 559 // is used as the final usage_mask.
378 // 560 //
379 561
380 if (!key_data.byte_length()) 562 if (!key_data.byte_length())
381 return Status::ErrorImportEmptyKeyData(); 563 return Status::ErrorImportEmptyKeyData();
382 DCHECK(key); 564 DCHECK(key);
383 565
384 // Parse the incoming JWK JSON. 566 // Parse the incoming JWK JSON.
385 base::StringPiece json_string(reinterpret_cast<const char*>(key_data.bytes()), 567 base::StringPiece json_string(reinterpret_cast<const char*>(key_data.bytes()),
386 key_data.byte_length()); 568 key_data.byte_length());
387 scoped_ptr<base::Value> value(base::JSONReader::Read(json_string)); 569 scoped_ptr<base::Value> value(base::JSONReader::Read(json_string));
388 // Note, bare pointer dict_value is ok since it points into scoped value. 570 // Note, bare pointer dict_value is ok since it points into scoped value.
389 base::DictionaryValue* dict_value = NULL; 571 base::DictionaryValue* dict_value = NULL;
390 if (!value.get() || !value->GetAsDictionary(&dict_value) || !dict_value) 572 if (!value.get() || !value->GetAsDictionary(&dict_value) || !dict_value)
391 return Status::ErrorJwkNotDictionary(); 573 return Status::ErrorJwkNotDictionary();
392 574
393 // JWK "kty". Exit early if this required JWK parameter is missing. 575 // JWK "kty". Exit early if this required JWK parameter is missing.
394 std::string jwk_kty_value; 576 std::string jwk_kty_value;
395 Status status = GetJwkString(dict_value, "kty", &jwk_kty_value); 577 Status status = GetJwkString(dict_value, "kty", &jwk_kty_value);
396 if (status.IsError()) 578 if (status.IsError())
397 return status; 579 return status;
398 580
399 // JWK "extractable" (optional) --> extractable parameter 581 // JWK "ext" (optional) --> extractable parameter
400 { 582 {
401 bool jwk_extractable_value = false; 583 bool jwk_ext_value = false;
402 bool has_jwk_extractable; 584 bool has_jwk_ext;
403 status = GetOptionalJwkBool(dict_value, 585 status =
404 "extractable", 586 GetOptionalJwkBool(dict_value, "ext", &jwk_ext_value, &has_jwk_ext);
405 &jwk_extractable_value,
406 &has_jwk_extractable);
407 if (status.IsError()) 587 if (status.IsError())
408 return status; 588 return status;
409 if (has_jwk_extractable && !jwk_extractable_value && extractable) 589 if (has_jwk_ext && !jwk_ext_value && extractable)
410 return Status::ErrorJwkExtractableInconsistent(); 590 return Status::ErrorJwkExtInconsistent();
411 } 591 }
412 592
413 // JWK "alg" (optional) --> algorithm parameter 593 // JWK "alg" (optional) --> algorithm parameter
414 // Note: input algorithm is also optional, so we have six cases to handle. 594 // Note: input algorithm is also optional, so we have six cases to handle.
415 // 1. JWK alg present but unrecognized: error 595 // 1. JWK alg present but unrecognized: error
416 // 2. JWK alg valid AND input algorithm isNull: use JWK value 596 // 2. JWK alg valid AND input algorithm isNull: use JWK value
417 // 3. JWK alg valid AND input algorithm specified, but JWK value 597 // 3. JWK alg valid AND input algorithm specified, but JWK value
418 // inconsistent with input: error 598 // inconsistent with input: error
419 // 4. JWK alg valid AND input algorithm specified, both consistent: use 599 // 4. JWK alg valid AND input algorithm specified, both consistent: use
420 // input value (because it has potentially more details) 600 // input value (because it has potentially more details)
(...skipping 32 matching lines...) Expand 10 before | Expand all | Expand 10 after
453 algorithm = algorithm_or_null; // case 4 633 algorithm = algorithm_or_null; // case 4
454 } 634 }
455 } else { 635 } else {
456 // JWK alg missing 636 // JWK alg missing
457 if (algorithm_or_null.isNull()) 637 if (algorithm_or_null.isNull())
458 return Status::ErrorJwkAlgorithmMissing(); // case 5 638 return Status::ErrorJwkAlgorithmMissing(); // case 5
459 algorithm = algorithm_or_null; // case 6 639 algorithm = algorithm_or_null; // case 6
460 } 640 }
461 DCHECK(!algorithm.isNull()); 641 DCHECK(!algorithm.isNull());
462 642
643 // JWK "key_ops" (optional) --> usage_mask parameter
644 base::ListValue* jwk_key_ops_value = NULL;
645 bool has_jwk_key_ops;
646 status = GetOptionalJwkList(
647 dict_value, "key_ops", &jwk_key_ops_value, &has_jwk_key_ops);
648 if (status.IsError())
649 return status;
650 blink::WebCryptoKeyUsageMask jwk_key_ops_mask = 0;
651 if (has_jwk_key_ops) {
652 status =
653 GetWebCryptoUsagesFromJwkKeyOps(jwk_key_ops_value, &jwk_key_ops_mask);
654 if (status.IsError())
655 return status;
656 // The input usage_mask must be a subset of jwk_key_ops_mask.
657 if (!ContainsKeyUsages(jwk_key_ops_mask, usage_mask))
658 return Status::ErrorJwkKeyopsInconsistent();
659 }
660
463 // JWK "use" (optional) --> usage_mask parameter 661 // JWK "use" (optional) --> usage_mask parameter
464 std::string jwk_use_value; 662 std::string jwk_use_value;
465 bool has_jwk_use; 663 bool has_jwk_use;
466 status = 664 status =
467 GetOptionalJwkString(dict_value, "use", &jwk_use_value, &has_jwk_use); 665 GetOptionalJwkString(dict_value, "use", &jwk_use_value, &has_jwk_use);
468 if (status.IsError()) 666 if (status.IsError())
469 return status; 667 return status;
668 blink::WebCryptoKeyUsageMask jwk_use_mask = 0;
470 if (has_jwk_use) { 669 if (has_jwk_use) {
471 blink::WebCryptoKeyUsageMask jwk_usage_mask = 0; 670 if (jwk_use_value == "enc")
472 if (jwk_use_value == "enc") { 671 jwk_use_mask = kJwkEncUsage;
473 jwk_usage_mask = 672 else if (jwk_use_value == "sig")
474 blink::WebCryptoKeyUsageEncrypt | blink::WebCryptoKeyUsageDecrypt; 673 jwk_use_mask = kJwkSigUsage;
475 } else if (jwk_use_value == "sig") { 674 else
476 jwk_usage_mask = 675 return Status::ErrorJwkUnrecognizedUse();
477 blink::WebCryptoKeyUsageSign | blink::WebCryptoKeyUsageVerify; 676 // The input usage_mask must be a subset of jwk_use_mask.
478 } else if (jwk_use_value == "wrap") { 677 if (!ContainsKeyUsages(jwk_use_mask, usage_mask))
479 jwk_usage_mask = 678 return Status::ErrorJwkUseInconsistent();
480 blink::WebCryptoKeyUsageWrapKey | blink::WebCryptoKeyUsageUnwrapKey;
481 } else {
482 return Status::ErrorJwkUnrecognizedUsage();
483 }
484 if ((jwk_usage_mask & usage_mask) != usage_mask) {
485 // A usage_mask must be a subset of jwk_usage_mask.
486 return Status::ErrorJwkUsageInconsistent();
487 }
488 } 679 }
489 680
681 // If both 'key_ops' and 'use' are present, ensure they are consistent.
682 if (has_jwk_key_ops && has_jwk_use &&
683 !ContainsKeyUsages(jwk_use_mask, jwk_key_ops_mask))
684 return Status::ErrorJwkUseAndKeyopsInconsistent();
685
490 // JWK keying material --> ImportKeyInternal() 686 // JWK keying material --> ImportKeyInternal()
491 if (jwk_kty_value == "oct") { 687 if (jwk_kty_value == "oct") {
492 688
493 std::string jwk_k_value; 689 std::string jwk_k_value;
494 status = GetJwkBytes(dict_value, "k", &jwk_k_value); 690 status = GetJwkBytes(dict_value, "k", &jwk_k_value);
495 if (status.IsError()) 691 if (status.IsError())
496 return status; 692 return status;
497 693
498 // Some JWK alg ID's embed information about the key length in the alg ID 694 // Some JWK alg ID's embed information about the key length in the alg ID
499 // string. For example "A128CBC" implies the JWK carries 128 bits 695 // string. For example "A128CBC" implies the JWK carries 128 bits
(...skipping 42 matching lines...) Expand 10 before | Expand all | Expand 10 after
542 CryptoData(jwk_e_value), 738 CryptoData(jwk_e_value),
543 key); 739 key);
544 740
545 } else { 741 } else {
546 return Status::ErrorJwkUnrecognizedKty(); 742 return Status::ErrorJwkUnrecognizedKty();
547 } 743 }
548 744
549 return Status::Success(); 745 return Status::Success();
550 } 746 }
551 747
748 Status ExportKeyJwk(const blink::WebCryptoKey& key,
749 blink::WebArrayBuffer* buffer) {
750 base::DictionaryValue jwk_dict;
751 Status status = Status::Error();
752 blink::WebArrayBuffer exported_key;
753
754 if (key.type() == blink::WebCryptoKeyTypeSecret) {
755 status = ExportKey(blink::WebCryptoKeyFormatRaw, key, &exported_key);
756 if (status.IsError())
757 return status;
758 WriteSecretKey(exported_key, &jwk_dict);
759 } else {
760 // TODO(padolph): Handle asymmetric keys, at least the public key.
761 return Status::ErrorUnsupported();
762 }
763
764 WriteKeyOps(key.usages(), &jwk_dict);
765 WriteExt(key.extractable(), &jwk_dict);
766 status = WriteAlg(key.algorithm(), exported_key.byteLength(), &jwk_dict);
767 if (status.IsError())
768 return status;
769
770 std::string json;
771 base::JSONWriter::Write(&jwk_dict, &json);
772 *buffer = CreateArrayBuffer(reinterpret_cast<const uint8*>(json.data()),
773 json.size());
774 return Status::Success();
775 }
776
552 } // namespace webcrypto 777 } // namespace webcrypto
553 778
554 } // namespace content 779 } // namespace content
OLDNEW
« no previous file with comments | « no previous file | content/child/webcrypto/shared_crypto.h » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698