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
3 // found in the LICENSE file.
5 #include "base/logging.h"
6 #include "base/stl_util.h"
7 #include "content/child/webcrypto/algorithm_dispatch.h"
8 #include "content/child/webcrypto/crypto_data.h"
9 #include "content/child/webcrypto/status.h"
10 #include "content/child/webcrypto/test/test_helpers.h"
11 #include "content/child/webcrypto/webcrypto_util.h"
12 #include "testing/gtest/include/gtest/gtest.h"
13 #include "third_party/WebKit/public/platform/WebCryptoAlgorithmParams.h"
14 #include "third_party/WebKit/public/platform/WebCryptoKeyAlgorithm.h"
22 // Creates an HMAC algorithm whose parameters struct is compatible with key
23 // generation. It is an error to call this with a hash_id that is not a SHA*.
24 // The key_length_bits parameter is optional, with zero meaning unspecified.
25 blink::WebCryptoAlgorithm
CreateHmacKeyGenAlgorithm(
26 blink::WebCryptoAlgorithmId hash_id
,
27 unsigned int key_length_bits
) {
28 DCHECK(blink::WebCryptoAlgorithm::isHash(hash_id
));
29 // key_length_bytes == 0 means unspecified
30 return blink::WebCryptoAlgorithm::adoptParamsAndCreate(
31 blink::WebCryptoAlgorithmIdHmac
,
32 new blink::WebCryptoHmacKeyGenParams(
33 CreateAlgorithm(hash_id
), (key_length_bits
!= 0), key_length_bits
));
36 TEST(WebCryptoHmacTest
, HMACSampleSets
) {
37 scoped_ptr
<base::ListValue
> tests
;
38 ASSERT_TRUE(ReadJsonTestFileToList("hmac.json", &tests
));
39 for (size_t test_index
= 0; test_index
< tests
->GetSize(); ++test_index
) {
40 SCOPED_TRACE(test_index
);
41 base::DictionaryValue
* test
;
42 ASSERT_TRUE(tests
->GetDictionary(test_index
, &test
));
44 blink::WebCryptoAlgorithm test_hash
= GetDigestAlgorithm(test
, "hash");
45 const std::vector
<uint8_t> test_key
= GetBytesFromHexString(test
, "key");
46 const std::vector
<uint8_t> test_message
=
47 GetBytesFromHexString(test
, "message");
48 const std::vector
<uint8_t> test_mac
= GetBytesFromHexString(test
, "mac");
50 blink::WebCryptoAlgorithm algorithm
=
51 CreateAlgorithm(blink::WebCryptoAlgorithmIdHmac
);
53 blink::WebCryptoAlgorithm import_algorithm
=
54 CreateHmacImportAlgorithm(test_hash
.id());
56 blink::WebCryptoKey key
= ImportSecretKeyFromRaw(
59 blink::WebCryptoKeyUsageSign
| blink::WebCryptoKeyUsageVerify
);
61 EXPECT_EQ(test_hash
.id(), key
.algorithm().hmacParams()->hash().id());
62 EXPECT_EQ(test_key
.size() * 8, key
.algorithm().hmacParams()->lengthBits());
64 // Verify exported raw key is identical to the imported data
65 std::vector
<uint8_t> raw_key
;
66 EXPECT_EQ(Status::Success(),
67 ExportKey(blink::WebCryptoKeyFormatRaw
, key
, &raw_key
));
68 EXPECT_BYTES_EQ(test_key
, raw_key
);
70 std::vector
<uint8_t> output
;
72 ASSERT_EQ(Status::Success(),
73 Sign(algorithm
, key
, CryptoData(test_message
), &output
));
75 EXPECT_BYTES_EQ(test_mac
, output
);
77 bool signature_match
= false;
78 EXPECT_EQ(Status::Success(),
82 CryptoData(test_message
),
84 EXPECT_TRUE(signature_match
);
86 // Ensure truncated signature does not verify by passing one less byte.
87 EXPECT_EQ(Status::Success(),
90 CryptoData(vector_as_array(&output
), output
.size() - 1),
91 CryptoData(test_message
),
93 EXPECT_FALSE(signature_match
);
95 // Ensure truncated signature does not verify by passing no bytes.
96 EXPECT_EQ(Status::Success(),
100 CryptoData(test_message
),
102 EXPECT_FALSE(signature_match
);
104 // Ensure extra long signature does not cause issues and fails.
105 const unsigned char kLongSignature
[1024] = {0};
106 EXPECT_EQ(Status::Success(),
109 CryptoData(kLongSignature
, sizeof(kLongSignature
)),
110 CryptoData(test_message
),
112 EXPECT_FALSE(signature_match
);
116 TEST(WebCryptoHmacTest
, GenerateKeyIsRandom
) {
117 // Generate a small sample of HMAC keys.
118 std::vector
<std::vector
<uint8_t> > keys
;
119 for (int i
= 0; i
< 16; ++i
) {
120 std::vector
<uint8_t> key_bytes
;
121 blink::WebCryptoKey key
;
122 blink::WebCryptoAlgorithm algorithm
=
123 CreateHmacKeyGenAlgorithm(blink::WebCryptoAlgorithmIdSha1
, 512);
124 ASSERT_EQ(Status::Success(), GenerateSecretKey(algorithm
, true, 0, &key
));
125 EXPECT_FALSE(key
.isNull());
126 EXPECT_TRUE(key
.handle());
127 EXPECT_EQ(blink::WebCryptoKeyTypeSecret
, key
.type());
128 EXPECT_EQ(blink::WebCryptoAlgorithmIdHmac
, key
.algorithm().id());
129 EXPECT_EQ(blink::WebCryptoAlgorithmIdSha1
,
130 key
.algorithm().hmacParams()->hash().id());
131 EXPECT_EQ(512u, key
.algorithm().hmacParams()->lengthBits());
133 std::vector
<uint8_t> raw_key
;
134 ASSERT_EQ(Status::Success(),
135 ExportKey(blink::WebCryptoKeyFormatRaw
, key
, &raw_key
));
136 EXPECT_EQ(64U, raw_key
.size());
137 keys
.push_back(raw_key
);
139 // Ensure all entries in the key sample set are unique. This is a simplistic
140 // estimate of whether the generated keys appear random.
141 EXPECT_FALSE(CopiesExist(keys
));
144 // If the key length is not provided, then the block size is used.
145 TEST(WebCryptoHmacTest
, GenerateKeyNoLengthSha1
) {
146 blink::WebCryptoKey key
;
147 blink::WebCryptoAlgorithm algorithm
=
148 CreateHmacKeyGenAlgorithm(blink::WebCryptoAlgorithmIdSha1
, 0);
149 ASSERT_EQ(Status::Success(), GenerateSecretKey(algorithm
, true, 0, &key
));
150 EXPECT_TRUE(key
.handle());
151 EXPECT_EQ(blink::WebCryptoKeyTypeSecret
, key
.type());
152 EXPECT_EQ(blink::WebCryptoAlgorithmIdHmac
, key
.algorithm().id());
153 EXPECT_EQ(blink::WebCryptoAlgorithmIdSha1
,
154 key
.algorithm().hmacParams()->hash().id());
155 EXPECT_EQ(512u, key
.algorithm().hmacParams()->lengthBits());
156 std::vector
<uint8_t> raw_key
;
157 ASSERT_EQ(Status::Success(),
158 ExportKey(blink::WebCryptoKeyFormatRaw
, key
, &raw_key
));
159 EXPECT_EQ(64U, raw_key
.size());
162 // If the key length is not provided, then the block size is used.
163 TEST(WebCryptoHmacTest
, GenerateKeyNoLengthSha512
) {
164 blink::WebCryptoKey key
;
165 blink::WebCryptoAlgorithm algorithm
=
166 CreateHmacKeyGenAlgorithm(blink::WebCryptoAlgorithmIdSha512
, 0);
167 ASSERT_EQ(Status::Success(), GenerateSecretKey(algorithm
, true, 0, &key
));
168 EXPECT_EQ(blink::WebCryptoAlgorithmIdHmac
, key
.algorithm().id());
169 EXPECT_EQ(blink::WebCryptoAlgorithmIdSha512
,
170 key
.algorithm().hmacParams()->hash().id());
171 EXPECT_EQ(1024u, key
.algorithm().hmacParams()->lengthBits());
172 std::vector
<uint8_t> raw_key
;
173 ASSERT_EQ(Status::Success(),
174 ExportKey(blink::WebCryptoKeyFormatRaw
, key
, &raw_key
));
175 EXPECT_EQ(128U, raw_key
.size());
178 TEST(WebCryptoHmacTest
, ImportKeyJwkKeyOpsSignVerify
) {
179 blink::WebCryptoKey key
;
180 base::DictionaryValue dict
;
181 dict
.SetString("kty", "oct");
182 dict
.SetString("k", "GADWrMRHwQfoNaXU5fZvTg==");
183 base::ListValue
* key_ops
= new base::ListValue
;
184 dict
.Set("key_ops", key_ops
); // Takes ownership.
186 key_ops
->AppendString("sign");
188 EXPECT_EQ(Status::Success(),
189 ImportKeyJwkFromDict(
191 CreateHmacImportAlgorithm(blink::WebCryptoAlgorithmIdSha256
),
193 blink::WebCryptoKeyUsageSign
,
196 EXPECT_EQ(blink::WebCryptoKeyUsageSign
, key
.usages());
198 key_ops
->AppendString("verify");
200 EXPECT_EQ(Status::Success(),
201 ImportKeyJwkFromDict(
203 CreateHmacImportAlgorithm(blink::WebCryptoAlgorithmIdSha256
),
205 blink::WebCryptoKeyUsageVerify
,
208 EXPECT_EQ(blink::WebCryptoKeyUsageVerify
, key
.usages());
211 // Test 'use' inconsistent with 'key_ops'.
212 TEST(WebCryptoHmacTest
, ImportKeyJwkUseInconsisteWithKeyOps
) {
213 blink::WebCryptoKey key
;
214 base::DictionaryValue dict
;
215 dict
.SetString("kty", "oct");
216 dict
.SetString("k", "GADWrMRHwQfoNaXU5fZvTg==");
217 base::ListValue
* key_ops
= new base::ListValue
;
218 dict
.Set("key_ops", key_ops
); // Takes ownership.
220 dict
.SetString("alg", "HS256");
221 dict
.SetString("use", "sig");
222 key_ops
->AppendString("sign");
223 key_ops
->AppendString("verify");
224 key_ops
->AppendString("encrypt");
225 EXPECT_EQ(Status::ErrorJwkUseAndKeyopsInconsistent(),
226 ImportKeyJwkFromDict(
228 CreateHmacImportAlgorithm(blink::WebCryptoAlgorithmIdSha256
),
230 blink::WebCryptoKeyUsageSign
| blink::WebCryptoKeyUsageVerify
,
234 // Test JWK composite 'sig' use
235 TEST(WebCryptoHmacTest
, ImportKeyJwkUseSig
) {
236 blink::WebCryptoKey key
;
237 base::DictionaryValue dict
;
238 dict
.SetString("kty", "oct");
239 dict
.SetString("k", "GADWrMRHwQfoNaXU5fZvTg==");
241 dict
.SetString("use", "sig");
242 EXPECT_EQ(Status::Success(),
243 ImportKeyJwkFromDict(
245 CreateHmacImportAlgorithm(blink::WebCryptoAlgorithmIdSha256
),
247 blink::WebCryptoKeyUsageSign
| blink::WebCryptoKeyUsageVerify
,
250 EXPECT_EQ(blink::WebCryptoKeyUsageSign
| blink::WebCryptoKeyUsageVerify
,
254 TEST(WebCryptoHmacTest
, ImportJwkInputConsistency
) {
255 // The Web Crypto spec says that if a JWK value is present, but is
256 // inconsistent with the input value, the operation must fail.
258 // Consistency rules when JWK value is not present: Inputs should be used.
259 blink::WebCryptoKey key
;
260 bool extractable
= false;
261 blink::WebCryptoAlgorithm algorithm
=
262 CreateHmacImportAlgorithm(blink::WebCryptoAlgorithmIdSha256
);
263 blink::WebCryptoKeyUsageMask usages
= blink::WebCryptoKeyUsageVerify
;
264 base::DictionaryValue dict
;
265 dict
.SetString("kty", "oct");
266 dict
.SetString("k", "l3nZEgZCeX8XRwJdWyK3rGB8qwjhdY8vOkbIvh4lxTuMao9Y_--hdg");
267 std::vector
<uint8_t> json_vec
= MakeJsonVector(dict
);
268 EXPECT_EQ(Status::Success(),
269 ImportKey(blink::WebCryptoKeyFormatJwk
,
270 CryptoData(json_vec
),
275 EXPECT_TRUE(key
.handle());
276 EXPECT_EQ(blink::WebCryptoKeyTypeSecret
, key
.type());
277 EXPECT_EQ(extractable
, key
.extractable());
278 EXPECT_EQ(blink::WebCryptoAlgorithmIdHmac
, key
.algorithm().id());
279 EXPECT_EQ(blink::WebCryptoAlgorithmIdSha256
,
280 key
.algorithm().hmacParams()->hash().id());
281 EXPECT_EQ(320u, key
.algorithm().hmacParams()->lengthBits());
282 EXPECT_EQ(blink::WebCryptoKeyUsageVerify
, key
.usages());
283 key
= blink::WebCryptoKey::createNull();
285 // Consistency rules when JWK value exists: Fail if inconsistency is found.
287 // Pass: All input values are consistent with the JWK values.
289 dict
.SetString("kty", "oct");
290 dict
.SetString("alg", "HS256");
291 dict
.SetString("use", "sig");
292 dict
.SetBoolean("ext", false);
293 dict
.SetString("k", "l3nZEgZCeX8XRwJdWyK3rGB8qwjhdY8vOkbIvh4lxTuMao9Y_--hdg");
294 json_vec
= MakeJsonVector(dict
);
295 EXPECT_EQ(Status::Success(),
296 ImportKey(blink::WebCryptoKeyFormatJwk
,
297 CryptoData(json_vec
),
303 // Extractable cases:
304 // 1. input=T, JWK=F ==> fail (inconsistent)
305 // 4. input=F, JWK=F ==> pass, result extractable is F
306 // 2. input=T, JWK=T ==> pass, result extractable is T
307 // 3. input=F, JWK=T ==> pass, result extractable is F
308 EXPECT_EQ(Status::ErrorJwkExtInconsistent(),
309 ImportKey(blink::WebCryptoKeyFormatJwk
,
310 CryptoData(json_vec
),
315 EXPECT_EQ(Status::Success(),
316 ImportKey(blink::WebCryptoKeyFormatJwk
,
317 CryptoData(json_vec
),
322 EXPECT_FALSE(key
.extractable());
323 dict
.SetBoolean("ext", true);
324 EXPECT_EQ(Status::Success(),
325 ImportKeyJwkFromDict(dict
, algorithm
, true, usages
, &key
));
326 EXPECT_TRUE(key
.extractable());
327 EXPECT_EQ(Status::Success(),
328 ImportKeyJwkFromDict(dict
, algorithm
, false, usages
, &key
));
329 EXPECT_FALSE(key
.extractable());
330 dict
.SetBoolean("ext", true); // restore previous value
332 // Fail: Input algorithm (AES-CBC) is inconsistent with JWK value
335 dict
.SetString("kty", "oct");
336 dict
.SetString("alg", "HS256");
337 dict
.SetString("k", "l3nZEgZCeX8XRwJdWyK3rGB8qwjhdY8vOkbIvh4lxTuMao9Y_--hdg");
339 Status::ErrorJwkAlgorithmInconsistent(),
340 ImportKeyJwkFromDict(dict
,
341 CreateAlgorithm(blink::WebCryptoAlgorithmIdAesCbc
),
343 blink::WebCryptoKeyUsageEncrypt
,
345 // Fail: Input usage (encrypt) is inconsistent with JWK value (use=sig).
346 EXPECT_EQ(Status::ErrorJwkUseInconsistent(),
347 ImportKey(blink::WebCryptoKeyFormatJwk
,
348 CryptoData(json_vec
),
349 CreateAlgorithm(blink::WebCryptoAlgorithmIdAesCbc
),
351 blink::WebCryptoKeyUsageEncrypt
,
354 // Fail: Input algorithm (HMAC SHA1) is inconsistent with JWK value
357 Status::ErrorJwkAlgorithmInconsistent(),
358 ImportKey(blink::WebCryptoKeyFormatJwk
,
359 CryptoData(json_vec
),
360 CreateHmacImportAlgorithm(blink::WebCryptoAlgorithmIdSha1
),
365 // Pass: JWK alg missing but input algorithm specified: use input value
366 dict
.Remove("alg", NULL
);
367 EXPECT_EQ(Status::Success(),
368 ImportKeyJwkFromDict(
370 CreateHmacImportAlgorithm(blink::WebCryptoAlgorithmIdSha256
),
374 EXPECT_EQ(blink::WebCryptoAlgorithmIdHmac
, algorithm
.id());
375 dict
.SetString("alg", "HS256");
377 // Fail: Input usages (encrypt) is not a subset of the JWK value
378 // (sign|verify). Moreover "encrypt" is not a valid usage for HMAC.
379 EXPECT_EQ(Status::ErrorCreateKeyBadUsages(),
380 ImportKey(blink::WebCryptoKeyFormatJwk
,
381 CryptoData(json_vec
),
384 blink::WebCryptoKeyUsageEncrypt
,
387 // Fail: Input usages (encrypt|sign|verify) is not a subset of the JWK
388 // value (sign|verify). Moreover "encrypt" is not a valid usage for HMAC.
389 usages
= blink::WebCryptoKeyUsageEncrypt
| blink::WebCryptoKeyUsageSign
|
390 blink::WebCryptoKeyUsageVerify
;
391 EXPECT_EQ(Status::ErrorCreateKeyBadUsages(),
392 ImportKey(blink::WebCryptoKeyFormatJwk
,
393 CryptoData(json_vec
),
399 // TODO(padolph): kty vs alg consistency tests: Depending on the kty value,
400 // only certain alg values are permitted. For example, when kty = "RSA" alg
401 // must be of the RSA family, or when kty = "oct" alg must be symmetric
404 // TODO(padolph): key_ops consistency tests
407 TEST(WebCryptoHmacTest
, ImportJwkHappy
) {
408 // This test verifies the happy path of JWK import, including the application
409 // of the imported key material.
411 blink::WebCryptoKey key
;
412 bool extractable
= false;
413 blink::WebCryptoAlgorithm algorithm
=
414 CreateHmacImportAlgorithm(blink::WebCryptoAlgorithmIdSha256
);
415 blink::WebCryptoKeyUsageMask usages
= blink::WebCryptoKeyUsageSign
;
417 // Import a symmetric key JWK and HMAC-SHA256 sign()
418 // Uses the first SHA256 test vector from the HMAC sample set above.
420 base::DictionaryValue dict
;
421 dict
.SetString("kty", "oct");
422 dict
.SetString("alg", "HS256");
423 dict
.SetString("use", "sig");
424 dict
.SetBoolean("ext", false);
425 dict
.SetString("k", "l3nZEgZCeX8XRwJdWyK3rGB8qwjhdY8vOkbIvh4lxTuMao9Y_--hdg");
427 ASSERT_EQ(Status::Success(),
428 ImportKeyJwkFromDict(dict
, algorithm
, extractable
, usages
, &key
));
430 EXPECT_EQ(blink::WebCryptoAlgorithmIdSha256
,
431 key
.algorithm().hmacParams()->hash().id());
433 const std::vector
<uint8_t> message_raw
= HexStringToBytes(
434 "b1689c2591eaf3c9e66070f8a77954ffb81749f1b00346f9dfe0b2ee905dcc288baf4a"
435 "92de3f4001dd9f44c468c3d07d6c6ee82faceafc97c2fc0fc0601719d2dcd0aa2aec92"
436 "d1b0ae933c65eb06a03c9c935c2bad0459810241347ab87e9f11adb30415424c6c7f5f"
437 "22a003b8ab8de54f6ded0e3ab9245fa79568451dfa258e");
439 std::vector
<uint8_t> output
;
441 ASSERT_EQ(Status::Success(),
442 Sign(CreateAlgorithm(blink::WebCryptoAlgorithmIdHmac
),
444 CryptoData(message_raw
),
447 const std::string mac_raw
=
448 "769f00d3e6a6cc1fb426a14a4f76c6462e6149726e0dee0ec0cf97a16605ac8b";
450 EXPECT_BYTES_EQ_HEX(mac_raw
, output
);
452 // TODO(padolph): Import an RSA public key JWK and use it
455 TEST(WebCryptoHmacTest
, ImportExportJwk
) {
457 ImportExportJwkSymmetricKey(
459 CreateHmacImportAlgorithm(blink::WebCryptoAlgorithmIdSha1
),
460 blink::WebCryptoKeyUsageSign
| blink::WebCryptoKeyUsageVerify
,
464 ImportExportJwkSymmetricKey(
466 CreateHmacImportAlgorithm(blink::WebCryptoAlgorithmIdSha384
),
467 blink::WebCryptoKeyUsageSign
,
471 ImportExportJwkSymmetricKey(
473 CreateHmacImportAlgorithm(blink::WebCryptoAlgorithmIdSha512
),
474 blink::WebCryptoKeyUsageVerify
,
478 ImportExportJwkSymmetricKey(
480 CreateHmacImportAlgorithm(blink::WebCryptoAlgorithmIdSha512
),
485 TEST(WebCryptoHmacTest
, ExportJwkEmptyKey
) {
486 const blink::WebCryptoAlgorithm import_algorithm
=
487 CreateHmacImportAlgorithm(blink::WebCryptoAlgorithmIdSha1
);
489 blink::WebCryptoKeyUsageMask usages
= blink::WebCryptoKeyUsageSign
;
490 blink::WebCryptoKey key
;
492 // Import a zero-byte HMAC key.
493 const char key_data_hex
[] = "";
494 key
= ImportSecretKeyFromRaw(
495 HexStringToBytes(key_data_hex
), import_algorithm
, usages
);
496 EXPECT_EQ(0u, key
.algorithm().hmacParams()->lengthBits());
498 // Export the key in JWK format and validate.
499 std::vector
<uint8_t> json
;
500 ASSERT_EQ(Status::Success(),
501 ExportKey(blink::WebCryptoKeyFormatJwk
, key
, &json
));
502 EXPECT_TRUE(VerifySecretJwk(json
, "HS1", key_data_hex
, usages
));
504 // Now try re-importing the JWK key.
505 key
= blink::WebCryptoKey::createNull();
506 EXPECT_EQ(Status::Success(),
507 ImportKey(blink::WebCryptoKeyFormatJwk
,
514 EXPECT_EQ(blink::WebCryptoKeyTypeSecret
, key
.type());
515 EXPECT_EQ(0u, key
.algorithm().hmacParams()->lengthBits());
517 std::vector
<uint8_t> exported_key_data
;
518 EXPECT_EQ(Status::Success(),
519 ExportKey(blink::WebCryptoKeyFormatRaw
, key
, &exported_key_data
));
521 EXPECT_EQ(0u, exported_key_data
.size());
524 // Import a huge hmac key (UINT_MAX bytes). This will fail before actually
525 // reading the bytes, as the key is too large.
526 TEST(WebCryptoHmacTest
, ImportRawKeyTooLarge
) {
527 CryptoData
big_data(NULL
, UINT_MAX
); // Invalid data of big length.
529 blink::WebCryptoKey key
;
531 Status::ErrorDataTooLarge(),
532 ImportKey(blink::WebCryptoKeyFormatRaw
,
533 CryptoData(big_data
),
534 CreateHmacImportAlgorithm(blink::WebCryptoAlgorithmIdSha1
),
536 blink::WebCryptoKeyUsageSign
,
542 } // namespace webcrypto
544 } // namespace content