Map WebSocket URL schemes to HTTP URL schemes for auth purposes.
[chromium-blink-merge.git] / content / child / webcrypto / shared_crypto_unittest.cc
blobea2c624b62ecded08856a059dd1712c06acf1614
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 "content/child/webcrypto/shared_crypto.h"
7 #include <algorithm>
8 #include <string>
9 #include <vector>
11 #include "base/basictypes.h"
12 #include "base/file_util.h"
13 #include "base/json/json_reader.h"
14 #include "base/json/json_writer.h"
15 #include "base/logging.h"
16 #include "base/memory/ref_counted.h"
17 #include "base/path_service.h"
18 #include "base/strings/string_number_conversions.h"
19 #include "base/strings/string_util.h"
20 #include "base/strings/stringprintf.h"
21 #include "content/child/webcrypto/crypto_data.h"
22 #include "content/child/webcrypto/status.h"
23 #include "content/child/webcrypto/webcrypto_util.h"
24 #include "content/public/common/content_paths.h"
25 #include "testing/gtest/include/gtest/gtest.h"
26 #include "third_party/WebKit/public/platform/WebCryptoAlgorithm.h"
27 #include "third_party/WebKit/public/platform/WebCryptoAlgorithmParams.h"
28 #include "third_party/WebKit/public/platform/WebCryptoKey.h"
29 #include "third_party/WebKit/public/platform/WebCryptoKeyAlgorithm.h"
30 #include "third_party/re2/re2/re2.h"
32 #if !defined(USE_OPENSSL)
33 #include <nss.h>
34 #include <pk11pub.h>
36 #include "crypto/scoped_nss_types.h"
37 #endif
39 // The OpenSSL implementation of WebCrypto is less complete, so don't run all of
40 // the tests: http://crbug.com/267888
41 #if defined(USE_OPENSSL)
42 #define MAYBE(test_name) DISABLED_##test_name
43 #else
44 #define MAYBE(test_name) test_name
45 #endif
47 #define EXPECT_BYTES_EQ(expected, actual) \
48 EXPECT_EQ(CryptoData(expected), CryptoData(actual))
50 #define EXPECT_BYTES_EQ_HEX(expected_hex, actual_bytes) \
51 EXPECT_BYTES_EQ(HexStringToBytes(expected_hex), actual_bytes)
53 namespace content {
55 namespace webcrypto {
57 // These functions are used by GTEST to support EXPECT_EQ() for
58 // webcrypto::Status and webcrypto::CryptoData
60 void PrintTo(const Status& status, ::std::ostream* os) {
61 if (status.IsSuccess())
62 *os << "Success";
63 else
64 *os << "Error type: " << status.error_type()
65 << " Error details: " << status.error_details();
68 bool operator==(const content::webcrypto::Status& a,
69 const content::webcrypto::Status& b) {
70 if (a.IsSuccess() != b.IsSuccess())
71 return false;
72 if (a.IsSuccess())
73 return true;
74 return a.error_type() == b.error_type() &&
75 a.error_details() == b.error_details();
78 bool operator!=(const content::webcrypto::Status& a,
79 const content::webcrypto::Status& b) {
80 return !(a == b);
83 void PrintTo(const CryptoData& data, ::std::ostream* os) {
84 *os << "[" << base::HexEncode(data.bytes(), data.byte_length()) << "]";
87 bool operator==(const content::webcrypto::CryptoData& a,
88 const content::webcrypto::CryptoData& b) {
89 return a.byte_length() == b.byte_length() &&
90 memcmp(a.bytes(), b.bytes(), a.byte_length()) == 0;
93 bool operator!=(const content::webcrypto::CryptoData& a,
94 const content::webcrypto::CryptoData& b) {
95 return !(a == b);
98 namespace {
100 // -----------------------------------------------------------------------------
102 // TODO(eroman): For Linux builds using system NSS, AES-GCM support is a
103 // runtime dependency. Test it by trying to import a key.
104 // TODO(padolph): Consider caching the result of the import key test.
105 bool SupportsAesGcm() {
106 std::vector<uint8> key_raw(16, 0);
108 blink::WebCryptoKey key = blink::WebCryptoKey::createNull();
109 Status status = ImportKey(blink::WebCryptoKeyFormatRaw,
110 CryptoData(key_raw),
111 CreateAlgorithm(blink::WebCryptoAlgorithmIdAesGcm),
112 true,
113 blink::WebCryptoKeyUsageEncrypt,
114 &key);
116 if (status.IsError())
117 EXPECT_EQ(blink::WebCryptoErrorTypeNotSupported, status.error_type());
118 return status.IsSuccess();
121 bool SupportsRsaOaep() {
122 #if defined(USE_OPENSSL)
123 return false;
124 #else
125 // TODO(eroman): Exclude version test for OS_CHROMEOS
126 #if defined(USE_NSS)
127 if (!NSS_VersionCheck("3.16.2"))
128 return false;
129 #endif
130 crypto::ScopedPK11Slot slot(PK11_GetInternalKeySlot());
131 return !!PK11_DoesMechanism(slot.get(), CKM_RSA_PKCS_OAEP);
132 #endif
135 bool SupportsRsaKeyImport() {
136 // TODO(eroman): Exclude version test for OS_CHROMEOS
137 #if defined(USE_NSS)
138 if (!NSS_VersionCheck("3.16.2")) {
139 LOG(WARNING) << "RSA key import is not supported by this version of NSS. "
140 "Skipping some tests";
141 return false;
143 #endif
144 return true;
147 blink::WebCryptoAlgorithm CreateRsaHashedKeyGenAlgorithm(
148 blink::WebCryptoAlgorithmId algorithm_id,
149 const blink::WebCryptoAlgorithmId hash_id,
150 unsigned int modulus_length,
151 const std::vector<uint8>& public_exponent) {
152 DCHECK(algorithm_id == blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5 ||
153 algorithm_id == blink::WebCryptoAlgorithmIdRsaOaep);
154 DCHECK(blink::WebCryptoAlgorithm::isHash(hash_id));
155 return blink::WebCryptoAlgorithm::adoptParamsAndCreate(
156 algorithm_id,
157 new blink::WebCryptoRsaHashedKeyGenParams(
158 CreateAlgorithm(hash_id),
159 modulus_length,
160 webcrypto::Uint8VectorStart(public_exponent),
161 public_exponent.size()));
164 // Creates an RSA-OAEP algorithm
165 blink::WebCryptoAlgorithm CreateRsaOaepAlgorithm(
166 const std::vector<uint8>& label) {
167 return blink::WebCryptoAlgorithm::adoptParamsAndCreate(
168 blink::WebCryptoAlgorithmIdRsaOaep,
169 new blink::WebCryptoRsaOaepParams(
170 !label.empty(), Uint8VectorStart(label), label.size()));
173 // Creates an AES-CBC algorithm.
174 blink::WebCryptoAlgorithm CreateAesCbcAlgorithm(const std::vector<uint8>& iv) {
175 return blink::WebCryptoAlgorithm::adoptParamsAndCreate(
176 blink::WebCryptoAlgorithmIdAesCbc,
177 new blink::WebCryptoAesCbcParams(Uint8VectorStart(iv), iv.size()));
180 // Creates an AES-GCM algorithm.
181 blink::WebCryptoAlgorithm CreateAesGcmAlgorithm(
182 const std::vector<uint8>& iv,
183 const std::vector<uint8>& additional_data,
184 unsigned int tag_length_bits) {
185 EXPECT_TRUE(SupportsAesGcm());
186 return blink::WebCryptoAlgorithm::adoptParamsAndCreate(
187 blink::WebCryptoAlgorithmIdAesGcm,
188 new blink::WebCryptoAesGcmParams(Uint8VectorStart(iv),
189 iv.size(),
190 true,
191 Uint8VectorStart(additional_data),
192 additional_data.size(),
193 true,
194 tag_length_bits));
197 // Creates an HMAC algorithm whose parameters struct is compatible with key
198 // generation. It is an error to call this with a hash_id that is not a SHA*.
199 // The key_length_bits parameter is optional, with zero meaning unspecified.
200 blink::WebCryptoAlgorithm CreateHmacKeyGenAlgorithm(
201 blink::WebCryptoAlgorithmId hash_id,
202 unsigned int key_length_bits) {
203 DCHECK(blink::WebCryptoAlgorithm::isHash(hash_id));
204 // key_length_bytes == 0 means unspecified
205 return blink::WebCryptoAlgorithm::adoptParamsAndCreate(
206 blink::WebCryptoAlgorithmIdHmac,
207 new blink::WebCryptoHmacKeyGenParams(
208 CreateAlgorithm(hash_id), (key_length_bits != 0), key_length_bits));
211 // Returns a slightly modified version of the input vector.
213 // - For non-empty inputs a single bit is inverted.
214 // - For empty inputs, a byte is added.
215 std::vector<uint8> Corrupted(const std::vector<uint8>& input) {
216 std::vector<uint8> corrupted_data(input);
217 if (corrupted_data.empty())
218 corrupted_data.push_back(0);
219 corrupted_data[corrupted_data.size() / 2] ^= 0x01;
220 return corrupted_data;
223 std::vector<uint8> HexStringToBytes(const std::string& hex) {
224 std::vector<uint8> bytes;
225 base::HexStringToBytes(hex, &bytes);
226 return bytes;
229 std::vector<uint8> MakeJsonVector(const std::string& json_string) {
230 return std::vector<uint8>(json_string.begin(), json_string.end());
233 std::vector<uint8> MakeJsonVector(const base::DictionaryValue& dict) {
234 std::string json;
235 base::JSONWriter::Write(&dict, &json);
236 return MakeJsonVector(json);
239 // ----------------------------------------------------------------
240 // Helpers for working with JSON data files for test expectations.
241 // ----------------------------------------------------------------
243 // Reads a file in "src/content/test/data/webcrypto" to a base::Value.
244 // The file must be JSON, however it can also include C++ style comments.
245 ::testing::AssertionResult ReadJsonTestFile(const char* test_file_name,
246 scoped_ptr<base::Value>* value) {
247 base::FilePath test_data_dir;
248 if (!PathService::Get(DIR_TEST_DATA, &test_data_dir))
249 return ::testing::AssertionFailure() << "Couldn't retrieve test dir";
251 base::FilePath file_path =
252 test_data_dir.AppendASCII("webcrypto").AppendASCII(test_file_name);
254 std::string file_contents;
255 if (!base::ReadFileToString(file_path, &file_contents)) {
256 return ::testing::AssertionFailure()
257 << "Couldn't read test file: " << file_path.value();
260 // Strip C++ style comments out of the "json" file, otherwise it cannot be
261 // parsed.
262 re2::RE2::GlobalReplace(&file_contents, re2::RE2("\\s*//.*"), "");
264 // Parse the JSON to a dictionary.
265 value->reset(base::JSONReader::Read(file_contents));
266 if (!value->get()) {
267 return ::testing::AssertionFailure()
268 << "Couldn't parse test file JSON: " << file_path.value();
271 return ::testing::AssertionSuccess();
274 // Same as ReadJsonTestFile(), but return the value as a List.
275 ::testing::AssertionResult ReadJsonTestFileToList(
276 const char* test_file_name,
277 scoped_ptr<base::ListValue>* list) {
278 // Read the JSON.
279 scoped_ptr<base::Value> json;
280 ::testing::AssertionResult result = ReadJsonTestFile(test_file_name, &json);
281 if (!result)
282 return result;
284 // Cast to an ListValue.
285 base::ListValue* list_value = NULL;
286 if (!json->GetAsList(&list_value) || !list_value)
287 return ::testing::AssertionFailure() << "The JSON was not a list";
289 list->reset(list_value);
290 ignore_result(json.release());
292 return ::testing::AssertionSuccess();
295 // Read a string property from the dictionary with path |property_name|
296 // (which can include periods for nested dictionaries). Interprets the
297 // string as a hex encoded string and converts it to a bytes list.
299 // Returns empty vector on failure.
300 std::vector<uint8> GetBytesFromHexString(base::DictionaryValue* dict,
301 const char* property_name) {
302 std::string hex_string;
303 if (!dict->GetString(property_name, &hex_string)) {
304 EXPECT_TRUE(false) << "Couldn't get string property: " << property_name;
305 return std::vector<uint8>();
308 return HexStringToBytes(hex_string);
311 // Reads a string property with path "property_name" and converts it to a
312 // WebCryptoAlgorith. Returns null algorithm on failure.
313 blink::WebCryptoAlgorithm GetDigestAlgorithm(base::DictionaryValue* dict,
314 const char* property_name) {
315 std::string algorithm_name;
316 if (!dict->GetString(property_name, &algorithm_name)) {
317 EXPECT_TRUE(false) << "Couldn't get string property: " << property_name;
318 return blink::WebCryptoAlgorithm::createNull();
321 struct {
322 const char* name;
323 blink::WebCryptoAlgorithmId id;
324 } kDigestNameToId[] = {
325 {"sha-1", blink::WebCryptoAlgorithmIdSha1},
326 {"sha-256", blink::WebCryptoAlgorithmIdSha256},
327 {"sha-384", blink::WebCryptoAlgorithmIdSha384},
328 {"sha-512", blink::WebCryptoAlgorithmIdSha512},
331 for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kDigestNameToId); ++i) {
332 if (kDigestNameToId[i].name == algorithm_name)
333 return CreateAlgorithm(kDigestNameToId[i].id);
336 return blink::WebCryptoAlgorithm::createNull();
339 // Helper for ImportJwkFailures and ImportJwkOctFailures. Restores the JWK JSON
340 // dictionary to a good state
341 void RestoreJwkOctDictionary(base::DictionaryValue* dict) {
342 dict->Clear();
343 dict->SetString("kty", "oct");
344 dict->SetString("alg", "A128CBC");
345 dict->SetString("use", "enc");
346 dict->SetBoolean("ext", false);
347 dict->SetString("k", "GADWrMRHwQfoNaXU5fZvTg==");
350 // Helper for ImportJwkRsaFailures. Restores the JWK JSON
351 // dictionary to a good state
352 void RestoreJwkRsaDictionary(base::DictionaryValue* dict) {
353 dict->Clear();
354 dict->SetString("kty", "RSA");
355 dict->SetString("alg", "RS256");
356 dict->SetString("use", "sig");
357 dict->SetBoolean("ext", false);
358 dict->SetString(
359 "n",
360 "qLOyhK-OtQs4cDSoYPFGxJGfMYdjzWxVmMiuSBGh4KvEx-CwgtaTpef87Wdc9GaFEncsDLxk"
361 "p0LGxjD1M8jMcvYq6DPEC_JYQumEu3i9v5fAEH1VvbZi9cTg-rmEXLUUjvc5LdOq_5OuHmtm"
362 "e7PUJHYW1PW6ENTP0ibeiNOfFvs");
363 dict->SetString("e", "AQAB");
366 // Returns true if any of the vectors in the input list have identical content.
367 // Dumb O(n^2) implementation but should be fast enough for the input sizes that
368 // are used.
369 bool CopiesExist(const std::vector<std::vector<uint8> >& bufs) {
370 for (size_t i = 0; i < bufs.size(); ++i) {
371 for (size_t j = i + 1; j < bufs.size(); ++j) {
372 if (CryptoData(bufs[i]) == CryptoData(bufs[j]))
373 return true;
376 return false;
379 blink::WebCryptoAlgorithm CreateAesKeyGenAlgorithm(
380 blink::WebCryptoAlgorithmId aes_alg_id,
381 unsigned short length) {
382 return blink::WebCryptoAlgorithm::adoptParamsAndCreate(
383 aes_alg_id, new blink::WebCryptoAesKeyGenParams(length));
386 blink::WebCryptoAlgorithm CreateAesCbcKeyGenAlgorithm(
387 unsigned short key_length_bits) {
388 return CreateAesKeyGenAlgorithm(blink::WebCryptoAlgorithmIdAesCbc,
389 key_length_bits);
392 blink::WebCryptoAlgorithm CreateAesGcmKeyGenAlgorithm(
393 unsigned short key_length_bits) {
394 EXPECT_TRUE(SupportsAesGcm());
395 return CreateAesKeyGenAlgorithm(blink::WebCryptoAlgorithmIdAesGcm,
396 key_length_bits);
399 blink::WebCryptoAlgorithm CreateAesKwKeyGenAlgorithm(
400 unsigned short key_length_bits) {
401 return CreateAesKeyGenAlgorithm(blink::WebCryptoAlgorithmIdAesKw,
402 key_length_bits);
405 // The following key pair is comprised of the SPKI (public key) and PKCS#8
406 // (private key) representations of the key pair provided in Example 1 of the
407 // NIST test vectors at
408 // ftp://ftp.rsa.com/pub/rsalabs/tmp/pkcs1v15sign-vectors.txt
409 const unsigned int kModulusLengthBits = 1024;
410 const char* const kPublicKeySpkiDerHex =
411 "30819f300d06092a864886f70d010101050003818d0030818902818100a5"
412 "6e4a0e701017589a5187dc7ea841d156f2ec0e36ad52a44dfeb1e61f7ad9"
413 "91d8c51056ffedb162b4c0f283a12a88a394dff526ab7291cbb307ceabfc"
414 "e0b1dfd5cd9508096d5b2b8b6df5d671ef6377c0921cb23c270a70e2598e"
415 "6ff89d19f105acc2d3f0cb35f29280e1386b6f64c4ef22e1e1f20d0ce8cf"
416 "fb2249bd9a21370203010001";
417 const char* const kPrivateKeyPkcs8DerHex =
418 "30820275020100300d06092a864886f70d01010105000482025f3082025b"
419 "02010002818100a56e4a0e701017589a5187dc7ea841d156f2ec0e36ad52"
420 "a44dfeb1e61f7ad991d8c51056ffedb162b4c0f283a12a88a394dff526ab"
421 "7291cbb307ceabfce0b1dfd5cd9508096d5b2b8b6df5d671ef6377c0921c"
422 "b23c270a70e2598e6ff89d19f105acc2d3f0cb35f29280e1386b6f64c4ef"
423 "22e1e1f20d0ce8cffb2249bd9a2137020301000102818033a5042a90b27d"
424 "4f5451ca9bbbd0b44771a101af884340aef9885f2a4bbe92e894a724ac3c"
425 "568c8f97853ad07c0266c8c6a3ca0929f1e8f11231884429fc4d9ae55fee"
426 "896a10ce707c3ed7e734e44727a39574501a532683109c2abacaba283c31"
427 "b4bd2f53c3ee37e352cee34f9e503bd80c0622ad79c6dcee883547c6a3b3"
428 "25024100e7e8942720a877517273a356053ea2a1bc0c94aa72d55c6e8629"
429 "6b2dfc967948c0a72cbccca7eacb35706e09a1df55a1535bd9b3cc34160b"
430 "3b6dcd3eda8e6443024100b69dca1cf7d4d7ec81e75b90fcca874abcde12"
431 "3fd2700180aa90479b6e48de8d67ed24f9f19d85ba275874f542cd20dc72"
432 "3e6963364a1f9425452b269a6799fd024028fa13938655be1f8a159cbaca"
433 "5a72ea190c30089e19cd274a556f36c4f6e19f554b34c077790427bbdd8d"
434 "d3ede2448328f385d81b30e8e43b2fffa02786197902401a8b38f398fa71"
435 "2049898d7fb79ee0a77668791299cdfa09efc0e507acb21ed74301ef5bfd"
436 "48be455eaeb6e1678255827580a8e4e8e14151d1510a82a3f2e729024027"
437 "156aba4126d24a81f3a528cbfb27f56886f840a9f6e86e17a44b94fe9319"
438 "584b8e22fdde1e5a2e3bd8aa5ba8d8584194eb2190acf832b847f13a3d24"
439 "a79f4d";
440 // The modulus and exponent (in hex) of kPublicKeySpkiDerHex
441 const char* const kPublicKeyModulusHex =
442 "A56E4A0E701017589A5187DC7EA841D156F2EC0E36AD52A44DFEB1E61F7AD991D8C51056"
443 "FFEDB162B4C0F283A12A88A394DFF526AB7291CBB307CEABFCE0B1DFD5CD9508096D5B2B"
444 "8B6DF5D671EF6377C0921CB23C270A70E2598E6FF89D19F105ACC2D3F0CB35F29280E138"
445 "6B6F64C4EF22E1E1F20D0CE8CFFB2249BD9A2137";
446 const char* const kPublicKeyExponentHex = "010001";
448 class SharedCryptoTest : public testing::Test {
449 protected:
450 virtual void SetUp() OVERRIDE { Init(); }
453 blink::WebCryptoKey ImportSecretKeyFromRaw(
454 const std::vector<uint8>& key_raw,
455 const blink::WebCryptoAlgorithm& algorithm,
456 blink::WebCryptoKeyUsageMask usage) {
457 blink::WebCryptoKey key = blink::WebCryptoKey::createNull();
458 bool extractable = true;
459 EXPECT_EQ(Status::Success(),
460 ImportKey(blink::WebCryptoKeyFormatRaw,
461 CryptoData(key_raw),
462 algorithm,
463 extractable,
464 usage,
465 &key));
467 EXPECT_FALSE(key.isNull());
468 EXPECT_TRUE(key.handle());
469 EXPECT_EQ(blink::WebCryptoKeyTypeSecret, key.type());
470 EXPECT_EQ(algorithm.id(), key.algorithm().id());
471 EXPECT_EQ(extractable, key.extractable());
472 EXPECT_EQ(usage, key.usages());
473 return key;
476 void ImportRsaKeyPair(const std::vector<uint8>& spki_der,
477 const std::vector<uint8>& pkcs8_der,
478 const blink::WebCryptoAlgorithm& algorithm,
479 bool extractable,
480 blink::WebCryptoKeyUsageMask public_key_usage_mask,
481 blink::WebCryptoKeyUsageMask private_key_usage_mask,
482 blink::WebCryptoKey* public_key,
483 blink::WebCryptoKey* private_key) {
484 ASSERT_EQ(Status::Success(),
485 ImportKey(blink::WebCryptoKeyFormatSpki,
486 CryptoData(spki_der),
487 algorithm,
488 true,
489 public_key_usage_mask,
490 public_key));
491 EXPECT_FALSE(public_key->isNull());
492 EXPECT_TRUE(public_key->handle());
493 EXPECT_EQ(blink::WebCryptoKeyTypePublic, public_key->type());
494 EXPECT_EQ(algorithm.id(), public_key->algorithm().id());
495 EXPECT_TRUE(public_key->extractable());
496 EXPECT_EQ(public_key_usage_mask, public_key->usages());
498 ASSERT_EQ(Status::Success(),
499 ImportKey(blink::WebCryptoKeyFormatPkcs8,
500 CryptoData(pkcs8_der),
501 algorithm,
502 extractable,
503 private_key_usage_mask,
504 private_key));
505 EXPECT_FALSE(private_key->isNull());
506 EXPECT_TRUE(private_key->handle());
507 EXPECT_EQ(blink::WebCryptoKeyTypePrivate, private_key->type());
508 EXPECT_EQ(algorithm.id(), private_key->algorithm().id());
509 EXPECT_EQ(extractable, private_key->extractable());
510 EXPECT_EQ(private_key_usage_mask, private_key->usages());
513 Status AesGcmEncrypt(const blink::WebCryptoKey& key,
514 const std::vector<uint8>& iv,
515 const std::vector<uint8>& additional_data,
516 unsigned int tag_length_bits,
517 const std::vector<uint8>& plain_text,
518 std::vector<uint8>* cipher_text,
519 std::vector<uint8>* authentication_tag) {
520 EXPECT_TRUE(SupportsAesGcm());
521 blink::WebCryptoAlgorithm algorithm =
522 CreateAesGcmAlgorithm(iv, additional_data, tag_length_bits);
524 std::vector<uint8> output;
525 Status status = Encrypt(algorithm, key, CryptoData(plain_text), &output);
526 if (status.IsError())
527 return status;
529 if ((tag_length_bits % 8) != 0) {
530 EXPECT_TRUE(false) << "Encrypt should have failed.";
531 return Status::OperationError();
534 size_t tag_length_bytes = tag_length_bits / 8;
536 if (tag_length_bytes > output.size()) {
537 EXPECT_TRUE(false) << "tag length is larger than output";
538 return Status::OperationError();
541 // The encryption result is cipher text with authentication tag appended.
542 cipher_text->assign(output.begin(),
543 output.begin() + (output.size() - tag_length_bytes));
544 authentication_tag->assign(output.begin() + cipher_text->size(),
545 output.end());
547 return Status::Success();
550 Status AesGcmDecrypt(const blink::WebCryptoKey& key,
551 const std::vector<uint8>& iv,
552 const std::vector<uint8>& additional_data,
553 unsigned int tag_length_bits,
554 const std::vector<uint8>& cipher_text,
555 const std::vector<uint8>& authentication_tag,
556 std::vector<uint8>* plain_text) {
557 EXPECT_TRUE(SupportsAesGcm());
558 blink::WebCryptoAlgorithm algorithm =
559 CreateAesGcmAlgorithm(iv, additional_data, tag_length_bits);
561 // Join cipher text and authentication tag.
562 std::vector<uint8> cipher_text_with_tag;
563 cipher_text_with_tag.reserve(cipher_text.size() + authentication_tag.size());
564 cipher_text_with_tag.insert(
565 cipher_text_with_tag.end(), cipher_text.begin(), cipher_text.end());
566 cipher_text_with_tag.insert(cipher_text_with_tag.end(),
567 authentication_tag.begin(),
568 authentication_tag.end());
570 return Decrypt(algorithm, key, CryptoData(cipher_text_with_tag), plain_text);
573 Status ImportKeyJwk(const CryptoData& key_data,
574 const blink::WebCryptoAlgorithm& algorithm,
575 bool extractable,
576 blink::WebCryptoKeyUsageMask usage_mask,
577 blink::WebCryptoKey* key) {
578 return ImportKey(blink::WebCryptoKeyFormatJwk,
579 key_data,
580 algorithm,
581 extractable,
582 usage_mask,
583 key);
586 Status ImportKeyJwkFromDict(const base::DictionaryValue& dict,
587 const blink::WebCryptoAlgorithm& algorithm,
588 bool extractable,
589 blink::WebCryptoKeyUsageMask usage_mask,
590 blink::WebCryptoKey* key) {
591 return ImportKeyJwk(CryptoData(MakeJsonVector(dict)),
592 algorithm,
593 extractable,
594 usage_mask,
595 key);
598 // Parses a vector of JSON into a dictionary.
599 scoped_ptr<base::DictionaryValue> GetJwkDictionary(
600 const std::vector<uint8>& json) {
601 base::StringPiece json_string(
602 reinterpret_cast<const char*>(Uint8VectorStart(json)), json.size());
603 base::Value* value = base::JSONReader::Read(json_string);
604 EXPECT_TRUE(value);
605 base::DictionaryValue* dict_value = NULL;
606 value->GetAsDictionary(&dict_value);
607 return scoped_ptr<base::DictionaryValue>(dict_value);
610 // Verifies the input dictionary contains the expected values. Exact matches are
611 // required on the fields examined.
612 ::testing::AssertionResult VerifyJwk(
613 const scoped_ptr<base::DictionaryValue>& dict,
614 const std::string& kty_expected,
615 const std::string& alg_expected,
616 blink::WebCryptoKeyUsageMask use_mask_expected) {
617 // ---- kty
618 std::string value_string;
619 if (!dict->GetString("kty", &value_string))
620 return ::testing::AssertionFailure() << "Missing 'kty'";
621 if (value_string != kty_expected)
622 return ::testing::AssertionFailure() << "Expected 'kty' to be "
623 << kty_expected << "but found "
624 << value_string;
626 // ---- alg
627 if (!dict->GetString("alg", &value_string))
628 return ::testing::AssertionFailure() << "Missing 'alg'";
629 if (value_string != alg_expected)
630 return ::testing::AssertionFailure() << "Expected 'alg' to be "
631 << alg_expected << " but found "
632 << value_string;
634 // ---- ext
635 // always expect ext == true in this case
636 bool ext_value;
637 if (!dict->GetBoolean("ext", &ext_value))
638 return ::testing::AssertionFailure() << "Missing 'ext'";
639 if (!ext_value)
640 return ::testing::AssertionFailure()
641 << "Expected 'ext' to be true but found false";
643 // ---- key_ops
644 base::ListValue* key_ops;
645 if (!dict->GetList("key_ops", &key_ops))
646 return ::testing::AssertionFailure() << "Missing 'key_ops'";
647 blink::WebCryptoKeyUsageMask key_ops_mask = 0;
648 Status status = GetWebCryptoUsagesFromJwkKeyOps(key_ops, &key_ops_mask);
649 if (status.IsError())
650 return ::testing::AssertionFailure() << "Failure extracting 'key_ops'";
651 if (key_ops_mask != use_mask_expected)
652 return ::testing::AssertionFailure()
653 << "Expected 'key_ops' mask to be " << use_mask_expected
654 << " but found " << key_ops_mask << " (" << value_string << ")";
656 return ::testing::AssertionSuccess();
659 // Verifies that the JSON in the input vector contains the provided
660 // expected values. Exact matches are required on the fields examined.
661 ::testing::AssertionResult VerifySecretJwk(
662 const std::vector<uint8>& json,
663 const std::string& alg_expected,
664 const std::string& k_expected_hex,
665 blink::WebCryptoKeyUsageMask use_mask_expected) {
666 scoped_ptr<base::DictionaryValue> dict = GetJwkDictionary(json);
667 if (!dict.get() || dict->empty())
668 return ::testing::AssertionFailure() << "JSON parsing failed";
670 // ---- k
671 std::string value_string;
672 if (!dict->GetString("k", &value_string))
673 return ::testing::AssertionFailure() << "Missing 'k'";
674 std::string k_value;
675 if (!webcrypto::Base64DecodeUrlSafe(value_string, &k_value))
676 return ::testing::AssertionFailure() << "Base64DecodeUrlSafe(k) failed";
677 if (!LowerCaseEqualsASCII(base::HexEncode(k_value.data(), k_value.size()),
678 k_expected_hex.c_str())) {
679 return ::testing::AssertionFailure() << "Expected 'k' to be "
680 << k_expected_hex
681 << " but found something different";
684 return VerifyJwk(dict, "oct", alg_expected, use_mask_expected);
687 // Verifies that the JSON in the input vector contains the provided
688 // expected values. Exact matches are required on the fields examined.
689 ::testing::AssertionResult VerifyPublicJwk(
690 const std::vector<uint8>& json,
691 const std::string& alg_expected,
692 const std::string& n_expected_hex,
693 const std::string& e_expected_hex,
694 blink::WebCryptoKeyUsageMask use_mask_expected) {
695 scoped_ptr<base::DictionaryValue> dict = GetJwkDictionary(json);
696 if (!dict.get() || dict->empty())
697 return ::testing::AssertionFailure() << "JSON parsing failed";
699 // ---- n
700 std::string value_string;
701 if (!dict->GetString("n", &value_string))
702 return ::testing::AssertionFailure() << "Missing 'n'";
703 std::string n_value;
704 if (!webcrypto::Base64DecodeUrlSafe(value_string, &n_value))
705 return ::testing::AssertionFailure() << "Base64DecodeUrlSafe(n) failed";
706 if (base::HexEncode(n_value.data(), n_value.size()) != n_expected_hex) {
707 return ::testing::AssertionFailure() << "'n' does not match the expected "
708 "value";
710 // TODO(padolph): LowerCaseEqualsASCII() does not work for above!
712 // ---- e
713 if (!dict->GetString("e", &value_string))
714 return ::testing::AssertionFailure() << "Missing 'e'";
715 std::string e_value;
716 if (!webcrypto::Base64DecodeUrlSafe(value_string, &e_value))
717 return ::testing::AssertionFailure() << "Base64DecodeUrlSafe(e) failed";
718 if (!LowerCaseEqualsASCII(base::HexEncode(e_value.data(), e_value.size()),
719 e_expected_hex.c_str())) {
720 return ::testing::AssertionFailure() << "Expected 'e' to be "
721 << e_expected_hex
722 << " but found something different";
725 return VerifyJwk(dict, "RSA", alg_expected, use_mask_expected);
728 } // namespace
730 TEST_F(SharedCryptoTest, CheckAesGcm) {
731 if (!SupportsAesGcm()) {
732 LOG(WARNING) << "AES GCM not supported on this platform, so some tests "
733 "will be skipped. Consider upgrading local NSS libraries";
734 return;
738 // Tests several Status objects against their expected hard coded values, as
739 // well as ensuring that comparison of Status objects works.
740 // Comparison should take into account both the error details, as well as the
741 // error type.
742 TEST_F(SharedCryptoTest, Status) {
743 // Even though the error message is the same, these should not be considered
744 // the same by the tests because the error type is different.
745 EXPECT_NE(Status::DataError(), Status::OperationError());
746 EXPECT_NE(Status::Success(), Status::OperationError());
748 EXPECT_EQ(Status::Success(), Status::Success());
749 EXPECT_EQ(Status::ErrorJwkPropertyWrongType("kty", "string"),
750 Status::ErrorJwkPropertyWrongType("kty", "string"));
752 Status status = Status::Success();
754 EXPECT_FALSE(status.IsError());
755 EXPECT_EQ("", status.error_details());
757 status = Status::OperationError();
758 EXPECT_TRUE(status.IsError());
759 EXPECT_EQ("", status.error_details());
760 EXPECT_EQ(blink::WebCryptoErrorTypeOperation, status.error_type());
762 status = Status::DataError();
763 EXPECT_TRUE(status.IsError());
764 EXPECT_EQ("", status.error_details());
765 EXPECT_EQ(blink::WebCryptoErrorTypeData, status.error_type());
767 status = Status::ErrorUnsupported();
768 EXPECT_TRUE(status.IsError());
769 EXPECT_EQ("The requested operation is unsupported", status.error_details());
770 EXPECT_EQ(blink::WebCryptoErrorTypeNotSupported, status.error_type());
772 status = Status::ErrorJwkPropertyMissing("kty");
773 EXPECT_TRUE(status.IsError());
774 EXPECT_EQ("The required JWK property \"kty\" was missing",
775 status.error_details());
776 EXPECT_EQ(blink::WebCryptoErrorTypeData, status.error_type());
778 status = Status::ErrorJwkPropertyWrongType("kty", "string");
779 EXPECT_TRUE(status.IsError());
780 EXPECT_EQ("The JWK property \"kty\" must be a string",
781 status.error_details());
782 EXPECT_EQ(blink::WebCryptoErrorTypeData, status.error_type());
784 status = Status::ErrorJwkBase64Decode("n");
785 EXPECT_TRUE(status.IsError());
786 EXPECT_EQ("The JWK property \"n\" could not be base64 decoded",
787 status.error_details());
788 EXPECT_EQ(blink::WebCryptoErrorTypeData, status.error_type());
791 TEST_F(SharedCryptoTest, DigestSampleSets) {
792 scoped_ptr<base::ListValue> tests;
793 ASSERT_TRUE(ReadJsonTestFileToList("digest.json", &tests));
795 for (size_t test_index = 0; test_index < tests->GetSize(); ++test_index) {
796 SCOPED_TRACE(test_index);
797 base::DictionaryValue* test;
798 ASSERT_TRUE(tests->GetDictionary(test_index, &test));
800 blink::WebCryptoAlgorithm test_algorithm =
801 GetDigestAlgorithm(test, "algorithm");
802 std::vector<uint8> test_input = GetBytesFromHexString(test, "input");
803 std::vector<uint8> test_output = GetBytesFromHexString(test, "output");
805 std::vector<uint8> output;
806 ASSERT_EQ(Status::Success(),
807 Digest(test_algorithm, CryptoData(test_input), &output));
808 EXPECT_BYTES_EQ(test_output, output);
812 TEST_F(SharedCryptoTest, DigestSampleSetsInChunks) {
813 scoped_ptr<base::ListValue> tests;
814 ASSERT_TRUE(ReadJsonTestFileToList("digest.json", &tests));
816 for (size_t test_index = 0; test_index < tests->GetSize(); ++test_index) {
817 SCOPED_TRACE(test_index);
818 base::DictionaryValue* test;
819 ASSERT_TRUE(tests->GetDictionary(test_index, &test));
821 blink::WebCryptoAlgorithm test_algorithm =
822 GetDigestAlgorithm(test, "algorithm");
823 std::vector<uint8> test_input = GetBytesFromHexString(test, "input");
824 std::vector<uint8> test_output = GetBytesFromHexString(test, "output");
826 // Test the chunk version of the digest functions. Test with 129 byte chunks
827 // because the SHA-512 chunk size is 128 bytes.
828 unsigned char* output;
829 unsigned int output_length;
830 static const size_t kChunkSizeBytes = 129;
831 size_t length = test_input.size();
832 scoped_ptr<blink::WebCryptoDigestor> digestor(
833 CreateDigestor(test_algorithm.id()));
834 std::vector<uint8>::iterator begin = test_input.begin();
835 size_t chunk_index = 0;
836 while (begin != test_input.end()) {
837 size_t chunk_length = std::min(kChunkSizeBytes, length - chunk_index);
838 std::vector<uint8> chunk(begin, begin + chunk_length);
839 ASSERT_TRUE(chunk.size() > 0);
840 EXPECT_TRUE(digestor->consume(&chunk.front(), chunk.size()));
841 chunk_index = chunk_index + chunk_length;
842 begin = begin + chunk_length;
844 EXPECT_TRUE(digestor->finish(output, output_length));
845 EXPECT_BYTES_EQ(test_output, CryptoData(output, output_length));
849 TEST_F(SharedCryptoTest, HMACSampleSets) {
850 scoped_ptr<base::ListValue> tests;
851 ASSERT_TRUE(ReadJsonTestFileToList("hmac.json", &tests));
852 // TODO(padolph): Missing known answer tests for HMAC SHA384, and SHA512.
853 for (size_t test_index = 0; test_index < tests->GetSize(); ++test_index) {
854 SCOPED_TRACE(test_index);
855 base::DictionaryValue* test;
856 ASSERT_TRUE(tests->GetDictionary(test_index, &test));
858 blink::WebCryptoAlgorithm test_hash = GetDigestAlgorithm(test, "hash");
859 const std::vector<uint8> test_key = GetBytesFromHexString(test, "key");
860 const std::vector<uint8> test_message =
861 GetBytesFromHexString(test, "message");
862 const std::vector<uint8> test_mac = GetBytesFromHexString(test, "mac");
864 blink::WebCryptoAlgorithm algorithm =
865 CreateAlgorithm(blink::WebCryptoAlgorithmIdHmac);
867 blink::WebCryptoAlgorithm import_algorithm =
868 CreateHmacImportAlgorithm(test_hash.id());
870 blink::WebCryptoKey key = ImportSecretKeyFromRaw(
871 test_key,
872 import_algorithm,
873 blink::WebCryptoKeyUsageSign | blink::WebCryptoKeyUsageVerify);
875 EXPECT_EQ(test_hash.id(), key.algorithm().hmacParams()->hash().id());
876 EXPECT_EQ(test_key.size() * 8, key.algorithm().hmacParams()->lengthBits());
878 // Verify exported raw key is identical to the imported data
879 std::vector<uint8> raw_key;
880 EXPECT_EQ(Status::Success(),
881 ExportKey(blink::WebCryptoKeyFormatRaw, key, &raw_key));
882 EXPECT_BYTES_EQ(test_key, raw_key);
884 std::vector<uint8> output;
886 ASSERT_EQ(Status::Success(),
887 Sign(algorithm, key, CryptoData(test_message), &output));
889 EXPECT_BYTES_EQ(test_mac, output);
891 bool signature_match = false;
892 EXPECT_EQ(Status::Success(),
893 VerifySignature(algorithm,
894 key,
895 CryptoData(output),
896 CryptoData(test_message),
897 &signature_match));
898 EXPECT_TRUE(signature_match);
900 // Ensure truncated signature does not verify by passing one less byte.
901 EXPECT_EQ(
902 Status::Success(),
903 VerifySignature(algorithm,
904 key,
905 CryptoData(Uint8VectorStart(output), output.size() - 1),
906 CryptoData(test_message),
907 &signature_match));
908 EXPECT_FALSE(signature_match);
910 // Ensure truncated signature does not verify by passing no bytes.
911 EXPECT_EQ(Status::Success(),
912 VerifySignature(algorithm,
913 key,
914 CryptoData(),
915 CryptoData(test_message),
916 &signature_match));
917 EXPECT_FALSE(signature_match);
919 // Ensure extra long signature does not cause issues and fails.
920 const unsigned char kLongSignature[1024] = {0};
921 EXPECT_EQ(
922 Status::Success(),
923 VerifySignature(algorithm,
924 key,
925 CryptoData(kLongSignature, sizeof(kLongSignature)),
926 CryptoData(test_message),
927 &signature_match));
928 EXPECT_FALSE(signature_match);
932 TEST_F(SharedCryptoTest, AesCbcFailures) {
933 const std::string key_hex = "2b7e151628aed2a6abf7158809cf4f3c";
934 blink::WebCryptoKey key = ImportSecretKeyFromRaw(
935 HexStringToBytes(key_hex),
936 CreateAlgorithm(blink::WebCryptoAlgorithmIdAesCbc),
937 blink::WebCryptoKeyUsageEncrypt | blink::WebCryptoKeyUsageDecrypt);
939 // Verify exported raw key is identical to the imported data
940 std::vector<uint8> raw_key;
941 EXPECT_EQ(Status::Success(),
942 ExportKey(blink::WebCryptoKeyFormatRaw, key, &raw_key));
943 EXPECT_BYTES_EQ_HEX(key_hex, raw_key);
945 std::vector<uint8> output;
947 // Use an invalid |iv| (fewer than 16 bytes)
949 std::vector<uint8> input(32);
950 std::vector<uint8> iv;
951 EXPECT_EQ(Status::ErrorIncorrectSizeAesCbcIv(),
952 Encrypt(webcrypto::CreateAesCbcAlgorithm(iv),
953 key,
954 CryptoData(input),
955 &output));
956 EXPECT_EQ(Status::ErrorIncorrectSizeAesCbcIv(),
957 Decrypt(webcrypto::CreateAesCbcAlgorithm(iv),
958 key,
959 CryptoData(input),
960 &output));
963 // Use an invalid |iv| (more than 16 bytes)
965 std::vector<uint8> input(32);
966 std::vector<uint8> iv(17);
967 EXPECT_EQ(Status::ErrorIncorrectSizeAesCbcIv(),
968 Encrypt(webcrypto::CreateAesCbcAlgorithm(iv),
969 key,
970 CryptoData(input),
971 &output));
972 EXPECT_EQ(Status::ErrorIncorrectSizeAesCbcIv(),
973 Decrypt(webcrypto::CreateAesCbcAlgorithm(iv),
974 key,
975 CryptoData(input),
976 &output));
979 // Give an input that is too large (would cause integer overflow when
980 // narrowing to an int).
982 std::vector<uint8> iv(16);
984 // Pretend the input is large. Don't pass data pointer as NULL in case that
985 // is special cased; the implementation shouldn't actually dereference the
986 // data.
987 CryptoData input(&iv[0], INT_MAX - 3);
989 EXPECT_EQ(Status::ErrorDataTooLarge(),
990 Encrypt(CreateAesCbcAlgorithm(iv), key, input, &output));
991 EXPECT_EQ(Status::ErrorDataTooLarge(),
992 Decrypt(CreateAesCbcAlgorithm(iv), key, input, &output));
995 // Fail importing the key (too few bytes specified)
997 std::vector<uint8> key_raw(1);
998 std::vector<uint8> iv(16);
1000 blink::WebCryptoKey key = blink::WebCryptoKey::createNull();
1001 EXPECT_EQ(Status::ErrorImportAesKeyLength(),
1002 ImportKey(blink::WebCryptoKeyFormatRaw,
1003 CryptoData(key_raw),
1004 CreateAesCbcAlgorithm(iv),
1005 true,
1006 blink::WebCryptoKeyUsageEncrypt,
1007 &key));
1010 // Fail exporting the key in SPKI and PKCS#8 formats (not allowed for secret
1011 // keys).
1012 EXPECT_EQ(Status::ErrorUnexpectedKeyType(),
1013 ExportKey(blink::WebCryptoKeyFormatSpki, key, &output));
1014 EXPECT_EQ(Status::ErrorUnexpectedKeyType(),
1015 ExportKey(blink::WebCryptoKeyFormatPkcs8, key, &output));
1018 TEST_F(SharedCryptoTest, MAYBE(AesCbcSampleSets)) {
1019 scoped_ptr<base::ListValue> tests;
1020 ASSERT_TRUE(ReadJsonTestFileToList("aes_cbc.json", &tests));
1022 for (size_t test_index = 0; test_index < tests->GetSize(); ++test_index) {
1023 SCOPED_TRACE(test_index);
1024 base::DictionaryValue* test;
1025 ASSERT_TRUE(tests->GetDictionary(test_index, &test));
1027 std::vector<uint8> test_key = GetBytesFromHexString(test, "key");
1028 std::vector<uint8> test_iv = GetBytesFromHexString(test, "iv");
1029 std::vector<uint8> test_plain_text =
1030 GetBytesFromHexString(test, "plain_text");
1031 std::vector<uint8> test_cipher_text =
1032 GetBytesFromHexString(test, "cipher_text");
1034 blink::WebCryptoKey key = ImportSecretKeyFromRaw(
1035 test_key,
1036 CreateAlgorithm(blink::WebCryptoAlgorithmIdAesCbc),
1037 blink::WebCryptoKeyUsageEncrypt | blink::WebCryptoKeyUsageDecrypt);
1039 EXPECT_EQ(test_key.size() * 8, key.algorithm().aesParams()->lengthBits());
1041 // Verify exported raw key is identical to the imported data
1042 std::vector<uint8> raw_key;
1043 EXPECT_EQ(Status::Success(),
1044 ExportKey(blink::WebCryptoKeyFormatRaw, key, &raw_key));
1045 EXPECT_BYTES_EQ(test_key, raw_key);
1047 std::vector<uint8> output;
1049 // Test encryption.
1050 EXPECT_EQ(Status::Success(),
1051 Encrypt(webcrypto::CreateAesCbcAlgorithm(test_iv),
1052 key,
1053 CryptoData(test_plain_text),
1054 &output));
1055 EXPECT_BYTES_EQ(test_cipher_text, output);
1057 // Test decryption.
1058 EXPECT_EQ(Status::Success(),
1059 Decrypt(webcrypto::CreateAesCbcAlgorithm(test_iv),
1060 key,
1061 CryptoData(test_cipher_text),
1062 &output));
1063 EXPECT_BYTES_EQ(test_plain_text, output);
1065 const unsigned int kAesCbcBlockSize = 16;
1067 // Decrypt with a padding error by stripping the last block. This also ends
1068 // up testing decryption over empty cipher text.
1069 if (test_cipher_text.size() >= kAesCbcBlockSize) {
1070 EXPECT_EQ(Status::OperationError(),
1071 Decrypt(CreateAesCbcAlgorithm(test_iv),
1072 key,
1073 CryptoData(&test_cipher_text[0],
1074 test_cipher_text.size() - kAesCbcBlockSize),
1075 &output));
1078 // Decrypt cipher text which is not a multiple of block size by stripping
1079 // a few bytes off the cipher text.
1080 if (test_cipher_text.size() > 3) {
1081 EXPECT_EQ(
1082 Status::OperationError(),
1083 Decrypt(CreateAesCbcAlgorithm(test_iv),
1084 key,
1085 CryptoData(&test_cipher_text[0], test_cipher_text.size() - 3),
1086 &output));
1091 TEST_F(SharedCryptoTest, GenerateKeyAes) {
1092 // Check key generation for each of AES-CBC, AES-GCM, and AES-KW, and for each
1093 // allowed key length.
1094 std::vector<blink::WebCryptoAlgorithm> algorithm;
1095 const unsigned short kKeyLength[] = {128, 256};
1096 for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kKeyLength); ++i) {
1097 algorithm.push_back(CreateAesCbcKeyGenAlgorithm(kKeyLength[i]));
1098 algorithm.push_back(CreateAesKwKeyGenAlgorithm(kKeyLength[i]));
1099 if (SupportsAesGcm())
1100 algorithm.push_back(CreateAesGcmKeyGenAlgorithm(kKeyLength[i]));
1102 blink::WebCryptoKey key = blink::WebCryptoKey::createNull();
1103 std::vector<std::vector<uint8> > keys;
1104 std::vector<uint8> key_bytes;
1105 for (size_t i = 0; i < algorithm.size(); ++i) {
1106 SCOPED_TRACE(i);
1107 // Generate a small sample of keys.
1108 keys.clear();
1109 for (int j = 0; j < 16; ++j) {
1110 ASSERT_EQ(Status::Success(),
1111 GenerateSecretKey(algorithm[i], true, 0, &key));
1112 EXPECT_TRUE(key.handle());
1113 EXPECT_EQ(blink::WebCryptoKeyTypeSecret, key.type());
1114 ASSERT_EQ(Status::Success(),
1115 ExportKey(blink::WebCryptoKeyFormatRaw, key, &key_bytes));
1116 EXPECT_EQ(key_bytes.size() * 8,
1117 key.algorithm().aesParams()->lengthBits());
1118 keys.push_back(key_bytes);
1120 // Ensure all entries in the key sample set are unique. This is a simplistic
1121 // estimate of whether the generated keys appear random.
1122 EXPECT_FALSE(CopiesExist(keys));
1126 TEST_F(SharedCryptoTest, GenerateKeyAesBadLength) {
1127 const unsigned short kKeyLen[] = {0, 127, 257};
1128 blink::WebCryptoKey key = blink::WebCryptoKey::createNull();
1129 for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kKeyLen); ++i) {
1130 SCOPED_TRACE(i);
1131 EXPECT_EQ(Status::ErrorGenerateKeyLength(),
1132 GenerateSecretKey(
1133 CreateAesCbcKeyGenAlgorithm(kKeyLen[i]), true, 0, &key));
1134 EXPECT_EQ(Status::ErrorGenerateKeyLength(),
1135 GenerateSecretKey(
1136 CreateAesKwKeyGenAlgorithm(kKeyLen[i]), true, 0, &key));
1137 if (SupportsAesGcm()) {
1138 EXPECT_EQ(Status::ErrorGenerateKeyLength(),
1139 GenerateSecretKey(
1140 CreateAesGcmKeyGenAlgorithm(kKeyLen[i]), true, 0, &key));
1145 TEST_F(SharedCryptoTest, MAYBE(GenerateKeyHmac)) {
1146 // Generate a small sample of HMAC keys.
1147 std::vector<std::vector<uint8> > keys;
1148 for (int i = 0; i < 16; ++i) {
1149 std::vector<uint8> key_bytes;
1150 blink::WebCryptoKey key = blink::WebCryptoKey::createNull();
1151 blink::WebCryptoAlgorithm algorithm =
1152 CreateHmacKeyGenAlgorithm(blink::WebCryptoAlgorithmIdSha1, 512);
1153 ASSERT_EQ(Status::Success(), GenerateSecretKey(algorithm, true, 0, &key));
1154 EXPECT_FALSE(key.isNull());
1155 EXPECT_TRUE(key.handle());
1156 EXPECT_EQ(blink::WebCryptoKeyTypeSecret, key.type());
1157 EXPECT_EQ(blink::WebCryptoAlgorithmIdHmac, key.algorithm().id());
1158 EXPECT_EQ(blink::WebCryptoAlgorithmIdSha1,
1159 key.algorithm().hmacParams()->hash().id());
1160 EXPECT_EQ(512u, key.algorithm().hmacParams()->lengthBits());
1162 std::vector<uint8> raw_key;
1163 ASSERT_EQ(Status::Success(),
1164 ExportKey(blink::WebCryptoKeyFormatRaw, key, &raw_key));
1165 EXPECT_EQ(64U, raw_key.size());
1166 keys.push_back(raw_key);
1168 // Ensure all entries in the key sample set are unique. This is a simplistic
1169 // estimate of whether the generated keys appear random.
1170 EXPECT_FALSE(CopiesExist(keys));
1173 // If the key length is not provided, then the block size is used.
1174 TEST_F(SharedCryptoTest, MAYBE(GenerateKeyHmacNoLength)) {
1175 blink::WebCryptoKey key = blink::WebCryptoKey::createNull();
1176 blink::WebCryptoAlgorithm algorithm =
1177 CreateHmacKeyGenAlgorithm(blink::WebCryptoAlgorithmIdSha1, 0);
1178 ASSERT_EQ(Status::Success(), GenerateSecretKey(algorithm, true, 0, &key));
1179 EXPECT_TRUE(key.handle());
1180 EXPECT_EQ(blink::WebCryptoKeyTypeSecret, key.type());
1181 EXPECT_EQ(blink::WebCryptoAlgorithmIdHmac, key.algorithm().id());
1182 EXPECT_EQ(blink::WebCryptoAlgorithmIdSha1,
1183 key.algorithm().hmacParams()->hash().id());
1184 EXPECT_EQ(512u, key.algorithm().hmacParams()->lengthBits());
1185 std::vector<uint8> raw_key;
1186 ASSERT_EQ(Status::Success(),
1187 ExportKey(blink::WebCryptoKeyFormatRaw, key, &raw_key));
1188 EXPECT_EQ(64U, raw_key.size());
1190 // The block size for HMAC SHA-512 is larger.
1191 algorithm = CreateHmacKeyGenAlgorithm(blink::WebCryptoAlgorithmIdSha512, 0);
1192 ASSERT_EQ(Status::Success(), GenerateSecretKey(algorithm, true, 0, &key));
1193 EXPECT_EQ(blink::WebCryptoAlgorithmIdHmac, key.algorithm().id());
1194 EXPECT_EQ(blink::WebCryptoAlgorithmIdSha512,
1195 key.algorithm().hmacParams()->hash().id());
1196 EXPECT_EQ(1024u, key.algorithm().hmacParams()->lengthBits());
1197 ASSERT_EQ(Status::Success(),
1198 ExportKey(blink::WebCryptoKeyFormatRaw, key, &raw_key));
1199 EXPECT_EQ(128U, raw_key.size());
1202 TEST_F(SharedCryptoTest, ImportJwkKeyUsage) {
1203 blink::WebCryptoKey key = blink::WebCryptoKey::createNull();
1204 base::DictionaryValue dict;
1205 dict.SetString("kty", "oct");
1206 dict.SetBoolean("ext", false);
1207 dict.SetString("k", "GADWrMRHwQfoNaXU5fZvTg==");
1208 const blink::WebCryptoAlgorithm aes_cbc_algorithm =
1209 webcrypto::CreateAlgorithm(blink::WebCryptoAlgorithmIdAesCbc);
1210 const blink::WebCryptoAlgorithm hmac_algorithm =
1211 webcrypto::CreateHmacImportAlgorithm(blink::WebCryptoAlgorithmIdSha256);
1212 const blink::WebCryptoAlgorithm aes_kw_algorithm =
1213 webcrypto::CreateAlgorithm(blink::WebCryptoAlgorithmIdAesKw);
1215 // Test null usage.
1216 base::ListValue* key_ops = new base::ListValue;
1217 // Note: the following call makes dict assume ownership of key_ops.
1218 dict.Set("key_ops", key_ops);
1219 EXPECT_EQ(Status::Success(),
1220 ImportKeyJwkFromDict(dict, aes_cbc_algorithm, false, 0, &key));
1221 EXPECT_EQ(0, key.usages());
1223 // Test each key_ops value translates to the correct Web Crypto value.
1224 struct TestCase {
1225 const char* jwk_key_op;
1226 const char* jwk_alg;
1227 const blink::WebCryptoAlgorithm algorithm;
1228 const blink::WebCryptoKeyUsage usage;
1230 // TODO(padolph): Add 'deriveBits' key_ops value once it is supported.
1231 const TestCase test_case[] = {
1232 {"encrypt", "A128CBC", aes_cbc_algorithm,
1233 blink::WebCryptoKeyUsageEncrypt},
1234 {"decrypt", "A128CBC", aes_cbc_algorithm,
1235 blink::WebCryptoKeyUsageDecrypt},
1236 {"sign", "HS256", hmac_algorithm, blink::WebCryptoKeyUsageSign},
1237 {"verify", "HS256", hmac_algorithm, blink::WebCryptoKeyUsageVerify},
1238 {"wrapKey", "A128KW", aes_kw_algorithm, blink::WebCryptoKeyUsageWrapKey},
1239 {"unwrapKey", "A128KW", aes_kw_algorithm,
1240 blink::WebCryptoKeyUsageUnwrapKey}};
1241 for (size_t test_index = 0; test_index < ARRAYSIZE_UNSAFE(test_case);
1242 ++test_index) {
1243 SCOPED_TRACE(test_index);
1244 dict.SetString("alg", test_case[test_index].jwk_alg);
1245 key_ops->Clear();
1246 key_ops->AppendString(test_case[test_index].jwk_key_op);
1247 EXPECT_EQ(Status::Success(),
1248 ImportKeyJwkFromDict(dict,
1249 test_case[test_index].algorithm,
1250 false,
1251 test_case[test_index].usage,
1252 &key));
1253 EXPECT_EQ(test_case[test_index].usage, key.usages());
1256 // Test discrete multiple usages.
1257 dict.SetString("alg", "A128CBC");
1258 key_ops->Clear();
1259 key_ops->AppendString("encrypt");
1260 key_ops->AppendString("decrypt");
1261 EXPECT_EQ(Status::Success(),
1262 ImportKeyJwkFromDict(dict,
1263 aes_cbc_algorithm,
1264 false,
1265 blink::WebCryptoKeyUsageDecrypt |
1266 blink::WebCryptoKeyUsageEncrypt,
1267 &key));
1268 EXPECT_EQ(blink::WebCryptoKeyUsageDecrypt | blink::WebCryptoKeyUsageEncrypt,
1269 key.usages());
1271 // Test constrained key usage (input usage is a subset of JWK usage).
1272 key_ops->Clear();
1273 key_ops->AppendString("encrypt");
1274 key_ops->AppendString("decrypt");
1275 EXPECT_EQ(Status::Success(),
1276 ImportKeyJwkFromDict(dict,
1277 aes_cbc_algorithm,
1278 false,
1279 blink::WebCryptoKeyUsageDecrypt,
1280 &key));
1281 EXPECT_EQ(blink::WebCryptoKeyUsageDecrypt, key.usages());
1283 // Test failure if input usage is NOT a strict subset of the JWK usage.
1284 key_ops->Clear();
1285 key_ops->AppendString("encrypt");
1286 EXPECT_EQ(Status::ErrorJwkKeyopsInconsistent(),
1287 ImportKeyJwkFromDict(dict,
1288 aes_cbc_algorithm,
1289 false,
1290 blink::WebCryptoKeyUsageEncrypt |
1291 blink::WebCryptoKeyUsageDecrypt,
1292 &key));
1294 // Test 'use' inconsistent with 'key_ops'.
1295 dict.SetString("alg", "HS256");
1296 dict.SetString("use", "sig");
1297 key_ops->AppendString("sign");
1298 key_ops->AppendString("verify");
1299 key_ops->AppendString("encrypt");
1300 EXPECT_EQ(Status::ErrorJwkUseAndKeyopsInconsistent(),
1301 ImportKeyJwkFromDict(
1302 dict,
1303 hmac_algorithm,
1304 false,
1305 blink::WebCryptoKeyUsageSign | blink::WebCryptoKeyUsageVerify,
1306 &key));
1308 // Test JWK composite 'sig' use
1309 dict.Remove("key_ops", NULL);
1310 dict.SetString("use", "sig");
1311 EXPECT_EQ(Status::Success(),
1312 ImportKeyJwkFromDict(
1313 dict,
1314 hmac_algorithm,
1315 false,
1316 blink::WebCryptoKeyUsageSign | blink::WebCryptoKeyUsageVerify,
1317 &key));
1318 EXPECT_EQ(blink::WebCryptoKeyUsageSign | blink::WebCryptoKeyUsageVerify,
1319 key.usages());
1321 // Test JWK composite use 'enc' usage
1322 dict.SetString("alg", "A128CBC");
1323 dict.SetString("use", "enc");
1324 EXPECT_EQ(Status::Success(),
1325 ImportKeyJwkFromDict(dict,
1326 aes_cbc_algorithm,
1327 false,
1328 blink::WebCryptoKeyUsageDecrypt |
1329 blink::WebCryptoKeyUsageEncrypt |
1330 blink::WebCryptoKeyUsageWrapKey |
1331 blink::WebCryptoKeyUsageUnwrapKey,
1332 &key));
1333 EXPECT_EQ(blink::WebCryptoKeyUsageDecrypt | blink::WebCryptoKeyUsageEncrypt |
1334 blink::WebCryptoKeyUsageWrapKey |
1335 blink::WebCryptoKeyUsageUnwrapKey,
1336 key.usages());
1339 TEST_F(SharedCryptoTest, ImportJwkFailures) {
1340 blink::WebCryptoKey key = blink::WebCryptoKey::createNull();
1341 blink::WebCryptoAlgorithm algorithm =
1342 CreateAlgorithm(blink::WebCryptoAlgorithmIdAesCbc);
1343 blink::WebCryptoKeyUsageMask usage_mask = blink::WebCryptoKeyUsageEncrypt;
1345 // Baseline pass: each test below breaks a single item, so we start with a
1346 // passing case to make sure each failure is caused by the isolated break.
1347 // Each breaking subtest below resets the dictionary to this passing case when
1348 // complete.
1349 base::DictionaryValue dict;
1350 RestoreJwkOctDictionary(&dict);
1351 EXPECT_EQ(Status::Success(),
1352 ImportKeyJwkFromDict(dict, algorithm, false, usage_mask, &key));
1354 // Fail on empty JSON.
1355 EXPECT_EQ(
1356 Status::ErrorImportEmptyKeyData(),
1357 ImportKeyJwk(
1358 CryptoData(MakeJsonVector("")), algorithm, false, usage_mask, &key));
1360 // Fail on invalid JSON.
1361 const std::vector<uint8> bad_json_vec = MakeJsonVector(
1363 "\"kty\" : \"oct\","
1364 "\"alg\" : \"HS256\","
1365 "\"use\" : ");
1366 EXPECT_EQ(Status::ErrorJwkNotDictionary(),
1367 ImportKeyJwk(
1368 CryptoData(bad_json_vec), algorithm, false, usage_mask, &key));
1370 // Fail on JWK alg present but unrecognized.
1371 dict.SetString("alg", "A127CBC");
1372 EXPECT_EQ(Status::ErrorJwkUnrecognizedAlgorithm(),
1373 ImportKeyJwkFromDict(dict, algorithm, false, usage_mask, &key));
1374 RestoreJwkOctDictionary(&dict);
1376 // Fail on invalid kty.
1377 dict.SetString("kty", "foo");
1378 EXPECT_EQ(Status::ErrorJwkUnrecognizedKty(),
1379 ImportKeyJwkFromDict(dict, algorithm, false, usage_mask, &key));
1380 RestoreJwkOctDictionary(&dict);
1382 // Fail on missing kty.
1383 dict.Remove("kty", NULL);
1384 EXPECT_EQ(Status::ErrorJwkPropertyMissing("kty"),
1385 ImportKeyJwkFromDict(dict, algorithm, false, usage_mask, &key));
1386 RestoreJwkOctDictionary(&dict);
1388 // Fail on kty wrong type.
1389 dict.SetDouble("kty", 0.1);
1390 EXPECT_EQ(Status::ErrorJwkPropertyWrongType("kty", "string"),
1391 ImportKeyJwkFromDict(dict, algorithm, false, usage_mask, &key));
1392 RestoreJwkOctDictionary(&dict);
1394 // Fail on invalid use.
1395 dict.SetString("use", "foo");
1396 EXPECT_EQ(Status::ErrorJwkUnrecognizedUse(),
1397 ImportKeyJwkFromDict(dict, algorithm, false, usage_mask, &key));
1398 RestoreJwkOctDictionary(&dict);
1400 // Fail on invalid use (wrong type).
1401 dict.SetBoolean("use", true);
1402 EXPECT_EQ(Status::ErrorJwkPropertyWrongType("use", "string"),
1403 ImportKeyJwkFromDict(dict, algorithm, false, usage_mask, &key));
1404 RestoreJwkOctDictionary(&dict);
1406 // Fail on invalid extractable (wrong type).
1407 dict.SetInteger("ext", 0);
1408 EXPECT_EQ(Status::ErrorJwkPropertyWrongType("ext", "boolean"),
1409 ImportKeyJwkFromDict(dict, algorithm, false, usage_mask, &key));
1410 RestoreJwkOctDictionary(&dict);
1412 // Fail on invalid key_ops (wrong type).
1413 dict.SetBoolean("key_ops", true);
1414 EXPECT_EQ(Status::ErrorJwkPropertyWrongType("key_ops", "list"),
1415 ImportKeyJwkFromDict(dict, algorithm, false, usage_mask, &key));
1416 RestoreJwkOctDictionary(&dict);
1418 // Fail on inconsistent key_ops - asking for "encrypt" however JWK contains
1419 // only "foo".
1420 base::ListValue* key_ops = new base::ListValue;
1421 // Note: the following call makes dict assume ownership of key_ops.
1422 dict.Set("key_ops", key_ops);
1423 key_ops->AppendString("foo");
1424 EXPECT_EQ(Status::ErrorJwkKeyopsInconsistent(),
1425 ImportKeyJwkFromDict(dict, algorithm, false, usage_mask, &key));
1426 RestoreJwkOctDictionary(&dict);
1429 // Import a JWK with unrecognized values for "key_ops".
1430 TEST_F(SharedCryptoTest, ImportJwkUnrecognizedKeyOps) {
1431 blink::WebCryptoKey key = blink::WebCryptoKey::createNull();
1432 blink::WebCryptoAlgorithm algorithm =
1433 CreateAlgorithm(blink::WebCryptoAlgorithmIdAesCbc);
1434 blink::WebCryptoKeyUsageMask usage_mask = blink::WebCryptoKeyUsageEncrypt;
1436 base::DictionaryValue dict;
1437 RestoreJwkOctDictionary(&dict);
1439 base::ListValue* key_ops = new base::ListValue;
1440 dict.Set("key_ops", key_ops);
1441 key_ops->AppendString("foo");
1442 key_ops->AppendString("bar");
1443 key_ops->AppendString("baz");
1444 key_ops->AppendString("encrypt");
1445 EXPECT_EQ(Status::Success(),
1446 ImportKeyJwkFromDict(dict, algorithm, false, usage_mask, &key));
1449 // Import a JWK with a value in key_ops array that is not a string.
1450 TEST_F(SharedCryptoTest, ImportJwkNonStringKeyOp) {
1451 blink::WebCryptoKey key = blink::WebCryptoKey::createNull();
1452 blink::WebCryptoAlgorithm algorithm =
1453 CreateAlgorithm(blink::WebCryptoAlgorithmIdAesCbc);
1454 blink::WebCryptoKeyUsageMask usage_mask = blink::WebCryptoKeyUsageEncrypt;
1456 base::DictionaryValue dict;
1457 RestoreJwkOctDictionary(&dict);
1459 base::ListValue* key_ops = new base::ListValue;
1460 dict.Set("key_ops", key_ops);
1461 key_ops->AppendString("encrypt");
1462 key_ops->AppendInteger(3);
1463 EXPECT_EQ(Status::ErrorJwkPropertyWrongType("key_ops[1]", "string"),
1464 ImportKeyJwkFromDict(dict, algorithm, false, usage_mask, &key));
1467 TEST_F(SharedCryptoTest, ImportJwkOctFailures) {
1468 base::DictionaryValue dict;
1469 RestoreJwkOctDictionary(&dict);
1470 blink::WebCryptoAlgorithm algorithm =
1471 CreateAlgorithm(blink::WebCryptoAlgorithmIdAesCbc);
1472 blink::WebCryptoKeyUsageMask usage_mask = blink::WebCryptoKeyUsageEncrypt;
1473 blink::WebCryptoKey key = blink::WebCryptoKey::createNull();
1475 // Baseline pass.
1476 EXPECT_EQ(Status::Success(),
1477 ImportKeyJwkFromDict(dict, algorithm, false, usage_mask, &key));
1478 EXPECT_EQ(algorithm.id(), key.algorithm().id());
1479 EXPECT_FALSE(key.extractable());
1480 EXPECT_EQ(blink::WebCryptoKeyUsageEncrypt, key.usages());
1481 EXPECT_EQ(blink::WebCryptoKeyTypeSecret, key.type());
1483 // The following are specific failure cases for when kty = "oct".
1485 // Fail on missing k.
1486 dict.Remove("k", NULL);
1487 EXPECT_EQ(Status::ErrorJwkPropertyMissing("k"),
1488 ImportKeyJwkFromDict(dict, algorithm, false, usage_mask, &key));
1489 RestoreJwkOctDictionary(&dict);
1491 // Fail on bad b64 encoding for k.
1492 dict.SetString("k", "Qk3f0DsytU8lfza2au #$% Htaw2xpop9GYyTuH0p5GghxTI=");
1493 EXPECT_EQ(Status::ErrorJwkBase64Decode("k"),
1494 ImportKeyJwkFromDict(dict, algorithm, false, usage_mask, &key));
1495 RestoreJwkOctDictionary(&dict);
1497 // Fail on empty k.
1498 dict.SetString("k", "");
1499 EXPECT_EQ(Status::ErrorJwkIncorrectKeyLength(),
1500 ImportKeyJwkFromDict(dict, algorithm, false, usage_mask, &key));
1501 RestoreJwkOctDictionary(&dict);
1503 // Fail on k actual length (120 bits) inconsistent with the embedded JWK alg
1504 // value (128) for an AES key.
1505 dict.SetString("k", "AVj42h0Y5aqGtE3yluKL");
1506 EXPECT_EQ(Status::ErrorJwkIncorrectKeyLength(),
1507 ImportKeyJwkFromDict(dict, algorithm, false, usage_mask, &key));
1508 RestoreJwkOctDictionary(&dict);
1510 // Fail on k actual length (192 bits) inconsistent with the embedded JWK alg
1511 // value (128) for an AES key.
1512 dict.SetString("k", "dGhpcyAgaXMgIDI0ICBieXRlcyBsb25n");
1513 EXPECT_EQ(Status::ErrorJwkIncorrectKeyLength(),
1514 ImportKeyJwkFromDict(dict, algorithm, false, usage_mask, &key));
1515 RestoreJwkOctDictionary(&dict);
1518 TEST_F(SharedCryptoTest, MAYBE(ImportExportJwkRsaPublicKey)) {
1519 if (!SupportsRsaKeyImport())
1520 return;
1522 const bool supports_rsa_oaep = SupportsRsaOaep();
1523 if (!supports_rsa_oaep) {
1524 LOG(WARNING) << "RSA-OAEP not supported on this platform. Skipping some"
1525 << "tests.";
1528 struct TestCase {
1529 const blink::WebCryptoAlgorithm algorithm;
1530 const blink::WebCryptoKeyUsageMask usage;
1531 const char* const jwk_alg;
1533 const TestCase kTests[] = {
1534 // RSASSA-PKCS1-v1_5 SHA-1
1535 {CreateRsaHashedImportAlgorithm(
1536 blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
1537 blink::WebCryptoAlgorithmIdSha1),
1538 blink::WebCryptoKeyUsageVerify, "RS1"},
1539 // RSASSA-PKCS1-v1_5 SHA-256
1540 {CreateRsaHashedImportAlgorithm(
1541 blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
1542 blink::WebCryptoAlgorithmIdSha256),
1543 blink::WebCryptoKeyUsageVerify, "RS256"},
1544 // RSASSA-PKCS1-v1_5 SHA-384
1545 {CreateRsaHashedImportAlgorithm(
1546 blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
1547 blink::WebCryptoAlgorithmIdSha384),
1548 blink::WebCryptoKeyUsageVerify, "RS384"},
1549 // RSASSA-PKCS1-v1_5 SHA-512
1550 {CreateRsaHashedImportAlgorithm(
1551 blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
1552 blink::WebCryptoAlgorithmIdSha512),
1553 blink::WebCryptoKeyUsageVerify, "RS512"},
1554 // RSA-OAEP with SHA-1 and MGF-1 / SHA-1
1555 {CreateRsaHashedImportAlgorithm(blink::WebCryptoAlgorithmIdRsaOaep,
1556 blink::WebCryptoAlgorithmIdSha1),
1557 blink::WebCryptoKeyUsageEncrypt, "RSA-OAEP"},
1558 // RSA-OAEP with SHA-256 and MGF-1 / SHA-256
1559 {CreateRsaHashedImportAlgorithm(blink::WebCryptoAlgorithmIdRsaOaep,
1560 blink::WebCryptoAlgorithmIdSha256),
1561 blink::WebCryptoKeyUsageEncrypt, "RSA-OAEP-256"},
1562 // RSA-OAEP with SHA-384 and MGF-1 / SHA-384
1563 {CreateRsaHashedImportAlgorithm(blink::WebCryptoAlgorithmIdRsaOaep,
1564 blink::WebCryptoAlgorithmIdSha384),
1565 blink::WebCryptoKeyUsageEncrypt, "RSA-OAEP-384"},
1566 // RSA-OAEP with SHA-512 and MGF-1 / SHA-512
1567 {CreateRsaHashedImportAlgorithm(blink::WebCryptoAlgorithmIdRsaOaep,
1568 blink::WebCryptoAlgorithmIdSha512),
1569 blink::WebCryptoKeyUsageEncrypt, "RSA-OAEP-512"}};
1571 for (size_t test_index = 0; test_index < ARRAYSIZE_UNSAFE(kTests);
1572 ++test_index) {
1573 SCOPED_TRACE(test_index);
1574 const TestCase& test = kTests[test_index];
1575 if (!supports_rsa_oaep &&
1576 test.algorithm.id() == blink::WebCryptoAlgorithmIdRsaOaep) {
1577 continue;
1580 // Import the spki to create a public key
1581 blink::WebCryptoKey public_key = blink::WebCryptoKey::createNull();
1582 ASSERT_EQ(Status::Success(),
1583 ImportKey(blink::WebCryptoKeyFormatSpki,
1584 CryptoData(HexStringToBytes(kPublicKeySpkiDerHex)),
1585 test.algorithm,
1586 true,
1587 test.usage,
1588 &public_key));
1590 // Export the public key as JWK and verify its contents
1591 std::vector<uint8> jwk;
1592 ASSERT_EQ(Status::Success(),
1593 ExportKey(blink::WebCryptoKeyFormatJwk, public_key, &jwk));
1594 EXPECT_TRUE(VerifyPublicJwk(jwk,
1595 test.jwk_alg,
1596 kPublicKeyModulusHex,
1597 kPublicKeyExponentHex,
1598 test.usage));
1600 // Import the JWK back in to create a new key
1601 blink::WebCryptoKey public_key2 = blink::WebCryptoKey::createNull();
1602 ASSERT_EQ(
1603 Status::Success(),
1604 ImportKeyJwk(
1605 CryptoData(jwk), test.algorithm, true, test.usage, &public_key2));
1606 ASSERT_TRUE(public_key2.handle());
1607 EXPECT_EQ(blink::WebCryptoKeyTypePublic, public_key2.type());
1608 EXPECT_TRUE(public_key2.extractable());
1609 EXPECT_EQ(test.algorithm.id(), public_key2.algorithm().id());
1611 // Only perform SPKI consistency test for RSA-SSA as its
1612 // export format is the same as kPublicKeySpkiDerHex
1613 if (test.algorithm.id() == blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5) {
1614 // Export the new key as spki and compare to the original.
1615 std::vector<uint8> spki;
1616 ASSERT_EQ(Status::Success(),
1617 ExportKey(blink::WebCryptoKeyFormatSpki, public_key2, &spki));
1618 EXPECT_BYTES_EQ_HEX(kPublicKeySpkiDerHex, CryptoData(spki));
1623 TEST_F(SharedCryptoTest, MAYBE(ImportJwkRsaFailures)) {
1624 base::DictionaryValue dict;
1625 RestoreJwkRsaDictionary(&dict);
1626 blink::WebCryptoAlgorithm algorithm =
1627 CreateRsaHashedImportAlgorithm(blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
1628 blink::WebCryptoAlgorithmIdSha256);
1629 blink::WebCryptoKeyUsageMask usage_mask = blink::WebCryptoKeyUsageVerify;
1630 blink::WebCryptoKey key = blink::WebCryptoKey::createNull();
1632 // An RSA public key JWK _must_ have an "n" (modulus) and an "e" (exponent)
1633 // entry, while an RSA private key must have those plus at least a "d"
1634 // (private exponent) entry.
1635 // See http://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-18,
1636 // section 6.3.
1638 // Baseline pass.
1639 EXPECT_EQ(Status::Success(),
1640 ImportKeyJwkFromDict(dict, algorithm, false, usage_mask, &key));
1641 EXPECT_EQ(algorithm.id(), key.algorithm().id());
1642 EXPECT_FALSE(key.extractable());
1643 EXPECT_EQ(blink::WebCryptoKeyUsageVerify, key.usages());
1644 EXPECT_EQ(blink::WebCryptoKeyTypePublic, key.type());
1646 // The following are specific failure cases for when kty = "RSA".
1648 // Fail if either "n" or "e" is not present or malformed.
1649 const std::string kKtyParmName[] = {"n", "e"};
1650 for (size_t idx = 0; idx < ARRAYSIZE_UNSAFE(kKtyParmName); ++idx) {
1651 // Fail on missing parameter.
1652 dict.Remove(kKtyParmName[idx], NULL);
1653 EXPECT_NE(Status::Success(),
1654 ImportKeyJwkFromDict(dict, algorithm, false, usage_mask, &key));
1655 RestoreJwkRsaDictionary(&dict);
1657 // Fail on bad b64 parameter encoding.
1658 dict.SetString(kKtyParmName[idx], "Qk3f0DsytU8lfza2au #$% Htaw2xpop9yTuH0");
1659 EXPECT_NE(Status::Success(),
1660 ImportKeyJwkFromDict(dict, algorithm, false, usage_mask, &key));
1661 RestoreJwkRsaDictionary(&dict);
1663 // Fail on empty parameter.
1664 dict.SetString(kKtyParmName[idx], "");
1665 EXPECT_NE(Status::Success(),
1666 ImportKeyJwkFromDict(dict, algorithm, false, usage_mask, &key));
1667 RestoreJwkRsaDictionary(&dict);
1671 TEST_F(SharedCryptoTest, MAYBE(ImportJwkInputConsistency)) {
1672 // The Web Crypto spec says that if a JWK value is present, but is
1673 // inconsistent with the input value, the operation must fail.
1675 // Consistency rules when JWK value is not present: Inputs should be used.
1676 blink::WebCryptoKey key = blink::WebCryptoKey::createNull();
1677 bool extractable = false;
1678 blink::WebCryptoAlgorithm algorithm =
1679 CreateHmacImportAlgorithm(blink::WebCryptoAlgorithmIdSha256);
1680 blink::WebCryptoKeyUsageMask usage_mask = blink::WebCryptoKeyUsageVerify;
1681 base::DictionaryValue dict;
1682 dict.SetString("kty", "oct");
1683 dict.SetString("k", "l3nZEgZCeX8XRwJdWyK3rGB8qwjhdY8vOkbIvh4lxTuMao9Y_--hdg");
1684 std::vector<uint8> json_vec = MakeJsonVector(dict);
1685 EXPECT_EQ(
1686 Status::Success(),
1687 ImportKeyJwk(
1688 CryptoData(json_vec), algorithm, extractable, usage_mask, &key));
1689 EXPECT_TRUE(key.handle());
1690 EXPECT_EQ(blink::WebCryptoKeyTypeSecret, key.type());
1691 EXPECT_EQ(extractable, key.extractable());
1692 EXPECT_EQ(blink::WebCryptoAlgorithmIdHmac, key.algorithm().id());
1693 EXPECT_EQ(blink::WebCryptoAlgorithmIdSha256,
1694 key.algorithm().hmacParams()->hash().id());
1695 EXPECT_EQ(320u, key.algorithm().hmacParams()->lengthBits());
1696 EXPECT_EQ(blink::WebCryptoKeyUsageVerify, key.usages());
1697 key = blink::WebCryptoKey::createNull();
1699 // Consistency rules when JWK value exists: Fail if inconsistency is found.
1701 // Pass: All input values are consistent with the JWK values.
1702 dict.Clear();
1703 dict.SetString("kty", "oct");
1704 dict.SetString("alg", "HS256");
1705 dict.SetString("use", "sig");
1706 dict.SetBoolean("ext", false);
1707 dict.SetString("k", "l3nZEgZCeX8XRwJdWyK3rGB8qwjhdY8vOkbIvh4lxTuMao9Y_--hdg");
1708 json_vec = MakeJsonVector(dict);
1709 EXPECT_EQ(
1710 Status::Success(),
1711 ImportKeyJwk(
1712 CryptoData(json_vec), algorithm, extractable, usage_mask, &key));
1714 // Extractable cases:
1715 // 1. input=T, JWK=F ==> fail (inconsistent)
1716 // 4. input=F, JWK=F ==> pass, result extractable is F
1717 // 2. input=T, JWK=T ==> pass, result extractable is T
1718 // 3. input=F, JWK=T ==> pass, result extractable is F
1719 EXPECT_EQ(
1720 Status::ErrorJwkExtInconsistent(),
1721 ImportKeyJwk(CryptoData(json_vec), algorithm, true, usage_mask, &key));
1722 EXPECT_EQ(
1723 Status::Success(),
1724 ImportKeyJwk(CryptoData(json_vec), algorithm, false, usage_mask, &key));
1725 EXPECT_FALSE(key.extractable());
1726 dict.SetBoolean("ext", true);
1727 EXPECT_EQ(Status::Success(),
1728 ImportKeyJwkFromDict(dict, algorithm, true, usage_mask, &key));
1729 EXPECT_TRUE(key.extractable());
1730 EXPECT_EQ(Status::Success(),
1731 ImportKeyJwkFromDict(dict, algorithm, false, usage_mask, &key));
1732 EXPECT_FALSE(key.extractable());
1733 dict.SetBoolean("ext", true); // restore previous value
1735 // Fail: Input algorithm (AES-CBC) is inconsistent with JWK value
1736 // (HMAC SHA256).
1737 EXPECT_EQ(Status::ErrorJwkAlgorithmInconsistent(),
1738 ImportKeyJwk(CryptoData(json_vec),
1739 CreateAlgorithm(blink::WebCryptoAlgorithmIdAesCbc),
1740 extractable,
1741 blink::WebCryptoKeyUsageEncrypt,
1742 &key));
1744 // Fail: Input algorithm (HMAC SHA1) is inconsistent with JWK value
1745 // (HMAC SHA256).
1746 EXPECT_EQ(
1747 Status::ErrorJwkAlgorithmInconsistent(),
1748 ImportKeyJwk(CryptoData(json_vec),
1749 CreateHmacImportAlgorithm(blink::WebCryptoAlgorithmIdSha1),
1750 extractable,
1751 usage_mask,
1752 &key));
1754 // Pass: JWK alg missing but input algorithm specified: use input value
1755 dict.Remove("alg", NULL);
1756 EXPECT_EQ(Status::Success(),
1757 ImportKeyJwkFromDict(
1758 dict,
1759 CreateHmacImportAlgorithm(blink::WebCryptoAlgorithmIdSha256),
1760 extractable,
1761 usage_mask,
1762 &key));
1763 EXPECT_EQ(blink::WebCryptoAlgorithmIdHmac, algorithm.id());
1764 dict.SetString("alg", "HS256");
1766 // Fail: Input usage_mask (encrypt) is not a subset of the JWK value
1767 // (sign|verify). Moreover "encrypt" is not a valid usage for HMAC.
1768 EXPECT_EQ(Status::ErrorCreateKeyBadUsages(),
1769 ImportKeyJwk(CryptoData(json_vec),
1770 algorithm,
1771 extractable,
1772 blink::WebCryptoKeyUsageEncrypt,
1773 &key));
1775 // Fail: Input usage_mask (encrypt|sign|verify) is not a subset of the JWK
1776 // value (sign|verify). Moreover "encrypt" is not a valid usage for HMAC.
1777 usage_mask = blink::WebCryptoKeyUsageEncrypt | blink::WebCryptoKeyUsageSign |
1778 blink::WebCryptoKeyUsageVerify;
1779 EXPECT_EQ(
1780 Status::ErrorCreateKeyBadUsages(),
1781 ImportKeyJwk(
1782 CryptoData(json_vec), algorithm, extractable, usage_mask, &key));
1784 // TODO(padolph): kty vs alg consistency tests: Depending on the kty value,
1785 // only certain alg values are permitted. For example, when kty = "RSA" alg
1786 // must be of the RSA family, or when kty = "oct" alg must be symmetric
1787 // algorithm.
1789 // TODO(padolph): key_ops consistency tests
1792 TEST_F(SharedCryptoTest, MAYBE(ImportJwkHappy)) {
1793 // This test verifies the happy path of JWK import, including the application
1794 // of the imported key material.
1796 blink::WebCryptoKey key = blink::WebCryptoKey::createNull();
1797 bool extractable = false;
1798 blink::WebCryptoAlgorithm algorithm =
1799 CreateHmacImportAlgorithm(blink::WebCryptoAlgorithmIdSha256);
1800 blink::WebCryptoKeyUsageMask usage_mask = blink::WebCryptoKeyUsageSign;
1802 // Import a symmetric key JWK and HMAC-SHA256 sign()
1803 // Uses the first SHA256 test vector from the HMAC sample set above.
1805 base::DictionaryValue dict;
1806 dict.SetString("kty", "oct");
1807 dict.SetString("alg", "HS256");
1808 dict.SetString("use", "sig");
1809 dict.SetBoolean("ext", false);
1810 dict.SetString("k", "l3nZEgZCeX8XRwJdWyK3rGB8qwjhdY8vOkbIvh4lxTuMao9Y_--hdg");
1812 ASSERT_EQ(
1813 Status::Success(),
1814 ImportKeyJwkFromDict(dict, algorithm, extractable, usage_mask, &key));
1816 EXPECT_EQ(blink::WebCryptoAlgorithmIdSha256,
1817 key.algorithm().hmacParams()->hash().id());
1819 const std::vector<uint8> message_raw = HexStringToBytes(
1820 "b1689c2591eaf3c9e66070f8a77954ffb81749f1b00346f9dfe0b2ee905dcc288baf4a"
1821 "92de3f4001dd9f44c468c3d07d6c6ee82faceafc97c2fc0fc0601719d2dcd0aa2aec92"
1822 "d1b0ae933c65eb06a03c9c935c2bad0459810241347ab87e9f11adb30415424c6c7f5f"
1823 "22a003b8ab8de54f6ded0e3ab9245fa79568451dfa258e");
1825 std::vector<uint8> output;
1827 ASSERT_EQ(Status::Success(),
1828 Sign(CreateAlgorithm(blink::WebCryptoAlgorithmIdHmac),
1829 key,
1830 CryptoData(message_raw),
1831 &output));
1833 const std::string mac_raw =
1834 "769f00d3e6a6cc1fb426a14a4f76c6462e6149726e0dee0ec0cf97a16605ac8b";
1836 EXPECT_BYTES_EQ_HEX(mac_raw, output);
1838 // TODO(padolph): Import an RSA public key JWK and use it
1841 TEST_F(SharedCryptoTest, MAYBE(ImportExportJwkSymmetricKey)) {
1842 // Raw keys are generated by openssl:
1843 // % openssl rand -hex <key length bytes>
1844 const char* const key_hex_128 = "3f1e7cd4f6f8543f6b1e16002e688623";
1845 const char* const key_hex_256 =
1846 "bd08286b81a74783fd1ccf46b7e05af84ee25ae021210074159e0c4d9d907692";
1847 const char* const key_hex_384 =
1848 "a22c5441c8b185602283d64c7221de1d0951e706bfc09539435ec0e0ed614e1d406623f2"
1849 "b31d31819fec30993380dd82";
1850 const char* const key_hex_512 =
1851 "5834f639000d4cf82de124fbfd26fb88d463e99f839a76ba41ac88967c80a3f61e1239a4"
1852 "52e573dba0750e988152988576efd75b8d0229b7aca2ada2afd392ee";
1853 const blink::WebCryptoAlgorithm aes_cbc_alg =
1854 webcrypto::CreateAlgorithm(blink::WebCryptoAlgorithmIdAesCbc);
1855 const blink::WebCryptoAlgorithm aes_gcm_alg =
1856 webcrypto::CreateAlgorithm(blink::WebCryptoAlgorithmIdAesGcm);
1857 const blink::WebCryptoAlgorithm aes_kw_alg =
1858 webcrypto::CreateAlgorithm(blink::WebCryptoAlgorithmIdAesKw);
1859 const blink::WebCryptoAlgorithm hmac_sha_1_alg =
1860 webcrypto::CreateHmacImportAlgorithm(blink::WebCryptoAlgorithmIdSha1);
1861 const blink::WebCryptoAlgorithm hmac_sha_256_alg =
1862 webcrypto::CreateHmacImportAlgorithm(blink::WebCryptoAlgorithmIdSha256);
1863 const blink::WebCryptoAlgorithm hmac_sha_384_alg =
1864 webcrypto::CreateHmacImportAlgorithm(blink::WebCryptoAlgorithmIdSha384);
1865 const blink::WebCryptoAlgorithm hmac_sha_512_alg =
1866 webcrypto::CreateHmacImportAlgorithm(blink::WebCryptoAlgorithmIdSha512);
1868 struct TestCase {
1869 const char* const key_hex;
1870 const blink::WebCryptoAlgorithm algorithm;
1871 const blink::WebCryptoKeyUsageMask usage;
1872 const char* const jwk_alg;
1875 // TODO(padolph): Test AES-CTR JWK export, once AES-CTR import works.
1876 const TestCase kTests[] = {
1877 // AES-CBC 128
1878 {key_hex_128, aes_cbc_alg,
1879 blink::WebCryptoKeyUsageEncrypt | blink::WebCryptoKeyUsageDecrypt,
1880 "A128CBC"},
1881 // AES-CBC 256
1882 {key_hex_256, aes_cbc_alg, blink::WebCryptoKeyUsageDecrypt, "A256CBC"},
1883 // AES-GCM 128
1884 {key_hex_128, aes_gcm_alg,
1885 blink::WebCryptoKeyUsageEncrypt | blink::WebCryptoKeyUsageDecrypt,
1886 "A128GCM"},
1887 // AES-GCM 256
1888 {key_hex_256, aes_gcm_alg, blink::WebCryptoKeyUsageDecrypt, "A256GCM"},
1889 // AES-KW 128
1890 {key_hex_128, aes_kw_alg,
1891 blink::WebCryptoKeyUsageWrapKey | blink::WebCryptoKeyUsageUnwrapKey,
1892 "A128KW"},
1893 // AES-KW 256
1894 {key_hex_256, aes_kw_alg,
1895 blink::WebCryptoKeyUsageWrapKey | blink::WebCryptoKeyUsageUnwrapKey,
1896 "A256KW"},
1897 // HMAC SHA-1
1898 {key_hex_256, hmac_sha_1_alg,
1899 blink::WebCryptoKeyUsageSign | blink::WebCryptoKeyUsageVerify, "HS1"},
1900 // HMAC SHA-384
1901 {key_hex_384, hmac_sha_384_alg, blink::WebCryptoKeyUsageSign, "HS384"},
1902 // HMAC SHA-512
1903 {key_hex_512, hmac_sha_512_alg, blink::WebCryptoKeyUsageVerify, "HS512"},
1904 // Large usage value
1905 {key_hex_256, aes_cbc_alg,
1906 blink::WebCryptoKeyUsageEncrypt | blink::WebCryptoKeyUsageDecrypt |
1907 blink::WebCryptoKeyUsageWrapKey | blink::WebCryptoKeyUsageUnwrapKey,
1908 "A256CBC"},
1909 // Zero usage value
1910 {key_hex_512, hmac_sha_512_alg, 0, "HS512"},
1913 // Round-trip import/export each key.
1915 blink::WebCryptoKey key = blink::WebCryptoKey::createNull();
1916 std::vector<uint8> json;
1917 for (size_t test_index = 0; test_index < ARRAYSIZE_UNSAFE(kTests);
1918 ++test_index) {
1919 SCOPED_TRACE(test_index);
1920 const TestCase& test = kTests[test_index];
1922 // Skip AES-GCM tests where not supported.
1923 if (test.algorithm.id() == blink::WebCryptoAlgorithmIdAesGcm &&
1924 !SupportsAesGcm()) {
1925 continue;
1928 // Import a raw key.
1929 key = ImportSecretKeyFromRaw(
1930 HexStringToBytes(test.key_hex), test.algorithm, test.usage);
1932 // Export the key in JWK format and validate.
1933 ASSERT_EQ(Status::Success(),
1934 ExportKey(blink::WebCryptoKeyFormatJwk, key, &json));
1935 EXPECT_TRUE(VerifySecretJwk(json, test.jwk_alg, test.key_hex, test.usage));
1937 // Import the JWK-formatted key.
1938 ASSERT_EQ(
1939 Status::Success(),
1940 ImportKeyJwk(CryptoData(json), test.algorithm, true, test.usage, &key));
1941 EXPECT_TRUE(key.handle());
1942 EXPECT_EQ(blink::WebCryptoKeyTypeSecret, key.type());
1943 EXPECT_EQ(test.algorithm.id(), key.algorithm().id());
1944 EXPECT_EQ(true, key.extractable());
1945 EXPECT_EQ(test.usage, key.usages());
1947 // Export the key in raw format and compare to the original.
1948 std::vector<uint8> key_raw_out;
1949 ASSERT_EQ(Status::Success(),
1950 ExportKey(blink::WebCryptoKeyFormatRaw, key, &key_raw_out));
1951 EXPECT_BYTES_EQ_HEX(test.key_hex, key_raw_out);
1955 TEST_F(SharedCryptoTest, MAYBE(ExportJwkEmptySymmetricKey)) {
1956 const blink::WebCryptoAlgorithm import_algorithm =
1957 webcrypto::CreateHmacImportAlgorithm(blink::WebCryptoAlgorithmIdSha1);
1959 blink::WebCryptoKeyUsageMask usages = blink::WebCryptoKeyUsageSign;
1960 blink::WebCryptoKey key = blink::WebCryptoKey::createNull();
1962 // Import a zero-byte HMAC key.
1963 const char key_data_hex[] = "";
1964 key = ImportSecretKeyFromRaw(
1965 HexStringToBytes(key_data_hex), import_algorithm, usages);
1966 EXPECT_EQ(0u, key.algorithm().hmacParams()->lengthBits());
1968 // Export the key in JWK format and validate.
1969 std::vector<uint8> json;
1970 ASSERT_EQ(Status::Success(),
1971 ExportKey(blink::WebCryptoKeyFormatJwk, key, &json));
1972 EXPECT_TRUE(VerifySecretJwk(json, "HS1", key_data_hex, usages));
1974 // Now try re-importing the JWK key.
1975 key = blink::WebCryptoKey::createNull();
1976 EXPECT_EQ(Status::Success(),
1977 ImportKey(blink::WebCryptoKeyFormatJwk,
1978 CryptoData(json),
1979 import_algorithm,
1980 true,
1981 usages,
1982 &key));
1984 EXPECT_EQ(blink::WebCryptoKeyTypeSecret, key.type());
1985 EXPECT_EQ(0u, key.algorithm().hmacParams()->lengthBits());
1987 std::vector<uint8> exported_key_data;
1988 EXPECT_EQ(Status::Success(),
1989 ExportKey(blink::WebCryptoKeyFormatRaw, key, &exported_key_data));
1991 EXPECT_EQ(0u, exported_key_data.size());
1994 TEST_F(SharedCryptoTest, MAYBE(ImportExportSpki)) {
1995 if (!SupportsRsaKeyImport())
1996 return;
1998 // Passing case: Import a valid RSA key in SPKI format.
1999 blink::WebCryptoKey key = blink::WebCryptoKey::createNull();
2000 ASSERT_EQ(Status::Success(),
2001 ImportKey(blink::WebCryptoKeyFormatSpki,
2002 CryptoData(HexStringToBytes(kPublicKeySpkiDerHex)),
2003 CreateRsaHashedImportAlgorithm(
2004 blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
2005 blink::WebCryptoAlgorithmIdSha256),
2006 true,
2007 blink::WebCryptoKeyUsageVerify,
2008 &key));
2009 EXPECT_TRUE(key.handle());
2010 EXPECT_EQ(blink::WebCryptoKeyTypePublic, key.type());
2011 EXPECT_TRUE(key.extractable());
2012 EXPECT_EQ(blink::WebCryptoKeyUsageVerify, key.usages());
2013 EXPECT_EQ(kModulusLengthBits,
2014 key.algorithm().rsaHashedParams()->modulusLengthBits());
2015 EXPECT_BYTES_EQ_HEX(
2016 "010001",
2017 CryptoData(key.algorithm().rsaHashedParams()->publicExponent()));
2019 // Failing case: Empty SPKI data
2020 EXPECT_EQ(
2021 Status::ErrorImportEmptyKeyData(),
2022 ImportKey(blink::WebCryptoKeyFormatSpki,
2023 CryptoData(std::vector<uint8>()),
2024 CreateAlgorithm(blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5),
2025 true,
2026 blink::WebCryptoKeyUsageVerify,
2027 &key));
2029 // Failing case: Bad DER encoding.
2030 EXPECT_EQ(
2031 Status::DataError(),
2032 ImportKey(blink::WebCryptoKeyFormatSpki,
2033 CryptoData(HexStringToBytes("618333c4cb")),
2034 CreateAlgorithm(blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5),
2035 true,
2036 blink::WebCryptoKeyUsageVerify,
2037 &key));
2039 // Failing case: Import RSA key but provide an inconsistent input algorithm.
2040 EXPECT_EQ(Status::DataError(),
2041 ImportKey(blink::WebCryptoKeyFormatSpki,
2042 CryptoData(HexStringToBytes(kPublicKeySpkiDerHex)),
2043 CreateAlgorithm(blink::WebCryptoAlgorithmIdAesCbc),
2044 true,
2045 blink::WebCryptoKeyUsageEncrypt,
2046 &key));
2048 // Passing case: Export a previously imported RSA public key in SPKI format
2049 // and compare to original data.
2050 std::vector<uint8> output;
2051 ASSERT_EQ(Status::Success(),
2052 ExportKey(blink::WebCryptoKeyFormatSpki, key, &output));
2053 EXPECT_BYTES_EQ_HEX(kPublicKeySpkiDerHex, output);
2055 // Failing case: Try to export a previously imported RSA public key in raw
2056 // format (not allowed for a public key).
2057 EXPECT_EQ(Status::ErrorUnexpectedKeyType(),
2058 ExportKey(blink::WebCryptoKeyFormatRaw, key, &output));
2060 // Failing case: Try to export a non-extractable key
2061 ASSERT_EQ(Status::Success(),
2062 ImportKey(blink::WebCryptoKeyFormatSpki,
2063 CryptoData(HexStringToBytes(kPublicKeySpkiDerHex)),
2064 CreateRsaHashedImportAlgorithm(
2065 blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
2066 blink::WebCryptoAlgorithmIdSha256),
2067 false,
2068 blink::WebCryptoKeyUsageVerify,
2069 &key));
2070 EXPECT_TRUE(key.handle());
2071 EXPECT_FALSE(key.extractable());
2072 EXPECT_EQ(Status::ErrorKeyNotExtractable(),
2073 ExportKey(blink::WebCryptoKeyFormatSpki, key, &output));
2075 // TODO(eroman): Failing test: Import a SPKI with an unrecognized hash OID
2076 // TODO(eroman): Failing test: Import a SPKI with invalid algorithm params
2077 // TODO(eroman): Failing test: Import a SPKI with inconsistent parameters
2078 // (e.g. SHA-1 in OID, SHA-256 in params)
2079 // TODO(eroman): Failing test: Import a SPKI for RSA-SSA, but with params
2080 // as OAEP/PSS
2083 TEST_F(SharedCryptoTest, MAYBE(ImportExportPkcs8)) {
2084 if (!SupportsRsaKeyImport())
2085 return;
2087 // Passing case: Import a valid RSA key in PKCS#8 format.
2088 blink::WebCryptoKey key = blink::WebCryptoKey::createNull();
2089 ASSERT_EQ(Status::Success(),
2090 ImportKey(blink::WebCryptoKeyFormatPkcs8,
2091 CryptoData(HexStringToBytes(kPrivateKeyPkcs8DerHex)),
2092 CreateRsaHashedImportAlgorithm(
2093 blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
2094 blink::WebCryptoAlgorithmIdSha1),
2095 true,
2096 blink::WebCryptoKeyUsageSign,
2097 &key));
2098 EXPECT_TRUE(key.handle());
2099 EXPECT_EQ(blink::WebCryptoKeyTypePrivate, key.type());
2100 EXPECT_TRUE(key.extractable());
2101 EXPECT_EQ(blink::WebCryptoKeyUsageSign, key.usages());
2102 EXPECT_EQ(blink::WebCryptoAlgorithmIdSha1,
2103 key.algorithm().rsaHashedParams()->hash().id());
2104 EXPECT_EQ(kModulusLengthBits,
2105 key.algorithm().rsaHashedParams()->modulusLengthBits());
2106 EXPECT_BYTES_EQ_HEX(
2107 "010001",
2108 CryptoData(key.algorithm().rsaHashedParams()->publicExponent()));
2110 std::vector<uint8> exported_key;
2111 ASSERT_EQ(Status::Success(),
2112 ExportKey(blink::WebCryptoKeyFormatPkcs8, key, &exported_key));
2113 EXPECT_BYTES_EQ_HEX(kPrivateKeyPkcs8DerHex, exported_key);
2115 // Failing case: Empty PKCS#8 data
2116 EXPECT_EQ(Status::ErrorImportEmptyKeyData(),
2117 ImportKey(blink::WebCryptoKeyFormatPkcs8,
2118 CryptoData(std::vector<uint8>()),
2119 CreateRsaHashedImportAlgorithm(
2120 blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
2121 blink::WebCryptoAlgorithmIdSha1),
2122 true,
2123 blink::WebCryptoKeyUsageSign,
2124 &key));
2126 // Failing case: Bad DER encoding.
2127 EXPECT_EQ(
2128 Status::DataError(),
2129 ImportKey(blink::WebCryptoKeyFormatPkcs8,
2130 CryptoData(HexStringToBytes("618333c4cb")),
2131 CreateAlgorithm(blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5),
2132 true,
2133 blink::WebCryptoKeyUsageSign,
2134 &key));
2136 // Failing case: Import RSA key but provide an inconsistent input algorithm
2137 // and usage. Several issues here:
2138 // * AES-CBC doesn't support PKCS8 key format
2139 // * AES-CBC doesn't support "sign" usage
2140 EXPECT_EQ(Status::ErrorCreateKeyBadUsages(),
2141 ImportKey(blink::WebCryptoKeyFormatPkcs8,
2142 CryptoData(HexStringToBytes(kPrivateKeyPkcs8DerHex)),
2143 CreateAlgorithm(blink::WebCryptoAlgorithmIdAesCbc),
2144 true,
2145 blink::WebCryptoKeyUsageSign,
2146 &key));
2149 // Tests JWK import and export by doing a roundtrip key conversion and ensuring
2150 // it was lossless:
2152 // PKCS8 --> JWK --> PKCS8
2153 TEST_F(SharedCryptoTest, MAYBE(ImportRsaPrivateKeyJwkToPkcs8RoundTrip)) {
2154 if (!SupportsRsaKeyImport())
2155 return;
2157 blink::WebCryptoKey key = blink::WebCryptoKey::createNull();
2158 ASSERT_EQ(Status::Success(),
2159 ImportKey(blink::WebCryptoKeyFormatPkcs8,
2160 CryptoData(HexStringToBytes(kPrivateKeyPkcs8DerHex)),
2161 CreateRsaHashedImportAlgorithm(
2162 blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
2163 blink::WebCryptoAlgorithmIdSha1),
2164 true,
2165 blink::WebCryptoKeyUsageSign,
2166 &key));
2168 std::vector<uint8> exported_key_jwk;
2169 ASSERT_EQ(Status::Success(),
2170 ExportKey(blink::WebCryptoKeyFormatJwk, key, &exported_key_jwk));
2172 // All of the optional parameters (p, q, dp, dq, qi) should be present in the
2173 // output.
2174 const char* expected_jwk =
2175 "{\"alg\":\"RS1\",\"d\":\"M6UEKpCyfU9UUcqbu9C0R3GhAa-IQ0Cu-YhfKku-"
2176 "kuiUpySsPFaMj5eFOtB8AmbIxqPKCSnx6PESMYhEKfxNmuVf7olqEM5wfD7X5zTkRyejlXRQ"
2177 "GlMmgxCcKrrKuig8MbS9L1PD7jfjUs7jT55QO9gMBiKtecbc7og1R8ajsyU\",\"dp\":"
2178 "\"KPoTk4ZVvh-"
2179 "KFZy6ylpy6hkMMAieGc0nSlVvNsT24Z9VSzTAd3kEJ7vdjdPt4kSDKPOF2Bsw6OQ7L_-"
2180 "gJ4YZeQ\",\"dq\":\"Gos485j6cSBJiY1_t57gp3ZoeRKZzfoJ78DlB6yyHtdDAe9b_Ui-"
2181 "RV6utuFnglWCdYCo5OjhQVHRUQqCo_LnKQ\",\"e\":\"AQAB\",\"ext\":true,\"key_"
2182 "ops\":[\"sign\"],\"kty\":\"RSA\",\"n\":"
2183 "\"pW5KDnAQF1iaUYfcfqhB0Vby7A42rVKkTf6x5h962ZHYxRBW_-2xYrTA8oOhKoijlN_"
2184 "1JqtykcuzB86r_OCx39XNlQgJbVsri2311nHvY3fAkhyyPCcKcOJZjm_4nRnxBazC0_"
2185 "DLNfKSgOE4a29kxO8i4eHyDQzoz_siSb2aITc\",\"p\":\"5-"
2186 "iUJyCod1Fyc6NWBT6iobwMlKpy1VxuhilrLfyWeUjApyy8zKfqyzVwbgmh31WhU1vZs8w0Fg"
2187 "s7bc0-2o5kQw\",\"q\":\"tp3KHPfU1-yB51uQ_MqHSrzeEj_"
2188 "ScAGAqpBHm25I3o1n7ST58Z2FuidYdPVCzSDccj5pYzZKH5QlRSsmmmeZ_Q\",\"qi\":"
2189 "\"JxVqukEm0kqB86Uoy_sn9WiG-"
2190 "ECp9uhuF6RLlP6TGVhLjiL93h5aLjvYqluo2FhBlOshkKz4MrhH8To9JKefTQ\"}";
2192 ASSERT_EQ(CryptoData(std::string(expected_jwk)),
2193 CryptoData(exported_key_jwk));
2195 ASSERT_EQ(Status::Success(),
2196 ImportKey(blink::WebCryptoKeyFormatJwk,
2197 CryptoData(exported_key_jwk),
2198 CreateRsaHashedImportAlgorithm(
2199 blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
2200 blink::WebCryptoAlgorithmIdSha1),
2201 true,
2202 blink::WebCryptoKeyUsageSign,
2203 &key));
2205 std::vector<uint8> exported_key_pkcs8;
2206 ASSERT_EQ(
2207 Status::Success(),
2208 ExportKey(blink::WebCryptoKeyFormatPkcs8, key, &exported_key_pkcs8));
2210 ASSERT_EQ(CryptoData(HexStringToBytes(kPrivateKeyPkcs8DerHex)),
2211 CryptoData(exported_key_pkcs8));
2214 // Tests importing multiple RSA private keys from JWK, and then exporting to
2215 // PKCS8.
2217 // This is a regression test for http://crbug.com/378315, for which importing
2218 // a sequence of keys from JWK could yield the wrong key. The first key would
2219 // be imported correctly, however every key after that would actually import
2220 // the first key.
2221 TEST_F(SharedCryptoTest, MAYBE(ImportMultipleRSAPrivateKeysJwk)) {
2222 if (!SupportsRsaKeyImport())
2223 return;
2225 scoped_ptr<base::ListValue> key_list;
2226 ASSERT_TRUE(ReadJsonTestFileToList("rsa_private_keys.json", &key_list));
2228 // For this test to be meaningful the keys MUST be kept alive before importing
2229 // new keys.
2230 std::vector<blink::WebCryptoKey> live_keys;
2232 for (size_t key_index = 0; key_index < key_list->GetSize(); ++key_index) {
2233 SCOPED_TRACE(key_index);
2235 base::DictionaryValue* key_values;
2236 ASSERT_TRUE(key_list->GetDictionary(key_index, &key_values));
2238 // Get the JWK representation of the key.
2239 base::DictionaryValue* key_jwk;
2240 ASSERT_TRUE(key_values->GetDictionary("jwk", &key_jwk));
2242 // Get the PKCS8 representation of the key.
2243 std::string pkcs8_hex_string;
2244 ASSERT_TRUE(key_values->GetString("pkcs8", &pkcs8_hex_string));
2245 std::vector<uint8> pkcs8_bytes = HexStringToBytes(pkcs8_hex_string);
2247 // Get the modulus length for the key.
2248 int modulus_length_bits = 0;
2249 ASSERT_TRUE(key_values->GetInteger("modulusLength", &modulus_length_bits));
2251 blink::WebCryptoKey private_key = blink::WebCryptoKey::createNull();
2253 // Import the key from JWK.
2254 ASSERT_EQ(
2255 Status::Success(),
2256 ImportKeyJwkFromDict(*key_jwk,
2257 CreateRsaHashedImportAlgorithm(
2258 blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
2259 blink::WebCryptoAlgorithmIdSha256),
2260 true,
2261 blink::WebCryptoKeyUsageSign,
2262 &private_key));
2264 live_keys.push_back(private_key);
2266 EXPECT_EQ(
2267 modulus_length_bits,
2268 static_cast<int>(
2269 private_key.algorithm().rsaHashedParams()->modulusLengthBits()));
2271 // Export to PKCS8 and verify that it matches expectation.
2272 std::vector<uint8> exported_key_pkcs8;
2273 ASSERT_EQ(
2274 Status::Success(),
2275 ExportKey(
2276 blink::WebCryptoKeyFormatPkcs8, private_key, &exported_key_pkcs8));
2278 EXPECT_BYTES_EQ(pkcs8_bytes, exported_key_pkcs8);
2282 // Import an RSA private key using JWK. Next import a JWK containing the same
2283 // modulus, but mismatched parameters for the rest. It should NOT be possible
2284 // that the second import retrieves the first key. See http://crbug.com/378315
2285 // for how that could happen.
2286 TEST_F(SharedCryptoTest, MAYBE(ImportJwkExistingModulusAndInvalid)) {
2287 #if defined(USE_NSS)
2288 if (!NSS_VersionCheck("3.16.2")) {
2289 LOG(WARNING) << "Skipping test because lacks NSS support";
2290 return;
2292 #endif
2294 scoped_ptr<base::ListValue> key_list;
2295 ASSERT_TRUE(ReadJsonTestFileToList("rsa_private_keys.json", &key_list));
2297 // Import a 1024-bit private key.
2298 base::DictionaryValue* key1_props;
2299 ASSERT_TRUE(key_list->GetDictionary(1, &key1_props));
2300 base::DictionaryValue* key1_jwk;
2301 ASSERT_TRUE(key1_props->GetDictionary("jwk", &key1_jwk));
2303 blink::WebCryptoKey key1 = blink::WebCryptoKey::createNull();
2304 ASSERT_EQ(Status::Success(),
2305 ImportKeyJwkFromDict(*key1_jwk,
2306 CreateRsaHashedImportAlgorithm(
2307 blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
2308 blink::WebCryptoAlgorithmIdSha256),
2309 true,
2310 blink::WebCryptoKeyUsageSign,
2311 &key1));
2313 ASSERT_EQ(1024u, key1.algorithm().rsaHashedParams()->modulusLengthBits());
2315 // Construct a JWK using the modulus of key1, but all the other fields from
2316 // another key (also a 1024-bit private key).
2317 base::DictionaryValue* key2_props;
2318 ASSERT_TRUE(key_list->GetDictionary(5, &key2_props));
2319 base::DictionaryValue* key2_jwk;
2320 ASSERT_TRUE(key2_props->GetDictionary("jwk", &key2_jwk));
2321 std::string modulus;
2322 key1_jwk->GetString("n", &modulus);
2323 key2_jwk->SetString("n", modulus);
2325 // This should fail, as the n,e,d parameters are not consistent. It MUST NOT
2326 // somehow return the key created earlier.
2327 blink::WebCryptoKey key2 = blink::WebCryptoKey::createNull();
2328 ASSERT_EQ(Status::OperationError(),
2329 ImportKeyJwkFromDict(*key2_jwk,
2330 CreateRsaHashedImportAlgorithm(
2331 blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
2332 blink::WebCryptoAlgorithmIdSha256),
2333 true,
2334 blink::WebCryptoKeyUsageSign,
2335 &key2));
2338 // Import a JWK RSA private key with some optional parameters missing (q, dp,
2339 // dq, qi).
2341 // The only optional parameter included is "p".
2343 // This fails because JWA says that producers must include either ALL optional
2344 // parameters or NONE.
2345 TEST_F(SharedCryptoTest, MAYBE(ImportRsaPrivateKeyJwkMissingOptionalParams)) {
2346 blink::WebCryptoKey key = blink::WebCryptoKey::createNull();
2348 base::DictionaryValue dict;
2349 dict.SetString("kty", "RSA");
2350 dict.SetString("alg", "RS1");
2352 dict.SetString(
2353 "n",
2354 "pW5KDnAQF1iaUYfcfqhB0Vby7A42rVKkTf6x5h962ZHYxRBW_-2xYrTA8oOhKoijlN_"
2355 "1JqtykcuzB86r_OCx39XNlQgJbVsri2311nHvY3fAkhyyPCcKcOJZjm_4nRnxBazC0_"
2356 "DLNfKSgOE4a29kxO8i4eHyDQzoz_siSb2aITc");
2357 dict.SetString("e", "AQAB");
2358 dict.SetString(
2359 "d",
2360 "M6UEKpCyfU9UUcqbu9C0R3GhAa-IQ0Cu-YhfKku-"
2361 "kuiUpySsPFaMj5eFOtB8AmbIxqPKCSnx6PESMYhEKfxNmuVf7olqEM5wfD7X5zTkRyejlXRQ"
2362 "GlMmgxCcKrrKuig8MbS9L1PD7jfjUs7jT55QO9gMBiKtecbc7og1R8ajsyU");
2364 dict.SetString("p",
2365 "5-"
2366 "iUJyCod1Fyc6NWBT6iobwMlKpy1VxuhilrLfyWeUjApyy8zKfqyzVwbgmh31W"
2367 "hU1vZs8w0Fgs7bc0-2o5kQw");
2369 ASSERT_EQ(Status::ErrorJwkIncompleteOptionalRsaPrivateKey(),
2370 ImportKeyJwkFromDict(dict,
2371 CreateRsaHashedImportAlgorithm(
2372 blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
2373 blink::WebCryptoAlgorithmIdSha1),
2374 true,
2375 blink::WebCryptoKeyUsageSign,
2376 &key));
2379 // Import a JWK RSA private key, without any of the optional parameters.
2381 // This is expected to work, however based on the current NSS implementation it
2382 // does not.
2384 // TODO(eroman): http://crbug/com/374927
2385 TEST_F(SharedCryptoTest, MAYBE(ImportRsaPrivateKeyJwkIncorrectOptionalEmpty)) {
2386 if (!SupportsRsaKeyImport())
2387 return;
2389 blink::WebCryptoKey key = blink::WebCryptoKey::createNull();
2391 base::DictionaryValue dict;
2392 dict.SetString("kty", "RSA");
2393 dict.SetString("alg", "RS1");
2395 dict.SetString(
2396 "n",
2397 "pW5KDnAQF1iaUYfcfqhB0Vby7A42rVKkTf6x5h962ZHYxRBW_-2xYrTA8oOhKoijlN_"
2398 "1JqtykcuzB86r_OCx39XNlQgJbVsri2311nHvY3fAkhyyPCcKcOJZjm_4nRnxBazC0_"
2399 "DLNfKSgOE4a29kxO8i4eHyDQzoz_siSb2aITc");
2400 dict.SetString("e", "AQAB");
2401 dict.SetString(
2402 "d",
2403 "M6UEKpCyfU9UUcqbu9C0R3GhAa-IQ0Cu-YhfKku-"
2404 "kuiUpySsPFaMj5eFOtB8AmbIxqPKCSnx6PESMYhEKfxNmuVf7olqEM5wfD7X5zTkRyejlXRQ"
2405 "GlMmgxCcKrrKuig8MbS9L1PD7jfjUs7jT55QO9gMBiKtecbc7og1R8ajsyU");
2407 // TODO(eroman): This should pass, see: http://crbug/com/374927
2409 // Technically it is OK to fail since JWA says that consumer are not required
2410 // to support lack of the optional parameters.
2411 ASSERT_EQ(Status::OperationError(),
2412 ImportKeyJwkFromDict(dict,
2413 CreateRsaHashedImportAlgorithm(
2414 blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
2415 blink::WebCryptoAlgorithmIdSha1),
2416 true,
2417 blink::WebCryptoKeyUsageSign,
2418 &key));
2422 TEST_F(SharedCryptoTest, MAYBE(GenerateKeyPairRsa)) {
2423 // Note: using unrealistic short key lengths here to avoid bogging down tests.
2425 // Successful WebCryptoAlgorithmIdRsaSsaPkcs1v1_5 key generation (sha256)
2426 const unsigned int modulus_length = 256;
2427 const std::vector<uint8> public_exponent = HexStringToBytes("010001");
2428 blink::WebCryptoAlgorithm algorithm =
2429 CreateRsaHashedKeyGenAlgorithm(blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
2430 blink::WebCryptoAlgorithmIdSha256,
2431 modulus_length,
2432 public_exponent);
2433 bool extractable = true;
2434 const blink::WebCryptoKeyUsageMask usage_mask = 0;
2435 blink::WebCryptoKey public_key = blink::WebCryptoKey::createNull();
2436 blink::WebCryptoKey private_key = blink::WebCryptoKey::createNull();
2438 EXPECT_EQ(Status::Success(),
2439 GenerateKeyPair(
2440 algorithm, extractable, usage_mask, &public_key, &private_key));
2441 EXPECT_FALSE(public_key.isNull());
2442 EXPECT_FALSE(private_key.isNull());
2443 EXPECT_EQ(blink::WebCryptoKeyTypePublic, public_key.type());
2444 EXPECT_EQ(blink::WebCryptoKeyTypePrivate, private_key.type());
2445 EXPECT_EQ(modulus_length,
2446 public_key.algorithm().rsaHashedParams()->modulusLengthBits());
2447 EXPECT_EQ(modulus_length,
2448 private_key.algorithm().rsaHashedParams()->modulusLengthBits());
2449 EXPECT_EQ(blink::WebCryptoAlgorithmIdSha256,
2450 public_key.algorithm().rsaHashedParams()->hash().id());
2451 EXPECT_EQ(blink::WebCryptoAlgorithmIdSha256,
2452 private_key.algorithm().rsaHashedParams()->hash().id());
2453 EXPECT_TRUE(public_key.extractable());
2454 EXPECT_EQ(extractable, private_key.extractable());
2455 EXPECT_EQ(usage_mask, public_key.usages());
2456 EXPECT_EQ(usage_mask, private_key.usages());
2458 // Try exporting the generated key pair, and then re-importing to verify that
2459 // the exported data was valid.
2460 std::vector<uint8> public_key_spki;
2461 EXPECT_EQ(
2462 Status::Success(),
2463 ExportKey(blink::WebCryptoKeyFormatSpki, public_key, &public_key_spki));
2465 if (SupportsRsaKeyImport()) {
2466 public_key = blink::WebCryptoKey::createNull();
2467 EXPECT_EQ(Status::Success(),
2468 ImportKey(blink::WebCryptoKeyFormatSpki,
2469 CryptoData(public_key_spki),
2470 CreateRsaHashedImportAlgorithm(
2471 blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
2472 blink::WebCryptoAlgorithmIdSha256),
2473 true,
2474 usage_mask,
2475 &public_key));
2476 EXPECT_EQ(modulus_length,
2477 public_key.algorithm().rsaHashedParams()->modulusLengthBits());
2479 std::vector<uint8> private_key_pkcs8;
2480 EXPECT_EQ(
2481 Status::Success(),
2482 ExportKey(
2483 blink::WebCryptoKeyFormatPkcs8, private_key, &private_key_pkcs8));
2484 private_key = blink::WebCryptoKey::createNull();
2485 EXPECT_EQ(Status::Success(),
2486 ImportKey(blink::WebCryptoKeyFormatPkcs8,
2487 CryptoData(private_key_pkcs8),
2488 CreateRsaHashedImportAlgorithm(
2489 blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
2490 blink::WebCryptoAlgorithmIdSha256),
2491 true,
2492 usage_mask,
2493 &private_key));
2494 EXPECT_EQ(modulus_length,
2495 private_key.algorithm().rsaHashedParams()->modulusLengthBits());
2498 // Fail with bad modulus.
2499 algorithm =
2500 CreateRsaHashedKeyGenAlgorithm(blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
2501 blink::WebCryptoAlgorithmIdSha256,
2503 public_exponent);
2504 EXPECT_EQ(Status::ErrorGenerateRsaZeroModulus(),
2505 GenerateKeyPair(
2506 algorithm, extractable, usage_mask, &public_key, &private_key));
2508 // Fail with bad exponent: larger than unsigned long.
2509 unsigned int exponent_length = sizeof(unsigned long) + 1; // NOLINT
2510 const std::vector<uint8> long_exponent(exponent_length, 0x01);
2511 algorithm =
2512 CreateRsaHashedKeyGenAlgorithm(blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
2513 blink::WebCryptoAlgorithmIdSha256,
2514 modulus_length,
2515 long_exponent);
2516 EXPECT_EQ(Status::ErrorGenerateKeyPublicExponent(),
2517 GenerateKeyPair(
2518 algorithm, extractable, usage_mask, &public_key, &private_key));
2520 // Fail with bad exponent: empty.
2521 const std::vector<uint8> empty_exponent;
2522 algorithm =
2523 CreateRsaHashedKeyGenAlgorithm(blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
2524 blink::WebCryptoAlgorithmIdSha256,
2525 modulus_length,
2526 empty_exponent);
2527 EXPECT_EQ(Status::ErrorGenerateKeyPublicExponent(),
2528 GenerateKeyPair(
2529 algorithm, extractable, usage_mask, &public_key, &private_key));
2531 // Fail with bad exponent: all zeros.
2532 std::vector<uint8> exponent_with_leading_zeros(15, 0x00);
2533 algorithm =
2534 CreateRsaHashedKeyGenAlgorithm(blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
2535 blink::WebCryptoAlgorithmIdSha256,
2536 modulus_length,
2537 exponent_with_leading_zeros);
2538 EXPECT_EQ(Status::ErrorGenerateKeyPublicExponent(),
2539 GenerateKeyPair(
2540 algorithm, extractable, usage_mask, &public_key, &private_key));
2542 // Key generation success using exponent with leading zeros.
2543 exponent_with_leading_zeros.insert(exponent_with_leading_zeros.end(),
2544 public_exponent.begin(),
2545 public_exponent.end());
2546 algorithm =
2547 CreateRsaHashedKeyGenAlgorithm(blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
2548 blink::WebCryptoAlgorithmIdSha256,
2549 modulus_length,
2550 exponent_with_leading_zeros);
2551 EXPECT_EQ(Status::Success(),
2552 GenerateKeyPair(
2553 algorithm, extractable, usage_mask, &public_key, &private_key));
2554 EXPECT_FALSE(public_key.isNull());
2555 EXPECT_FALSE(private_key.isNull());
2556 EXPECT_EQ(blink::WebCryptoKeyTypePublic, public_key.type());
2557 EXPECT_EQ(blink::WebCryptoKeyTypePrivate, private_key.type());
2558 EXPECT_TRUE(public_key.extractable());
2559 EXPECT_EQ(extractable, private_key.extractable());
2560 EXPECT_EQ(usage_mask, public_key.usages());
2561 EXPECT_EQ(usage_mask, private_key.usages());
2563 // Successful WebCryptoAlgorithmIdRsaSsaPkcs1v1_5 key generation (sha1)
2564 algorithm =
2565 CreateRsaHashedKeyGenAlgorithm(blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
2566 blink::WebCryptoAlgorithmIdSha1,
2567 modulus_length,
2568 public_exponent);
2569 EXPECT_EQ(
2570 Status::Success(),
2571 GenerateKeyPair(algorithm, false, usage_mask, &public_key, &private_key));
2572 EXPECT_FALSE(public_key.isNull());
2573 EXPECT_FALSE(private_key.isNull());
2574 EXPECT_EQ(blink::WebCryptoKeyTypePublic, public_key.type());
2575 EXPECT_EQ(blink::WebCryptoKeyTypePrivate, private_key.type());
2576 EXPECT_EQ(modulus_length,
2577 public_key.algorithm().rsaHashedParams()->modulusLengthBits());
2578 EXPECT_EQ(modulus_length,
2579 private_key.algorithm().rsaHashedParams()->modulusLengthBits());
2580 EXPECT_EQ(blink::WebCryptoAlgorithmIdSha1,
2581 public_key.algorithm().rsaHashedParams()->hash().id());
2582 EXPECT_EQ(blink::WebCryptoAlgorithmIdSha1,
2583 private_key.algorithm().rsaHashedParams()->hash().id());
2584 // Even though "extractable" was set to false, the public key remains
2585 // extractable.
2586 EXPECT_TRUE(public_key.extractable());
2587 EXPECT_FALSE(private_key.extractable());
2588 EXPECT_EQ(usage_mask, public_key.usages());
2589 EXPECT_EQ(usage_mask, private_key.usages());
2591 // Exporting a private key as SPKI format doesn't make sense. However this
2592 // will first fail because the key is not extractable.
2593 std::vector<uint8> output;
2594 EXPECT_EQ(Status::ErrorKeyNotExtractable(),
2595 ExportKey(blink::WebCryptoKeyFormatSpki, private_key, &output));
2597 // Re-generate an extractable private_key and try to export it as SPKI format.
2598 // This should fail since spki is for public keys.
2599 EXPECT_EQ(
2600 Status::Success(),
2601 GenerateKeyPair(algorithm, true, usage_mask, &public_key, &private_key));
2602 EXPECT_EQ(Status::ErrorUnexpectedKeyType(),
2603 ExportKey(blink::WebCryptoKeyFormatSpki, private_key, &output));
2606 TEST_F(SharedCryptoTest, MAYBE(GenerateKeyPairRsaBadModulusLength)) {
2607 const unsigned int kBadModulus[] = {
2609 255, // Not a multiple of 8.
2610 1023, // Not a multiple of 8.
2611 0xFFFFFFFF, // Cannot fit in a signed int.
2612 16384 + 8, // 16384 is the maxmimum length that NSS succeeds for.
2615 const std::vector<uint8> public_exponent = HexStringToBytes("010001");
2617 for (size_t i = 0; i < arraysize(kBadModulus); ++i) {
2618 const unsigned int modulus_length = kBadModulus[i];
2619 blink::WebCryptoAlgorithm algorithm = CreateRsaHashedKeyGenAlgorithm(
2620 blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
2621 blink::WebCryptoAlgorithmIdSha256,
2622 modulus_length,
2623 public_exponent);
2624 bool extractable = true;
2625 const blink::WebCryptoKeyUsageMask usage_mask = 0;
2626 blink::WebCryptoKey public_key = blink::WebCryptoKey::createNull();
2627 blink::WebCryptoKey private_key = blink::WebCryptoKey::createNull();
2629 EXPECT_FALSE(
2630 GenerateKeyPair(
2631 algorithm, extractable, usage_mask, &public_key, &private_key)
2632 .IsSuccess());
2636 // Try generating RSA key pairs using unsupported public exponents. Only
2637 // exponents of 3 and 65537 are supported. While both OpenSSL and NSS can
2638 // support other values, OpenSSL hangs when given invalid exponents, so use a
2639 // whitelist to validate the parameters.
2640 TEST_F(SharedCryptoTest, MAYBE(GenerateKeyPairRsaBadExponent)) {
2641 const unsigned int modulus_length = 1024;
2643 const char* const kPublicExponents[] = {
2644 "11", // 17 - This is a valid public exponent, but currently disallowed.
2645 "00",
2646 "01",
2647 "02",
2648 "010000", // 65536
2651 for (size_t i = 0; i < arraysize(kPublicExponents); ++i) {
2652 SCOPED_TRACE(i);
2653 blink::WebCryptoAlgorithm algorithm = CreateRsaHashedKeyGenAlgorithm(
2654 blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
2655 blink::WebCryptoAlgorithmIdSha256,
2656 modulus_length,
2657 HexStringToBytes(kPublicExponents[i]));
2659 blink::WebCryptoKey public_key = blink::WebCryptoKey::createNull();
2660 blink::WebCryptoKey private_key = blink::WebCryptoKey::createNull();
2662 EXPECT_EQ(Status::ErrorGenerateKeyPublicExponent(),
2663 GenerateKeyPair(
2664 algorithm, true, 0, &public_key, &private_key));
2668 TEST_F(SharedCryptoTest, MAYBE(RsaSsaSignVerifyFailures)) {
2669 if (!SupportsRsaKeyImport())
2670 return;
2672 // Import a key pair.
2673 blink::WebCryptoAlgorithm import_algorithm =
2674 CreateRsaHashedImportAlgorithm(blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
2675 blink::WebCryptoAlgorithmIdSha1);
2676 blink::WebCryptoKey public_key = blink::WebCryptoKey::createNull();
2677 blink::WebCryptoKey private_key = blink::WebCryptoKey::createNull();
2678 ASSERT_NO_FATAL_FAILURE(
2679 ImportRsaKeyPair(HexStringToBytes(kPublicKeySpkiDerHex),
2680 HexStringToBytes(kPrivateKeyPkcs8DerHex),
2681 import_algorithm,
2682 false,
2683 blink::WebCryptoKeyUsageVerify,
2684 blink::WebCryptoKeyUsageSign,
2685 &public_key,
2686 &private_key));
2688 blink::WebCryptoAlgorithm algorithm =
2689 CreateAlgorithm(blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5);
2691 std::vector<uint8> signature;
2692 bool signature_match;
2694 // Compute a signature.
2695 const std::vector<uint8> data = HexStringToBytes("010203040506070809");
2696 ASSERT_EQ(Status::Success(),
2697 Sign(algorithm, private_key, CryptoData(data), &signature));
2699 // Ensure truncated signature does not verify by passing one less byte.
2700 EXPECT_EQ(Status::Success(),
2701 VerifySignature(
2702 algorithm,
2703 public_key,
2704 CryptoData(Uint8VectorStart(signature), signature.size() - 1),
2705 CryptoData(data),
2706 &signature_match));
2707 EXPECT_FALSE(signature_match);
2709 // Ensure truncated signature does not verify by passing no bytes.
2710 EXPECT_EQ(Status::Success(),
2711 VerifySignature(algorithm,
2712 public_key,
2713 CryptoData(),
2714 CryptoData(data),
2715 &signature_match));
2716 EXPECT_FALSE(signature_match);
2718 // Ensure corrupted signature does not verify.
2719 std::vector<uint8> corrupt_sig = signature;
2720 corrupt_sig[corrupt_sig.size() / 2] ^= 0x1;
2721 EXPECT_EQ(Status::Success(),
2722 VerifySignature(algorithm,
2723 public_key,
2724 CryptoData(corrupt_sig),
2725 CryptoData(data),
2726 &signature_match));
2727 EXPECT_FALSE(signature_match);
2729 // Ensure signatures that are greater than the modulus size fail.
2730 const unsigned int long_message_size_bytes = 1024;
2731 DCHECK_GT(long_message_size_bytes, kModulusLengthBits / 8);
2732 const unsigned char kLongSignature[long_message_size_bytes] = {0};
2733 EXPECT_EQ(Status::Success(),
2734 VerifySignature(algorithm,
2735 public_key,
2736 CryptoData(kLongSignature, sizeof(kLongSignature)),
2737 CryptoData(data),
2738 &signature_match));
2739 EXPECT_FALSE(signature_match);
2741 // Ensure that signing and verifying with an incompatible algorithm fails.
2742 algorithm = CreateAlgorithm(blink::WebCryptoAlgorithmIdRsaOaep);
2744 EXPECT_EQ(Status::ErrorUnexpected(),
2745 Sign(algorithm, private_key, CryptoData(data), &signature));
2746 EXPECT_EQ(Status::ErrorUnexpected(),
2747 VerifySignature(algorithm,
2748 public_key,
2749 CryptoData(signature),
2750 CryptoData(data),
2751 &signature_match));
2753 // Some crypto libraries (NSS) can automatically select the RSA SSA inner hash
2754 // based solely on the contents of the input signature data. In the Web Crypto
2755 // implementation, the inner hash should be specified uniquely by the key
2756 // algorithm parameter. To validate this behavior, call Verify with a computed
2757 // signature that used one hash type (SHA-1), but pass in a key with a
2758 // different inner hash type (SHA-256). If the hash type is determined by the
2759 // signature itself (undesired), the verify will pass, while if the hash type
2760 // is specified by the key algorithm (desired), the verify will fail.
2762 // Compute a signature using SHA-1 as the inner hash.
2763 EXPECT_EQ(Status::Success(),
2764 Sign(CreateAlgorithm(blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5),
2765 private_key,
2766 CryptoData(data),
2767 &signature));
2769 blink::WebCryptoKey public_key_256 = blink::WebCryptoKey::createNull();
2770 EXPECT_EQ(Status::Success(),
2771 ImportKey(blink::WebCryptoKeyFormatSpki,
2772 CryptoData(HexStringToBytes(kPublicKeySpkiDerHex)),
2773 CreateRsaHashedImportAlgorithm(
2774 blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
2775 blink::WebCryptoAlgorithmIdSha256),
2776 true,
2777 blink::WebCryptoKeyUsageVerify,
2778 &public_key_256));
2780 // Now verify using an algorithm whose inner hash is SHA-256, not SHA-1. The
2781 // signature should not verify.
2782 // NOTE: public_key was produced by generateKey, and so its associated
2783 // algorithm has WebCryptoRsaKeyGenParams and not WebCryptoRsaSsaParams. Thus
2784 // it has no inner hash to conflict with the input algorithm.
2785 EXPECT_EQ(blink::WebCryptoAlgorithmIdSha1,
2786 private_key.algorithm().rsaHashedParams()->hash().id());
2787 EXPECT_EQ(blink::WebCryptoAlgorithmIdSha256,
2788 public_key_256.algorithm().rsaHashedParams()->hash().id());
2790 bool is_match;
2791 EXPECT_EQ(Status::Success(),
2792 VerifySignature(
2793 CreateAlgorithm(blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5),
2794 public_key_256,
2795 CryptoData(signature),
2796 CryptoData(data),
2797 &is_match));
2798 EXPECT_FALSE(is_match);
2801 TEST_F(SharedCryptoTest, MAYBE(RsaSignVerifyKnownAnswer)) {
2802 if (!SupportsRsaKeyImport())
2803 return;
2805 scoped_ptr<base::ListValue> tests;
2806 ASSERT_TRUE(ReadJsonTestFileToList("pkcs1v15_sign.json", &tests));
2808 // Import the key pair.
2809 blink::WebCryptoAlgorithm import_algorithm =
2810 CreateRsaHashedImportAlgorithm(blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
2811 blink::WebCryptoAlgorithmIdSha1);
2812 blink::WebCryptoKey public_key = blink::WebCryptoKey::createNull();
2813 blink::WebCryptoKey private_key = blink::WebCryptoKey::createNull();
2814 ASSERT_NO_FATAL_FAILURE(
2815 ImportRsaKeyPair(HexStringToBytes(kPublicKeySpkiDerHex),
2816 HexStringToBytes(kPrivateKeyPkcs8DerHex),
2817 import_algorithm,
2818 false,
2819 blink::WebCryptoKeyUsageVerify,
2820 blink::WebCryptoKeyUsageSign,
2821 &public_key,
2822 &private_key));
2824 blink::WebCryptoAlgorithm algorithm =
2825 CreateAlgorithm(blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5);
2827 // Validate the signatures are computed and verified as expected.
2828 std::vector<uint8> signature;
2829 for (size_t test_index = 0; test_index < tests->GetSize(); ++test_index) {
2830 SCOPED_TRACE(test_index);
2832 base::DictionaryValue* test;
2833 ASSERT_TRUE(tests->GetDictionary(test_index, &test));
2835 std::vector<uint8> test_message =
2836 GetBytesFromHexString(test, "message_hex");
2837 std::vector<uint8> test_signature =
2838 GetBytesFromHexString(test, "signature_hex");
2840 signature.clear();
2841 ASSERT_EQ(
2842 Status::Success(),
2843 Sign(algorithm, private_key, CryptoData(test_message), &signature));
2844 EXPECT_BYTES_EQ(test_signature, signature);
2846 bool is_match = false;
2847 ASSERT_EQ(Status::Success(),
2848 VerifySignature(algorithm,
2849 public_key,
2850 CryptoData(test_signature),
2851 CryptoData(test_message),
2852 &is_match));
2853 EXPECT_TRUE(is_match);
2857 TEST_F(SharedCryptoTest, MAYBE(AesKwKeyImport)) {
2858 blink::WebCryptoKey key = blink::WebCryptoKey::createNull();
2859 blink::WebCryptoAlgorithm algorithm =
2860 CreateAlgorithm(blink::WebCryptoAlgorithmIdAesKw);
2862 // Import a 128-bit Key Encryption Key (KEK)
2863 std::string key_raw_hex_in = "025a8cf3f08b4f6c5f33bbc76a471939";
2864 ASSERT_EQ(Status::Success(),
2865 ImportKey(blink::WebCryptoKeyFormatRaw,
2866 CryptoData(HexStringToBytes(key_raw_hex_in)),
2867 algorithm,
2868 true,
2869 blink::WebCryptoKeyUsageWrapKey,
2870 &key));
2871 std::vector<uint8> key_raw_out;
2872 EXPECT_EQ(Status::Success(),
2873 ExportKey(blink::WebCryptoKeyFormatRaw, key, &key_raw_out));
2874 EXPECT_BYTES_EQ_HEX(key_raw_hex_in, key_raw_out);
2876 // Import a 192-bit KEK
2877 key_raw_hex_in = "c0192c6466b2370decbb62b2cfef4384544ffeb4d2fbc103";
2878 ASSERT_EQ(Status::ErrorAes192BitUnsupported(),
2879 ImportKey(blink::WebCryptoKeyFormatRaw,
2880 CryptoData(HexStringToBytes(key_raw_hex_in)),
2881 algorithm,
2882 true,
2883 blink::WebCryptoKeyUsageWrapKey,
2884 &key));
2886 // Import a 256-bit Key Encryption Key (KEK)
2887 key_raw_hex_in =
2888 "e11fe66380d90fa9ebefb74e0478e78f95664d0c67ca20ce4a0b5842863ac46f";
2889 ASSERT_EQ(Status::Success(),
2890 ImportKey(blink::WebCryptoKeyFormatRaw,
2891 CryptoData(HexStringToBytes(key_raw_hex_in)),
2892 algorithm,
2893 true,
2894 blink::WebCryptoKeyUsageWrapKey,
2895 &key));
2896 EXPECT_EQ(Status::Success(),
2897 ExportKey(blink::WebCryptoKeyFormatRaw, key, &key_raw_out));
2898 EXPECT_BYTES_EQ_HEX(key_raw_hex_in, key_raw_out);
2900 // Fail import of 0 length key
2901 EXPECT_EQ(Status::ErrorImportAesKeyLength(),
2902 ImportKey(blink::WebCryptoKeyFormatRaw,
2903 CryptoData(HexStringToBytes("")),
2904 algorithm,
2905 true,
2906 blink::WebCryptoKeyUsageWrapKey,
2907 &key));
2909 // Fail import of 124-bit KEK
2910 key_raw_hex_in = "3e4566a2bdaa10cb68134fa66c15ddb";
2911 EXPECT_EQ(Status::ErrorImportAesKeyLength(),
2912 ImportKey(blink::WebCryptoKeyFormatRaw,
2913 CryptoData(HexStringToBytes(key_raw_hex_in)),
2914 algorithm,
2915 true,
2916 blink::WebCryptoKeyUsageWrapKey,
2917 &key));
2919 // Fail import of 200-bit KEK
2920 key_raw_hex_in = "0a1d88608a5ad9fec64f1ada269ebab4baa2feeb8d95638c0e";
2921 EXPECT_EQ(Status::ErrorImportAesKeyLength(),
2922 ImportKey(blink::WebCryptoKeyFormatRaw,
2923 CryptoData(HexStringToBytes(key_raw_hex_in)),
2924 algorithm,
2925 true,
2926 blink::WebCryptoKeyUsageWrapKey,
2927 &key));
2929 // Fail import of 260-bit KEK
2930 key_raw_hex_in =
2931 "72d4e475ff34215416c9ad9c8281247a4d730c5f275ac23f376e73e3bce8d7d5a";
2932 EXPECT_EQ(Status::ErrorImportAesKeyLength(),
2933 ImportKey(blink::WebCryptoKeyFormatRaw,
2934 CryptoData(HexStringToBytes(key_raw_hex_in)),
2935 algorithm,
2936 true,
2937 blink::WebCryptoKeyUsageWrapKey,
2938 &key));
2941 TEST_F(SharedCryptoTest, MAYBE(UnwrapFailures)) {
2942 // This test exercises the code path common to all unwrap operations.
2943 scoped_ptr<base::ListValue> tests;
2944 ASSERT_TRUE(ReadJsonTestFileToList("aes_kw.json", &tests));
2945 base::DictionaryValue* test;
2946 ASSERT_TRUE(tests->GetDictionary(0, &test));
2947 const std::vector<uint8> test_kek = GetBytesFromHexString(test, "kek");
2948 const std::vector<uint8> test_ciphertext =
2949 GetBytesFromHexString(test, "ciphertext");
2951 blink::WebCryptoKey unwrapped_key = blink::WebCryptoKey::createNull();
2953 // Using a wrapping algorithm that does not match the wrapping key algorithm
2954 // should fail.
2955 blink::WebCryptoKey wrapping_key = ImportSecretKeyFromRaw(
2956 test_kek,
2957 webcrypto::CreateAlgorithm(blink::WebCryptoAlgorithmIdAesKw),
2958 blink::WebCryptoKeyUsageUnwrapKey);
2959 EXPECT_EQ(
2960 Status::ErrorUnexpected(),
2961 UnwrapKey(blink::WebCryptoKeyFormatRaw,
2962 CryptoData(test_ciphertext),
2963 wrapping_key,
2964 webcrypto::CreateAlgorithm(blink::WebCryptoAlgorithmIdAesCbc),
2965 webcrypto::CreateAlgorithm(blink::WebCryptoAlgorithmIdAesCbc),
2966 true,
2967 blink::WebCryptoKeyUsageEncrypt,
2968 &unwrapped_key));
2971 TEST_F(SharedCryptoTest, MAYBE(AesKwRawSymkeyWrapUnwrapKnownAnswer)) {
2972 scoped_ptr<base::ListValue> tests;
2973 ASSERT_TRUE(ReadJsonTestFileToList("aes_kw.json", &tests));
2975 for (size_t test_index = 0; test_index < tests->GetSize(); ++test_index) {
2976 SCOPED_TRACE(test_index);
2977 base::DictionaryValue* test;
2978 ASSERT_TRUE(tests->GetDictionary(test_index, &test));
2979 const std::vector<uint8> test_kek = GetBytesFromHexString(test, "kek");
2980 const std::vector<uint8> test_key = GetBytesFromHexString(test, "key");
2981 const std::vector<uint8> test_ciphertext =
2982 GetBytesFromHexString(test, "ciphertext");
2983 const blink::WebCryptoAlgorithm wrapping_algorithm =
2984 webcrypto::CreateAlgorithm(blink::WebCryptoAlgorithmIdAesKw);
2986 // Import the wrapping key.
2987 blink::WebCryptoKey wrapping_key = ImportSecretKeyFromRaw(
2988 test_kek,
2989 wrapping_algorithm,
2990 blink::WebCryptoKeyUsageWrapKey | blink::WebCryptoKeyUsageUnwrapKey);
2992 // Import the key to be wrapped.
2993 blink::WebCryptoKey key = ImportSecretKeyFromRaw(
2994 test_key,
2995 CreateHmacImportAlgorithm(blink::WebCryptoAlgorithmIdSha1),
2996 blink::WebCryptoKeyUsageSign);
2998 // Wrap the key and verify the ciphertext result against the known answer.
2999 std::vector<uint8> wrapped_key;
3000 ASSERT_EQ(Status::Success(),
3001 WrapKey(blink::WebCryptoKeyFormatRaw,
3002 key,
3003 wrapping_key,
3004 wrapping_algorithm,
3005 &wrapped_key));
3006 EXPECT_BYTES_EQ(test_ciphertext, wrapped_key);
3008 // Unwrap the known ciphertext to get a new test_key.
3009 blink::WebCryptoKey unwrapped_key = blink::WebCryptoKey::createNull();
3010 ASSERT_EQ(
3011 Status::Success(),
3012 UnwrapKey(blink::WebCryptoKeyFormatRaw,
3013 CryptoData(test_ciphertext),
3014 wrapping_key,
3015 wrapping_algorithm,
3016 CreateHmacImportAlgorithm(blink::WebCryptoAlgorithmIdSha1),
3017 true,
3018 blink::WebCryptoKeyUsageSign,
3019 &unwrapped_key));
3020 EXPECT_FALSE(key.isNull());
3021 EXPECT_TRUE(key.handle());
3022 EXPECT_EQ(blink::WebCryptoKeyTypeSecret, key.type());
3023 EXPECT_EQ(blink::WebCryptoAlgorithmIdHmac, key.algorithm().id());
3024 EXPECT_EQ(true, key.extractable());
3025 EXPECT_EQ(blink::WebCryptoKeyUsageSign, key.usages());
3027 // Export the new key and compare its raw bytes with the original known key.
3028 std::vector<uint8> raw_key;
3029 EXPECT_EQ(Status::Success(),
3030 ExportKey(blink::WebCryptoKeyFormatRaw, unwrapped_key, &raw_key));
3031 EXPECT_BYTES_EQ(test_key, raw_key);
3035 // Unwrap a HMAC key using AES-KW, and then try doing a sign/verify with the
3036 // unwrapped key
3037 TEST_F(SharedCryptoTest, MAYBE(AesKwRawSymkeyUnwrapSignVerifyHmac)) {
3038 scoped_ptr<base::ListValue> tests;
3039 ASSERT_TRUE(ReadJsonTestFileToList("aes_kw.json", &tests));
3041 base::DictionaryValue* test;
3042 ASSERT_TRUE(tests->GetDictionary(0, &test));
3043 const std::vector<uint8> test_kek = GetBytesFromHexString(test, "kek");
3044 const std::vector<uint8> test_ciphertext =
3045 GetBytesFromHexString(test, "ciphertext");
3046 const blink::WebCryptoAlgorithm wrapping_algorithm =
3047 CreateAlgorithm(blink::WebCryptoAlgorithmIdAesKw);
3049 // Import the wrapping key.
3050 blink::WebCryptoKey wrapping_key = ImportSecretKeyFromRaw(
3051 test_kek, wrapping_algorithm, blink::WebCryptoKeyUsageUnwrapKey);
3053 // Unwrap the known ciphertext.
3054 blink::WebCryptoKey key = blink::WebCryptoKey::createNull();
3055 ASSERT_EQ(
3056 Status::Success(),
3057 UnwrapKey(blink::WebCryptoKeyFormatRaw,
3058 CryptoData(test_ciphertext),
3059 wrapping_key,
3060 wrapping_algorithm,
3061 CreateHmacImportAlgorithm(blink::WebCryptoAlgorithmIdSha1),
3062 false,
3063 blink::WebCryptoKeyUsageSign | blink::WebCryptoKeyUsageVerify,
3064 &key));
3066 EXPECT_EQ(blink::WebCryptoKeyTypeSecret, key.type());
3067 EXPECT_EQ(blink::WebCryptoAlgorithmIdHmac, key.algorithm().id());
3068 EXPECT_FALSE(key.extractable());
3069 EXPECT_EQ(blink::WebCryptoKeyUsageSign | blink::WebCryptoKeyUsageVerify,
3070 key.usages());
3072 // Sign an empty message and ensure it is verified.
3073 std::vector<uint8> test_message;
3074 std::vector<uint8> signature;
3076 ASSERT_EQ(Status::Success(),
3077 Sign(CreateAlgorithm(blink::WebCryptoAlgorithmIdHmac),
3078 key,
3079 CryptoData(test_message),
3080 &signature));
3082 EXPECT_GT(signature.size(), 0u);
3084 bool verify_result;
3085 ASSERT_EQ(Status::Success(),
3086 VerifySignature(CreateAlgorithm(blink::WebCryptoAlgorithmIdHmac),
3087 key,
3088 CryptoData(signature),
3089 CryptoData(test_message),
3090 &verify_result));
3093 TEST_F(SharedCryptoTest, MAYBE(AesKwRawSymkeyWrapUnwrapErrors)) {
3094 scoped_ptr<base::ListValue> tests;
3095 ASSERT_TRUE(ReadJsonTestFileToList("aes_kw.json", &tests));
3096 base::DictionaryValue* test;
3097 // Use 256 bits of data with a 256-bit KEK
3098 ASSERT_TRUE(tests->GetDictionary(3, &test));
3099 const std::vector<uint8> test_kek = GetBytesFromHexString(test, "kek");
3100 const std::vector<uint8> test_key = GetBytesFromHexString(test, "key");
3101 const std::vector<uint8> test_ciphertext =
3102 GetBytesFromHexString(test, "ciphertext");
3103 const blink::WebCryptoAlgorithm wrapping_algorithm =
3104 webcrypto::CreateAlgorithm(blink::WebCryptoAlgorithmIdAesKw);
3105 const blink::WebCryptoAlgorithm key_algorithm =
3106 webcrypto::CreateAlgorithm(blink::WebCryptoAlgorithmIdAesCbc);
3107 // Import the wrapping key.
3108 blink::WebCryptoKey wrapping_key = ImportSecretKeyFromRaw(
3109 test_kek,
3110 wrapping_algorithm,
3111 blink::WebCryptoKeyUsageWrapKey | blink::WebCryptoKeyUsageUnwrapKey);
3112 // Import the key to be wrapped.
3113 blink::WebCryptoKey key = ImportSecretKeyFromRaw(
3114 test_key,
3115 webcrypto::CreateAlgorithm(blink::WebCryptoAlgorithmIdAesCbc),
3116 blink::WebCryptoKeyUsageEncrypt);
3118 // Unwrap with wrapped data too small must fail.
3119 const std::vector<uint8> small_data(test_ciphertext.begin(),
3120 test_ciphertext.begin() + 23);
3121 blink::WebCryptoKey unwrapped_key = blink::WebCryptoKey::createNull();
3122 EXPECT_EQ(Status::ErrorDataTooSmall(),
3123 UnwrapKey(blink::WebCryptoKeyFormatRaw,
3124 CryptoData(small_data),
3125 wrapping_key,
3126 wrapping_algorithm,
3127 key_algorithm,
3128 true,
3129 blink::WebCryptoKeyUsageEncrypt,
3130 &unwrapped_key));
3132 // Unwrap with wrapped data size not a multiple of 8 bytes must fail.
3133 const std::vector<uint8> unaligned_data(test_ciphertext.begin(),
3134 test_ciphertext.end() - 2);
3135 EXPECT_EQ(Status::ErrorInvalidAesKwDataLength(),
3136 UnwrapKey(blink::WebCryptoKeyFormatRaw,
3137 CryptoData(unaligned_data),
3138 wrapping_key,
3139 wrapping_algorithm,
3140 key_algorithm,
3141 true,
3142 blink::WebCryptoKeyUsageEncrypt,
3143 &unwrapped_key));
3146 TEST_F(SharedCryptoTest, MAYBE(AesKwRawSymkeyUnwrapCorruptData)) {
3147 scoped_ptr<base::ListValue> tests;
3148 ASSERT_TRUE(ReadJsonTestFileToList("aes_kw.json", &tests));
3149 base::DictionaryValue* test;
3150 // Use 256 bits of data with a 256-bit KEK
3151 ASSERT_TRUE(tests->GetDictionary(3, &test));
3152 const std::vector<uint8> test_kek = GetBytesFromHexString(test, "kek");
3153 const std::vector<uint8> test_key = GetBytesFromHexString(test, "key");
3154 const std::vector<uint8> test_ciphertext =
3155 GetBytesFromHexString(test, "ciphertext");
3156 const blink::WebCryptoAlgorithm wrapping_algorithm =
3157 webcrypto::CreateAlgorithm(blink::WebCryptoAlgorithmIdAesKw);
3159 // Import the wrapping key.
3160 blink::WebCryptoKey wrapping_key = ImportSecretKeyFromRaw(
3161 test_kek,
3162 wrapping_algorithm,
3163 blink::WebCryptoKeyUsageWrapKey | blink::WebCryptoKeyUsageUnwrapKey);
3165 // Unwrap of a corrupted version of the known ciphertext should fail, due to
3166 // AES-KW's built-in integrity check.
3167 blink::WebCryptoKey unwrapped_key = blink::WebCryptoKey::createNull();
3168 EXPECT_EQ(
3169 Status::OperationError(),
3170 UnwrapKey(blink::WebCryptoKeyFormatRaw,
3171 CryptoData(Corrupted(test_ciphertext)),
3172 wrapping_key,
3173 wrapping_algorithm,
3174 webcrypto::CreateAlgorithm(blink::WebCryptoAlgorithmIdAesCbc),
3175 true,
3176 blink::WebCryptoKeyUsageEncrypt,
3177 &unwrapped_key));
3180 TEST_F(SharedCryptoTest, MAYBE(AesKwJwkSymkeyUnwrapKnownData)) {
3181 // The following data lists a known HMAC SHA-256 key, then a JWK
3182 // representation of this key which was encrypted ("wrapped") using AES-KW and
3183 // the following wrapping key.
3184 // For reference, the intermediate clear JWK is
3185 // {"alg":"HS256","ext":true,"k":<b64urlKey>,"key_ops":["verify"],"kty":"oct"}
3186 // (Not shown is space padding to ensure the cleartext meets the size
3187 // requirements of the AES-KW algorithm.)
3188 const std::vector<uint8> key_data = HexStringToBytes(
3189 "000102030405060708090A0B0C0D0E0F000102030405060708090A0B0C0D0E0F");
3190 const std::vector<uint8> wrapped_key_data = HexStringToBytes(
3191 "14E6380B35FDC5B72E1994764B6CB7BFDD64E7832894356AAEE6C3768FC3D0F115E6B0"
3192 "6729756225F999AA99FDF81FD6A359F1576D3D23DE6CB69C3937054EB497AC1E8C38D5"
3193 "5E01B9783A20C8D930020932CF25926103002213D0FC37279888154FEBCEDF31832158"
3194 "97938C5CFE5B10B4254D0C399F39D0");
3195 const std::vector<uint8> wrapping_key_data =
3196 HexStringToBytes("000102030405060708090A0B0C0D0E0F");
3197 const blink::WebCryptoAlgorithm wrapping_algorithm =
3198 webcrypto::CreateAlgorithm(blink::WebCryptoAlgorithmIdAesKw);
3200 // Import the wrapping key.
3201 blink::WebCryptoKey wrapping_key = ImportSecretKeyFromRaw(
3202 wrapping_key_data, wrapping_algorithm, blink::WebCryptoKeyUsageUnwrapKey);
3204 // Unwrap the known wrapped key data to produce a new key
3205 blink::WebCryptoKey unwrapped_key = blink::WebCryptoKey::createNull();
3206 ASSERT_EQ(
3207 Status::Success(),
3208 UnwrapKey(blink::WebCryptoKeyFormatJwk,
3209 CryptoData(wrapped_key_data),
3210 wrapping_key,
3211 wrapping_algorithm,
3212 CreateHmacImportAlgorithm(blink::WebCryptoAlgorithmIdSha256),
3213 true,
3214 blink::WebCryptoKeyUsageVerify,
3215 &unwrapped_key));
3217 // Validate the new key's attributes.
3218 EXPECT_FALSE(unwrapped_key.isNull());
3219 EXPECT_TRUE(unwrapped_key.handle());
3220 EXPECT_EQ(blink::WebCryptoKeyTypeSecret, unwrapped_key.type());
3221 EXPECT_EQ(blink::WebCryptoAlgorithmIdHmac, unwrapped_key.algorithm().id());
3222 EXPECT_EQ(blink::WebCryptoAlgorithmIdSha256,
3223 unwrapped_key.algorithm().hmacParams()->hash().id());
3224 EXPECT_EQ(256u, unwrapped_key.algorithm().hmacParams()->lengthBits());
3225 EXPECT_EQ(true, unwrapped_key.extractable());
3226 EXPECT_EQ(blink::WebCryptoKeyUsageVerify, unwrapped_key.usages());
3228 // Export the new key's raw data and compare to the known original.
3229 std::vector<uint8> raw_key;
3230 EXPECT_EQ(Status::Success(),
3231 ExportKey(blink::WebCryptoKeyFormatRaw, unwrapped_key, &raw_key));
3232 EXPECT_BYTES_EQ(key_data, raw_key);
3235 // TODO(eroman):
3236 // * Test decryption when the tag length exceeds input size
3237 // * Test decryption with empty input
3238 // * Test decryption with tag length of 0.
3239 TEST_F(SharedCryptoTest, AesGcmSampleSets) {
3240 // Some Linux test runners may not have a new enough version of NSS.
3241 if (!SupportsAesGcm()) {
3242 LOG(WARNING) << "AES GCM not supported, skipping tests";
3243 return;
3246 scoped_ptr<base::ListValue> tests;
3247 ASSERT_TRUE(ReadJsonTestFileToList("aes_gcm.json", &tests));
3249 // Note that WebCrypto appends the authentication tag to the ciphertext.
3250 for (size_t test_index = 0; test_index < tests->GetSize(); ++test_index) {
3251 SCOPED_TRACE(test_index);
3252 base::DictionaryValue* test;
3253 ASSERT_TRUE(tests->GetDictionary(test_index, &test));
3255 const std::vector<uint8> test_key = GetBytesFromHexString(test, "key");
3256 const std::vector<uint8> test_iv = GetBytesFromHexString(test, "iv");
3257 const std::vector<uint8> test_additional_data =
3258 GetBytesFromHexString(test, "additional_data");
3259 const std::vector<uint8> test_plain_text =
3260 GetBytesFromHexString(test, "plain_text");
3261 const std::vector<uint8> test_authentication_tag =
3262 GetBytesFromHexString(test, "authentication_tag");
3263 const unsigned int test_tag_size_bits = test_authentication_tag.size() * 8;
3264 const std::vector<uint8> test_cipher_text =
3265 GetBytesFromHexString(test, "cipher_text");
3267 #if defined(USE_OPENSSL)
3268 // TODO(eroman): Add support for 256-bit keys.
3269 if (test_key.size() == 32) {
3270 LOG(WARNING)
3271 << "OpenSSL doesn't support 256-bit keys for AES-GCM; skipping";
3272 continue;
3274 #endif
3276 blink::WebCryptoKey key = ImportSecretKeyFromRaw(
3277 test_key,
3278 CreateAlgorithm(blink::WebCryptoAlgorithmIdAesGcm),
3279 blink::WebCryptoKeyUsageEncrypt | blink::WebCryptoKeyUsageDecrypt);
3281 // Verify exported raw key is identical to the imported data
3282 std::vector<uint8> raw_key;
3283 EXPECT_EQ(Status::Success(),
3284 ExportKey(blink::WebCryptoKeyFormatRaw, key, &raw_key));
3286 EXPECT_BYTES_EQ(test_key, raw_key);
3288 // Test encryption.
3289 std::vector<uint8> cipher_text;
3290 std::vector<uint8> authentication_tag;
3291 EXPECT_EQ(Status::Success(),
3292 AesGcmEncrypt(key,
3293 test_iv,
3294 test_additional_data,
3295 test_tag_size_bits,
3296 test_plain_text,
3297 &cipher_text,
3298 &authentication_tag));
3300 EXPECT_BYTES_EQ(test_cipher_text, cipher_text);
3301 EXPECT_BYTES_EQ(test_authentication_tag, authentication_tag);
3303 // Test decryption.
3304 std::vector<uint8> plain_text;
3305 EXPECT_EQ(Status::Success(),
3306 AesGcmDecrypt(key,
3307 test_iv,
3308 test_additional_data,
3309 test_tag_size_bits,
3310 test_cipher_text,
3311 test_authentication_tag,
3312 &plain_text));
3313 EXPECT_BYTES_EQ(test_plain_text, plain_text);
3315 // Decryption should fail if any of the inputs are tampered with.
3316 EXPECT_EQ(Status::OperationError(),
3317 AesGcmDecrypt(key,
3318 Corrupted(test_iv),
3319 test_additional_data,
3320 test_tag_size_bits,
3321 test_cipher_text,
3322 test_authentication_tag,
3323 &plain_text));
3324 EXPECT_EQ(Status::OperationError(),
3325 AesGcmDecrypt(key,
3326 test_iv,
3327 Corrupted(test_additional_data),
3328 test_tag_size_bits,
3329 test_cipher_text,
3330 test_authentication_tag,
3331 &plain_text));
3332 EXPECT_EQ(Status::OperationError(),
3333 AesGcmDecrypt(key,
3334 test_iv,
3335 test_additional_data,
3336 test_tag_size_bits,
3337 Corrupted(test_cipher_text),
3338 test_authentication_tag,
3339 &plain_text));
3340 EXPECT_EQ(Status::OperationError(),
3341 AesGcmDecrypt(key,
3342 test_iv,
3343 test_additional_data,
3344 test_tag_size_bits,
3345 test_cipher_text,
3346 Corrupted(test_authentication_tag),
3347 &plain_text));
3349 // Try different incorrect tag lengths
3350 uint8 kAlternateTagLengths[] = {0, 8, 96, 120, 128, 160, 255};
3351 for (size_t tag_i = 0; tag_i < arraysize(kAlternateTagLengths); ++tag_i) {
3352 unsigned int wrong_tag_size_bits = kAlternateTagLengths[tag_i];
3353 if (test_tag_size_bits == wrong_tag_size_bits)
3354 continue;
3355 EXPECT_NE(Status::Success(),
3356 AesGcmDecrypt(key,
3357 test_iv,
3358 test_additional_data,
3359 wrong_tag_size_bits,
3360 test_cipher_text,
3361 test_authentication_tag,
3362 &plain_text));
3367 // AES 192-bit is not allowed: http://crbug.com/381829
3368 TEST_F(SharedCryptoTest, MAYBE(ImportAesCbc192Raw)) {
3369 std::vector<uint8> key_raw(24, 0);
3370 blink::WebCryptoKey key = blink::WebCryptoKey::createNull();
3371 Status status = ImportKey(blink::WebCryptoKeyFormatRaw,
3372 CryptoData(key_raw),
3373 CreateAlgorithm(blink::WebCryptoAlgorithmIdAesCbc),
3374 true,
3375 blink::WebCryptoKeyUsageEncrypt,
3376 &key);
3377 ASSERT_EQ(Status::ErrorAes192BitUnsupported(), status);
3380 // AES 192-bit is not allowed: http://crbug.com/381829
3381 TEST_F(SharedCryptoTest, MAYBE(ImportAesCbc192Jwk)) {
3382 blink::WebCryptoKey key = blink::WebCryptoKey::createNull();
3384 base::DictionaryValue dict;
3385 dict.SetString("kty", "oct");
3386 dict.SetString("alg", "A192CBC");
3387 dict.SetString("k", "YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFh");
3389 EXPECT_EQ(
3390 Status::ErrorAes192BitUnsupported(),
3391 ImportKeyJwkFromDict(dict,
3392 CreateAlgorithm(blink::WebCryptoAlgorithmIdAesCbc),
3393 false,
3394 blink::WebCryptoKeyUsageEncrypt,
3395 &key));
3398 // AES 192-bit is not allowed: http://crbug.com/381829
3399 TEST_F(SharedCryptoTest, MAYBE(GenerateAesCbc192)) {
3400 blink::WebCryptoKey key = blink::WebCryptoKey::createNull();
3401 Status status = GenerateSecretKey(CreateAesCbcKeyGenAlgorithm(192),
3402 true,
3403 blink::WebCryptoKeyUsageEncrypt,
3404 &key);
3405 ASSERT_EQ(Status::ErrorAes192BitUnsupported(), status);
3408 // AES 192-bit is not allowed: http://crbug.com/381829
3409 TEST_F(SharedCryptoTest, MAYBE(UnwrapAesCbc192)) {
3410 std::vector<uint8> wrapping_key_data(16, 0);
3411 std::vector<uint8> wrapped_key = HexStringToBytes(
3412 "1A07ACAB6C906E50883173C29441DB1DE91D34F45C435B5F99C822867FB3956F");
3414 blink::WebCryptoKey wrapping_key =
3415 ImportSecretKeyFromRaw(wrapping_key_data,
3416 CreateAlgorithm(blink::WebCryptoAlgorithmIdAesKw),
3417 blink::WebCryptoKeyUsageUnwrapKey);
3419 blink::WebCryptoKey unwrapped_key = blink::WebCryptoKey::createNull();
3420 ASSERT_EQ(Status::ErrorAes192BitUnsupported(),
3421 UnwrapKey(blink::WebCryptoKeyFormatRaw,
3422 CryptoData(wrapped_key),
3423 wrapping_key,
3424 CreateAlgorithm(blink::WebCryptoAlgorithmIdAesKw),
3425 CreateAlgorithm(blink::WebCryptoAlgorithmIdAesCbc),
3426 true,
3427 blink::WebCryptoKeyUsageEncrypt,
3428 &unwrapped_key));
3431 class SharedCryptoRsaOaepTest : public ::testing::Test {
3432 public:
3433 SharedCryptoRsaOaepTest() { Init(); }
3435 scoped_ptr<base::DictionaryValue> CreatePublicKeyJwkDict() {
3436 scoped_ptr<base::DictionaryValue> jwk(new base::DictionaryValue());
3437 jwk->SetString("kty", "RSA");
3438 jwk->SetString("n",
3439 Base64EncodeUrlSafe(HexStringToBytes(kPublicKeyModulusHex)));
3440 jwk->SetString(
3441 "e", Base64EncodeUrlSafe(HexStringToBytes(kPublicKeyExponentHex)));
3442 return jwk.Pass();
3446 // Import a PKCS#8 private key that uses RSAPrivateKey with the
3447 // id-rsaEncryption OID.
3448 TEST_F(SharedCryptoRsaOaepTest, ImportPkcs8WithRsaEncryption) {
3449 if (!SupportsRsaOaep()) {
3450 LOG(WARNING) << "RSA-OAEP support not present; skipping.";
3451 return;
3454 blink::WebCryptoKey private_key = blink::WebCryptoKey::createNull();
3455 ASSERT_EQ(Status::Success(),
3456 ImportKey(blink::WebCryptoKeyFormatPkcs8,
3457 CryptoData(HexStringToBytes(kPrivateKeyPkcs8DerHex)),
3458 CreateRsaHashedImportAlgorithm(
3459 blink::WebCryptoAlgorithmIdRsaOaep,
3460 blink::WebCryptoAlgorithmIdSha1),
3461 true,
3462 blink::WebCryptoKeyUsageDecrypt,
3463 &private_key));
3466 TEST_F(SharedCryptoRsaOaepTest, ImportPublicJwkWithNoAlg) {
3467 if (!SupportsRsaOaep()) {
3468 LOG(WARNING) << "RSA-OAEP support not present; skipping.";
3469 return;
3472 scoped_ptr<base::DictionaryValue> jwk(CreatePublicKeyJwkDict());
3474 blink::WebCryptoKey public_key = blink::WebCryptoKey::createNull();
3475 ASSERT_EQ(Status::Success(),
3476 ImportKeyJwkFromDict(*jwk.get(),
3477 CreateRsaHashedImportAlgorithm(
3478 blink::WebCryptoAlgorithmIdRsaOaep,
3479 blink::WebCryptoAlgorithmIdSha1),
3480 true,
3481 blink::WebCryptoKeyUsageEncrypt,
3482 &public_key));
3485 TEST_F(SharedCryptoRsaOaepTest, ImportPublicJwkWithMatchingAlg) {
3486 if (!SupportsRsaOaep()) {
3487 LOG(WARNING) << "RSA-OAEP support not present; skipping.";
3488 return;
3491 scoped_ptr<base::DictionaryValue> jwk(CreatePublicKeyJwkDict());
3492 jwk->SetString("alg", "RSA-OAEP");
3494 blink::WebCryptoKey public_key = blink::WebCryptoKey::createNull();
3495 ASSERT_EQ(Status::Success(),
3496 ImportKeyJwkFromDict(*jwk.get(),
3497 CreateRsaHashedImportAlgorithm(
3498 blink::WebCryptoAlgorithmIdRsaOaep,
3499 blink::WebCryptoAlgorithmIdSha1),
3500 true,
3501 blink::WebCryptoKeyUsageEncrypt,
3502 &public_key));
3505 TEST_F(SharedCryptoRsaOaepTest, ImportPublicJwkWithMismatchedAlgFails) {
3506 if (!SupportsRsaOaep()) {
3507 LOG(WARNING) << "RSA-OAEP support not present; skipping.";
3508 return;
3511 scoped_ptr<base::DictionaryValue> jwk(CreatePublicKeyJwkDict());
3512 jwk->SetString("alg", "RSA-OAEP-512");
3514 blink::WebCryptoKey public_key = blink::WebCryptoKey::createNull();
3515 ASSERT_EQ(Status::ErrorJwkAlgorithmInconsistent(),
3516 ImportKeyJwkFromDict(*jwk.get(),
3517 CreateRsaHashedImportAlgorithm(
3518 blink::WebCryptoAlgorithmIdRsaOaep,
3519 blink::WebCryptoAlgorithmIdSha1),
3520 true,
3521 blink::WebCryptoKeyUsageEncrypt,
3522 &public_key));
3525 TEST_F(SharedCryptoRsaOaepTest, ImportPublicJwkWithMismatchedTypeFails) {
3526 if (!SupportsRsaOaep()) {
3527 LOG(WARNING) << "RSA-OAEP support not present; skipping.";
3528 return;
3531 scoped_ptr<base::DictionaryValue> jwk(CreatePublicKeyJwkDict());
3532 jwk->SetString("kty", "oct");
3533 jwk->SetString("alg", "RSA-OAEP");
3535 blink::WebCryptoKey public_key = blink::WebCryptoKey::createNull();
3536 ASSERT_EQ(Status::ErrorJwkPropertyMissing("k"),
3537 ImportKeyJwkFromDict(*jwk.get(),
3538 CreateRsaHashedImportAlgorithm(
3539 blink::WebCryptoAlgorithmIdRsaOaep,
3540 blink::WebCryptoAlgorithmIdSha1),
3541 true,
3542 blink::WebCryptoKeyUsageEncrypt,
3543 &public_key));
3546 TEST_F(SharedCryptoRsaOaepTest, ExportPublicJwk) {
3547 if (!SupportsRsaOaep()) {
3548 LOG(WARNING) << "RSA-OAEP support not present; skipping.";
3549 return;
3552 struct TestData {
3553 blink::WebCryptoAlgorithmId hash_alg;
3554 const char* expected_jwk_alg;
3555 } kTestData[] = {{blink::WebCryptoAlgorithmIdSha1, "RSA-OAEP"},
3556 {blink::WebCryptoAlgorithmIdSha256, "RSA-OAEP-256"},
3557 {blink::WebCryptoAlgorithmIdSha384, "RSA-OAEP-384"},
3558 {blink::WebCryptoAlgorithmIdSha512, "RSA-OAEP-512"}};
3559 for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kTestData); ++i) {
3560 const TestData& test_data = kTestData[i];
3561 SCOPED_TRACE(test_data.expected_jwk_alg);
3563 scoped_ptr<base::DictionaryValue> jwk(CreatePublicKeyJwkDict());
3564 jwk->SetString("alg", test_data.expected_jwk_alg);
3566 // Import the key in a known-good format
3567 blink::WebCryptoKey public_key = blink::WebCryptoKey::createNull();
3568 ASSERT_EQ(Status::Success(),
3569 ImportKeyJwkFromDict(
3570 *jwk.get(),
3571 CreateRsaHashedImportAlgorithm(
3572 blink::WebCryptoAlgorithmIdRsaOaep, test_data.hash_alg),
3573 true,
3574 blink::WebCryptoKeyUsageEncrypt,
3575 &public_key));
3577 // Now export the key as JWK and verify its contents
3578 std::vector<uint8> jwk_data;
3579 ASSERT_EQ(Status::Success(),
3580 ExportKey(blink::WebCryptoKeyFormatJwk, public_key, &jwk_data));
3581 EXPECT_TRUE(VerifyPublicJwk(jwk_data,
3582 test_data.expected_jwk_alg,
3583 kPublicKeyModulusHex,
3584 kPublicKeyExponentHex,
3585 blink::WebCryptoKeyUsageEncrypt));
3589 TEST_F(SharedCryptoRsaOaepTest, EncryptDecryptKnownAnswerTest) {
3590 if (!SupportsRsaOaep()) {
3591 LOG(WARNING) << "RSA-OAEP support not present; skipping.";
3592 return;
3595 scoped_ptr<base::ListValue> tests;
3596 ASSERT_TRUE(ReadJsonTestFileToList("rsa_oaep.json", &tests));
3598 for (size_t test_index = 0; test_index < tests->GetSize(); ++test_index) {
3599 SCOPED_TRACE(test_index);
3601 base::DictionaryValue* test = NULL;
3602 ASSERT_TRUE(tests->GetDictionary(test_index, &test));
3604 blink::WebCryptoAlgorithm digest_algorithm =
3605 GetDigestAlgorithm(test, "hash");
3606 ASSERT_FALSE(digest_algorithm.isNull());
3607 std::vector<uint8> public_key_der =
3608 GetBytesFromHexString(test, "public_key");
3609 std::vector<uint8> private_key_der =
3610 GetBytesFromHexString(test, "private_key");
3611 std::vector<uint8> ciphertext = GetBytesFromHexString(test, "ciphertext");
3612 std::vector<uint8> plaintext = GetBytesFromHexString(test, "plaintext");
3613 std::vector<uint8> label = GetBytesFromHexString(test, "label");
3615 blink::WebCryptoAlgorithm import_algorithm = CreateRsaHashedImportAlgorithm(
3616 blink::WebCryptoAlgorithmIdRsaOaep, digest_algorithm.id());
3617 blink::WebCryptoKey public_key = blink::WebCryptoKey::createNull();
3618 blink::WebCryptoKey private_key = blink::WebCryptoKey::createNull();
3620 ASSERT_NO_FATAL_FAILURE(ImportRsaKeyPair(public_key_der,
3621 private_key_der,
3622 import_algorithm,
3623 false,
3624 blink::WebCryptoKeyUsageEncrypt,
3625 blink::WebCryptoKeyUsageDecrypt,
3626 &public_key,
3627 &private_key));
3629 blink::WebCryptoAlgorithm op_algorithm = CreateRsaOaepAlgorithm(label);
3630 std::vector<uint8> decrypted_data;
3631 ASSERT_EQ(Status::Success(),
3632 Decrypt(op_algorithm,
3633 private_key,
3634 CryptoData(ciphertext),
3635 &decrypted_data));
3636 EXPECT_BYTES_EQ(plaintext, decrypted_data);
3637 std::vector<uint8> encrypted_data;
3638 ASSERT_EQ(
3639 Status::Success(),
3640 Encrypt(
3641 op_algorithm, public_key, CryptoData(plaintext), &encrypted_data));
3642 std::vector<uint8> redecrypted_data;
3643 ASSERT_EQ(Status::Success(),
3644 Decrypt(op_algorithm,
3645 private_key,
3646 CryptoData(encrypted_data),
3647 &redecrypted_data));
3648 EXPECT_BYTES_EQ(plaintext, redecrypted_data);
3652 TEST_F(SharedCryptoRsaOaepTest, EncryptWithLargeMessageFails) {
3653 if (!SupportsRsaOaep()) {
3654 LOG(WARNING) << "RSA-OAEP support not present; skipping.";
3655 return;
3658 const blink::WebCryptoAlgorithmId kHash = blink::WebCryptoAlgorithmIdSha1;
3659 const size_t kHashSize = 20;
3661 scoped_ptr<base::DictionaryValue> jwk(CreatePublicKeyJwkDict());
3663 blink::WebCryptoKey public_key = blink::WebCryptoKey::createNull();
3664 ASSERT_EQ(Status::Success(),
3665 ImportKeyJwkFromDict(*jwk.get(),
3666 CreateRsaHashedImportAlgorithm(
3667 blink::WebCryptoAlgorithmIdRsaOaep, kHash),
3668 true,
3669 blink::WebCryptoKeyUsageEncrypt,
3670 &public_key));
3672 // The maximum size of an encrypted message is:
3673 // modulus length
3674 // - 1 (leading octet)
3675 // - hash size (maskedSeed)
3676 // - hash size (lHash portion of maskedDB)
3677 // - 1 (at least one octet for the padding string)
3678 size_t kMaxMessageSize = (kModulusLengthBits / 8) - 2 - (2 * kHashSize);
3680 // The label has no influence on the maximum message size. For simplicity,
3681 // use the empty string.
3682 std::vector<uint8> label;
3683 blink::WebCryptoAlgorithm op_algorithm = CreateRsaOaepAlgorithm(label);
3685 // Test that a message just before the boundary succeeds.
3686 std::string large_message;
3687 large_message.resize(kMaxMessageSize - 1, 'A');
3689 std::vector<uint8> ciphertext;
3690 ASSERT_EQ(
3691 Status::Success(),
3692 Encrypt(
3693 op_algorithm, public_key, CryptoData(large_message), &ciphertext));
3695 // Test that a message at the boundary succeeds.
3696 large_message.resize(kMaxMessageSize, 'A');
3697 ciphertext.clear();
3699 ASSERT_EQ(
3700 Status::Success(),
3701 Encrypt(
3702 op_algorithm, public_key, CryptoData(large_message), &ciphertext));
3704 // Test that a message greater than the largest size fails.
3705 large_message.resize(kMaxMessageSize + 1, 'A');
3706 ciphertext.clear();
3708 ASSERT_EQ(
3709 Status::OperationError(),
3710 Encrypt(
3711 op_algorithm, public_key, CryptoData(large_message), &ciphertext));
3714 // Ensures that if the selected hash algorithm for the RSA-OAEP message is too
3715 // large, then it is rejected, independent of the actual message to be
3716 // encrypted.
3717 // For example, a 1024-bit RSA key is too small to accomodate a message that
3718 // uses OAEP with SHA-512, since it requires 1040 bits to encode
3719 // (2 * hash size + 2 padding bytes).
3720 TEST_F(SharedCryptoRsaOaepTest, EncryptWithLargeDigestFails) {
3721 if (!SupportsRsaOaep()) {
3722 LOG(WARNING) << "RSA-OAEP support not present; skipping.";
3723 return;
3726 const blink::WebCryptoAlgorithmId kHash = blink::WebCryptoAlgorithmIdSha512;
3728 scoped_ptr<base::DictionaryValue> jwk(CreatePublicKeyJwkDict());
3730 blink::WebCryptoKey public_key = blink::WebCryptoKey::createNull();
3731 ASSERT_EQ(Status::Success(),
3732 ImportKeyJwkFromDict(*jwk.get(),
3733 CreateRsaHashedImportAlgorithm(
3734 blink::WebCryptoAlgorithmIdRsaOaep, kHash),
3735 true,
3736 blink::WebCryptoKeyUsageEncrypt,
3737 &public_key));
3739 // The label has no influence on the maximum message size. For simplicity,
3740 // use the empty string.
3741 std::vector<uint8> label;
3742 blink::WebCryptoAlgorithm op_algorithm = CreateRsaOaepAlgorithm(label);
3744 std::string small_message("A");
3745 std::vector<uint8> ciphertext;
3746 // This is an operation error, as the internal consistency checking of the
3747 // algorithm parameters is up to the implementation.
3748 ASSERT_EQ(
3749 Status::OperationError(),
3750 Encrypt(
3751 op_algorithm, public_key, CryptoData(small_message), &ciphertext));
3754 TEST_F(SharedCryptoRsaOaepTest, DecryptWithLargeMessageFails) {
3755 if (!SupportsRsaOaep()) {
3756 LOG(WARNING) << "RSA-OAEP support not present; skipping.";
3757 return;
3760 blink::WebCryptoKey private_key = blink::WebCryptoKey::createNull();
3761 ASSERT_EQ(Status::Success(),
3762 ImportKey(blink::WebCryptoKeyFormatPkcs8,
3763 CryptoData(HexStringToBytes(kPrivateKeyPkcs8DerHex)),
3764 CreateRsaHashedImportAlgorithm(
3765 blink::WebCryptoAlgorithmIdRsaOaep,
3766 blink::WebCryptoAlgorithmIdSha1),
3767 true,
3768 blink::WebCryptoKeyUsageDecrypt,
3769 &private_key));
3771 // The label has no influence on the maximum message size. For simplicity,
3772 // use the empty string.
3773 std::vector<uint8> label;
3774 blink::WebCryptoAlgorithm op_algorithm = CreateRsaOaepAlgorithm(label);
3776 std::string large_dummy_message(kModulusLengthBits / 8, 'A');
3777 std::vector<uint8> plaintext;
3779 ASSERT_EQ(Status::OperationError(),
3780 Decrypt(op_algorithm,
3781 private_key,
3782 CryptoData(large_dummy_message),
3783 &plaintext));
3786 TEST_F(SharedCryptoRsaOaepTest, WrapUnwrapRawKey) {
3787 if (!SupportsRsaOaep()) {
3788 LOG(WARNING) << "RSA-OAEP support not present; skipping.";
3789 return;
3792 blink::WebCryptoAlgorithm import_algorithm = CreateRsaHashedImportAlgorithm(
3793 blink::WebCryptoAlgorithmIdRsaOaep, blink::WebCryptoAlgorithmIdSha1);
3794 blink::WebCryptoKey public_key = blink::WebCryptoKey::createNull();
3795 blink::WebCryptoKey private_key = blink::WebCryptoKey::createNull();
3797 ASSERT_NO_FATAL_FAILURE(ImportRsaKeyPair(
3798 HexStringToBytes(kPublicKeySpkiDerHex),
3799 HexStringToBytes(kPrivateKeyPkcs8DerHex),
3800 import_algorithm,
3801 false,
3802 blink::WebCryptoKeyUsageEncrypt | blink::WebCryptoKeyUsageWrapKey,
3803 blink::WebCryptoKeyUsageDecrypt | blink::WebCryptoKeyUsageUnwrapKey,
3804 &public_key,
3805 &private_key));
3807 std::vector<uint8> label;
3808 blink::WebCryptoAlgorithm wrapping_algorithm = CreateRsaOaepAlgorithm(label);
3810 const std::string key_hex = "000102030405060708090A0B0C0D0E0F";
3811 const blink::WebCryptoAlgorithm key_algorithm =
3812 webcrypto::CreateAlgorithm(blink::WebCryptoAlgorithmIdAesCbc);
3814 blink::WebCryptoKey key =
3815 ImportSecretKeyFromRaw(HexStringToBytes(key_hex),
3816 key_algorithm,
3817 blink::WebCryptoKeyUsageEncrypt);
3818 ASSERT_FALSE(key.isNull());
3820 std::vector<uint8> wrapped_key;
3821 ASSERT_EQ(Status::Success(),
3822 WrapKey(blink::WebCryptoKeyFormatRaw,
3823 key,
3824 public_key,
3825 wrapping_algorithm,
3826 &wrapped_key));
3828 // Verify that |wrapped_key| can be decrypted and yields the key data.
3829 // Because |private_key| supports both decrypt and unwrap, this is valid.
3830 std::vector<uint8> decrypted_key;
3831 ASSERT_EQ(Status::Success(),
3832 Decrypt(wrapping_algorithm,
3833 private_key,
3834 CryptoData(wrapped_key),
3835 &decrypted_key));
3836 EXPECT_BYTES_EQ_HEX(key_hex, decrypted_key);
3838 // Now attempt to unwrap the key, which should also decrypt the data.
3839 blink::WebCryptoKey unwrapped_key = blink::WebCryptoKey::createNull();
3840 ASSERT_EQ(Status::Success(),
3841 UnwrapKey(blink::WebCryptoKeyFormatRaw,
3842 CryptoData(wrapped_key),
3843 private_key,
3844 wrapping_algorithm,
3845 key_algorithm,
3846 true,
3847 blink::WebCryptoKeyUsageEncrypt,
3848 &unwrapped_key));
3849 ASSERT_FALSE(unwrapped_key.isNull());
3851 std::vector<uint8> raw_key;
3852 ASSERT_EQ(Status::Success(),
3853 ExportKey(blink::WebCryptoKeyFormatRaw, unwrapped_key, &raw_key));
3854 EXPECT_BYTES_EQ_HEX(key_hex, raw_key);
3857 TEST_F(SharedCryptoRsaOaepTest, WrapUnwrapJwkSymKey) {
3858 if (!SupportsRsaOaep()) {
3859 LOG(WARNING) << "RSA-OAEP support not present; skipping.";
3860 return;
3863 // The public and private portions of a 2048-bit RSA key with the
3864 // id-rsaEncryption OID
3865 const char kPublicKey2048SpkiDerHex[] =
3866 "30820122300d06092a864886f70d01010105000382010f003082010a0282010100c5d8ce"
3867 "137a38168c8ab70229cfa5accc640567159750a312ce2e7d54b6e2fdd59b300c6a6c9764"
3868 "f8de6f00519cdb90111453d273a967462786480621f9e7cee5b73d63358448e7183a3a68"
3869 "e991186359f26aa88fbca5f53e673e502e4c5a2ba5068aeba60c9d0c44d872458d1b1e2f"
3870 "7f339f986076d516e93dc750f0b7680b6f5f02bc0d5590495be04c4ae59d34ba17bc5d08"
3871 "a93c75cfda2828f4a55b153af912038438276cb4a14f8116ca94db0ea9893652d02fc606"
3872 "36f19975e3d79a4d8ea8bfed6f8e0a24b63d243b08ea70a086ad56dd6341d733711c89ca"
3873 "749d4a80b3e6ecd2f8e53731eadeac2ea77788ee55d7b4b47c0f2523fbd61b557c16615d"
3874 "5d0203010001";
3875 const char kPrivateKey2048Pkcs8DerHex[] =
3876 "308204bd020100300d06092a864886f70d0101010500048204a7308204a3020100028201"
3877 "0100c5d8ce137a38168c8ab70229cfa5accc640567159750a312ce2e7d54b6e2fdd59b30"
3878 "0c6a6c9764f8de6f00519cdb90111453d273a967462786480621f9e7cee5b73d63358448"
3879 "e7183a3a68e991186359f26aa88fbca5f53e673e502e4c5a2ba5068aeba60c9d0c44d872"
3880 "458d1b1e2f7f339f986076d516e93dc750f0b7680b6f5f02bc0d5590495be04c4ae59d34"
3881 "ba17bc5d08a93c75cfda2828f4a55b153af912038438276cb4a14f8116ca94db0ea98936"
3882 "52d02fc60636f19975e3d79a4d8ea8bfed6f8e0a24b63d243b08ea70a086ad56dd6341d7"
3883 "33711c89ca749d4a80b3e6ecd2f8e53731eadeac2ea77788ee55d7b4b47c0f2523fbd61b"
3884 "557c16615d5d02030100010282010074b70feb41a0b0fcbc207670400556c9450042ede3"
3885 "d4383fb1ce8f3558a6d4641d26dd4c333fa4db842d2b9cf9d2354d3e16ad027a9f682d8c"
3886 "f4145a1ad97b9edcd8a41c402bd9d8db10f62f43df854cdccbbb2100834f083f53ed6d42"
3887 "b1b729a59072b004a4e945fc027db15e9c121d1251464d320d4774d5732df6b3dbf751f4"
3888 "9b19c9db201e19989c883bbaad5333db47f64f6f7a95b8d4936b10d945aa3f794cfaab62"
3889 "e7d47686129358914f3b8085f03698a650ab5b8c7e45813f2b0515ec05b6e5195b6a7c2a"
3890 "0d36969745f431ded4fd059f6aa361a4649541016d356297362b778e90f077d48815b339"
3891 "ec6f43aba345df93e67fcb6c2cb5b4544e9be902818100e9c90abe5f9f32468c5b6d630c"
3892 "54a4d7d75e29a72cf792f21e242aac78fd7995c42dfd4ae871d2619ff7096cb05baa78e3"
3893 "23ecab338401a8059adf7a0d8be3b21edc9a9c82c5605634a2ec81ec053271721351868a"
3894 "4c2e50c689d7cef94e31ff23658af5843366e2b289c5bf81d72756a7b93487dd8770d69c"
3895 "1f4e089d6d89f302818100d8a58a727c4e209132afd9933b98c89aca862a01cc0be74133"
3896 "bee517909e5c379e526895ac4af11780c1fe91194c777c9670b6423f0f5a32fd7691a622"
3897 "113eef4bed2ef863363a335fd55b0e75088c582437237d7f3ed3f0a643950237bc6e6277"
3898 "ccd0d0a1b4170aa1047aa7ffa7c8c54be10e8c7327ae2e0885663963817f6f02818100e5"
3899 "aed9ba4d71b7502e6748a1ce247ecb7bd10c352d6d9256031cdf3c11a65e44b0b7ca2945"
3900 "134671195af84c6b3bb3d10ebf65ae916f38bd5dbc59a0ad1c69b8beaf57cb3a8335f19b"
3901 "c7117b576987b48331cd9fd3d1a293436b7bb5e1a35c6560de4b5688ea834367cb0997eb"
3902 "b578f59ed4cb724c47dba94d3b484c1876dcd70281807f15bc7d2406007cac2b138a96af"
3903 "2d1e00276b84da593132c253fcb73212732dfd25824c2a615bc3d9b7f2c8d2fa542d3562"
3904 "b0c7738e61eeff580a6056239fb367ea9e5efe73d4f846033602e90c36a78db6fa8ea792"
3905 "0769675ec58e237bd994d189c8045a96f5dd3a4f12547257ce224e3c9af830a4da3c0eab"
3906 "9227a0035ae9028180067caea877e0b23090fc689322b71fbcce63d6596e66ab5fcdbaa0"
3907 "0d49e93aba8effb4518c2da637f209028401a68f344865b4956b032c69acde51d29177ca"
3908 "3db99fdbf5e74848ed4fa7bdfc2ebb60e2aaa5354770a763e1399ab7a2099762d525fea0"
3909 "37f3e1972c45a477e66db95c9609bb27f862700ef93379930786cf751b";
3910 blink::WebCryptoAlgorithm import_algorithm = CreateRsaHashedImportAlgorithm(
3911 blink::WebCryptoAlgorithmIdRsaOaep, blink::WebCryptoAlgorithmIdSha1);
3912 blink::WebCryptoKey public_key = blink::WebCryptoKey::createNull();
3913 blink::WebCryptoKey private_key = blink::WebCryptoKey::createNull();
3915 ASSERT_NO_FATAL_FAILURE(ImportRsaKeyPair(
3916 HexStringToBytes(kPublicKey2048SpkiDerHex),
3917 HexStringToBytes(kPrivateKey2048Pkcs8DerHex),
3918 import_algorithm,
3919 false,
3920 blink::WebCryptoKeyUsageEncrypt | blink::WebCryptoKeyUsageWrapKey,
3921 blink::WebCryptoKeyUsageDecrypt | blink::WebCryptoKeyUsageUnwrapKey,
3922 &public_key,
3923 &private_key));
3925 std::vector<uint8> label;
3926 blink::WebCryptoAlgorithm wrapping_algorithm = CreateRsaOaepAlgorithm(label);
3928 const std::string key_hex = "000102030405060708090a0b0c0d0e0f";
3929 const blink::WebCryptoAlgorithm key_algorithm =
3930 webcrypto::CreateAlgorithm(blink::WebCryptoAlgorithmIdAesCbc);
3932 blink::WebCryptoKey key =
3933 ImportSecretKeyFromRaw(HexStringToBytes(key_hex),
3934 key_algorithm,
3935 blink::WebCryptoKeyUsageEncrypt);
3936 ASSERT_FALSE(key.isNull());
3938 std::vector<uint8> wrapped_key;
3939 ASSERT_EQ(Status::Success(),
3940 WrapKey(blink::WebCryptoKeyFormatJwk,
3941 key,
3942 public_key,
3943 wrapping_algorithm,
3944 &wrapped_key));
3946 // Verify that |wrapped_key| can be decrypted and yields a valid JWK object.
3947 // Because |private_key| supports both decrypt and unwrap, this is valid.
3948 std::vector<uint8> decrypted_jwk;
3949 ASSERT_EQ(Status::Success(),
3950 Decrypt(wrapping_algorithm,
3951 private_key,
3952 CryptoData(wrapped_key),
3953 &decrypted_jwk));
3954 EXPECT_TRUE(VerifySecretJwk(
3955 decrypted_jwk, "A128CBC", key_hex, blink::WebCryptoKeyUsageEncrypt));
3957 // Now attempt to unwrap the key, which should also decrypt the data.
3958 blink::WebCryptoKey unwrapped_key = blink::WebCryptoKey::createNull();
3959 ASSERT_EQ(Status::Success(),
3960 UnwrapKey(blink::WebCryptoKeyFormatJwk,
3961 CryptoData(wrapped_key),
3962 private_key,
3963 wrapping_algorithm,
3964 key_algorithm,
3965 true,
3966 blink::WebCryptoKeyUsageEncrypt,
3967 &unwrapped_key));
3968 ASSERT_FALSE(unwrapped_key.isNull());
3970 std::vector<uint8> raw_key;
3971 ASSERT_EQ(Status::Success(),
3972 ExportKey(blink::WebCryptoKeyFormatRaw, unwrapped_key, &raw_key));
3973 EXPECT_BYTES_EQ_HEX(key_hex, raw_key);
3976 // Try importing an RSA-SSA public key with unsupported key usages using SPKI
3977 // format. RSA-SSA public keys only support the 'verify' usage.
3978 TEST_F(SharedCryptoTest, MAYBE(ImportRsaSsaPublicKeyBadUsage_SPKI)) {
3979 const blink::WebCryptoAlgorithm algorithm =
3980 CreateRsaHashedImportAlgorithm(blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
3981 blink::WebCryptoAlgorithmIdSha256);
3983 blink::WebCryptoKeyUsageMask bad_usages[] = {
3984 blink::WebCryptoKeyUsageSign,
3985 blink::WebCryptoKeyUsageSign | blink::WebCryptoKeyUsageVerify,
3986 blink::WebCryptoKeyUsageEncrypt,
3987 blink::WebCryptoKeyUsageEncrypt | blink::WebCryptoKeyUsageDecrypt,
3990 for (size_t i = 0; i < arraysize(bad_usages); ++i) {
3991 SCOPED_TRACE(i);
3993 blink::WebCryptoKey public_key = blink::WebCryptoKey::createNull();
3994 ASSERT_EQ(Status::ErrorCreateKeyBadUsages(),
3995 ImportKey(blink::WebCryptoKeyFormatSpki,
3996 CryptoData(HexStringToBytes(kPublicKeySpkiDerHex)),
3997 algorithm,
3998 false,
3999 bad_usages[i],
4000 &public_key));
4004 // Try importing an RSA-SSA public key with unsupported key usages using JWK
4005 // format. RSA-SSA public keys only support the 'verify' usage.
4006 TEST_F(SharedCryptoTest, MAYBE(ImportRsaSsaPublicKeyBadUsage_JWK)) {
4007 const blink::WebCryptoAlgorithm algorithm =
4008 CreateRsaHashedImportAlgorithm(blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
4009 blink::WebCryptoAlgorithmIdSha256);
4011 blink::WebCryptoKeyUsageMask bad_usages[] = {
4012 blink::WebCryptoKeyUsageSign,
4013 blink::WebCryptoKeyUsageSign | blink::WebCryptoKeyUsageVerify,
4014 blink::WebCryptoKeyUsageEncrypt,
4015 blink::WebCryptoKeyUsageEncrypt | blink::WebCryptoKeyUsageDecrypt,
4018 base::DictionaryValue dict;
4019 RestoreJwkRsaDictionary(&dict);
4020 dict.Remove("use", NULL);
4021 dict.SetString("alg", "RS256");
4023 for (size_t i = 0; i < arraysize(bad_usages); ++i) {
4024 SCOPED_TRACE(i);
4026 blink::WebCryptoKey public_key = blink::WebCryptoKey::createNull();
4027 ASSERT_EQ(Status::ErrorCreateKeyBadUsages(),
4028 ImportKeyJwkFromDict(
4029 dict, algorithm, false, bad_usages[i], &public_key));
4033 // Try importing an AES-CBC key with unsupported key usages using raw
4034 // format. AES-CBC keys support the following usages:
4035 // 'encrypt', 'decrypt', 'wrapKey', 'unwrapKey'
4036 TEST_F(SharedCryptoTest, MAYBE(ImportAesCbcKeyBadUsage_Raw)) {
4037 const blink::WebCryptoAlgorithm algorithm =
4038 CreateAlgorithm(blink::WebCryptoAlgorithmIdAesCbc);
4040 blink::WebCryptoKeyUsageMask bad_usages[] = {
4041 blink::WebCryptoKeyUsageSign,
4042 blink::WebCryptoKeyUsageSign | blink::WebCryptoKeyUsageDecrypt,
4043 blink::WebCryptoKeyUsageDeriveBits,
4044 blink::WebCryptoKeyUsageUnwrapKey | blink::WebCryptoKeyUsageVerify,
4047 std::vector<uint8> key_bytes(16);
4049 for (size_t i = 0; i < arraysize(bad_usages); ++i) {
4050 SCOPED_TRACE(i);
4052 blink::WebCryptoKey key = blink::WebCryptoKey::createNull();
4053 ASSERT_EQ(Status::ErrorCreateKeyBadUsages(),
4054 ImportKey(blink::WebCryptoKeyFormatRaw,
4055 CryptoData(key_bytes),
4056 algorithm,
4057 true,
4058 bad_usages[i],
4059 &key));
4063 // Try importing an AES-KW key with unsupported key usages using raw
4064 // format. AES-KW keys support the following usages:
4065 // 'wrapKey', 'unwrapKey'
4066 TEST_F(SharedCryptoTest, MAYBE(ImportAesKwKeyBadUsage_Raw)) {
4067 const blink::WebCryptoAlgorithm algorithm =
4068 CreateAlgorithm(blink::WebCryptoAlgorithmIdAesKw);
4070 blink::WebCryptoKeyUsageMask bad_usages[] = {
4071 blink::WebCryptoKeyUsageEncrypt,
4072 blink::WebCryptoKeyUsageDecrypt,
4073 blink::WebCryptoKeyUsageSign,
4074 blink::WebCryptoKeyUsageSign | blink::WebCryptoKeyUsageUnwrapKey,
4075 blink::WebCryptoKeyUsageDeriveBits,
4076 blink::WebCryptoKeyUsageUnwrapKey | blink::WebCryptoKeyUsageVerify,
4079 std::vector<uint8> key_bytes(16);
4081 for (size_t i = 0; i < arraysize(bad_usages); ++i) {
4082 SCOPED_TRACE(i);
4084 blink::WebCryptoKey key = blink::WebCryptoKey::createNull();
4085 ASSERT_EQ(Status::ErrorCreateKeyBadUsages(),
4086 ImportKey(blink::WebCryptoKeyFormatRaw,
4087 CryptoData(key_bytes),
4088 algorithm,
4089 true,
4090 bad_usages[i],
4091 &key));
4095 // Try unwrapping an HMAC key with unsupported usages using JWK format and
4096 // AES-KW. HMAC keys support the following usages:
4097 // 'sign', 'verify'
4098 TEST_F(SharedCryptoTest, MAYBE(UnwrapHmacKeyBadUsage_JWK)) {
4099 const blink::WebCryptoAlgorithm unwrap_algorithm =
4100 CreateAlgorithm(blink::WebCryptoAlgorithmIdAesKw);
4102 blink::WebCryptoKeyUsageMask bad_usages[] = {
4103 blink::WebCryptoKeyUsageEncrypt,
4104 blink::WebCryptoKeyUsageDecrypt,
4105 blink::WebCryptoKeyUsageWrapKey,
4106 blink::WebCryptoKeyUsageSign | blink::WebCryptoKeyUsageWrapKey,
4107 blink::WebCryptoKeyUsageVerify | blink::WebCryptoKeyUsageDeriveKey,
4110 // Import the wrapping key.
4111 blink::WebCryptoKey wrapping_key = blink::WebCryptoKey::createNull();
4112 ASSERT_EQ(Status::Success(),
4113 ImportKey(blink::WebCryptoKeyFormatRaw,
4114 CryptoData(std::vector<uint8>(16)),
4115 unwrap_algorithm,
4116 true,
4117 blink::WebCryptoKeyUsageUnwrapKey,
4118 &wrapping_key));
4120 // The JWK plain text is:
4121 // { "kty": "oct","alg": "HS256","k": "GADWrMRHwQfoNaXU5fZvTg=="}
4122 const char* kWrappedJwk =
4123 "0AA245F17064FFB2A7A094436A39BEBFC962C627303D1327EA750CE9F917688C2782A943"
4124 "7AE7586547AC490E8AE7D5B02D63868D5C3BB57D36C4C8C5BF3962ACEC6F42E767E5706"
4125 "4";
4127 for (size_t i = 0; i < arraysize(bad_usages); ++i) {
4128 SCOPED_TRACE(i);
4130 blink::WebCryptoKey key = blink::WebCryptoKey::createNull();
4132 ASSERT_EQ(Status::ErrorCreateKeyBadUsages(),
4133 UnwrapKey(blink::WebCryptoKeyFormatJwk,
4134 CryptoData(HexStringToBytes(kWrappedJwk)),
4135 wrapping_key,
4136 unwrap_algorithm,
4137 webcrypto::CreateHmacImportAlgorithm(
4138 blink::WebCryptoAlgorithmIdSha256),
4139 true,
4140 bad_usages[i],
4141 &key));
4145 // Try unwrapping an RSA-SSA public key with unsupported usages using JWK format
4146 // and AES-KW. RSA-SSA public keys support the following usages:
4147 // 'verify'
4148 TEST_F(SharedCryptoTest, MAYBE(UnwrapRsaSsaPublicKeyBadUsage_JWK)) {
4149 const blink::WebCryptoAlgorithm unwrap_algorithm =
4150 CreateAlgorithm(blink::WebCryptoAlgorithmIdAesKw);
4152 blink::WebCryptoKeyUsageMask bad_usages[] = {
4153 blink::WebCryptoKeyUsageEncrypt,
4154 blink::WebCryptoKeyUsageSign,
4155 blink::WebCryptoKeyUsageDecrypt,
4156 blink::WebCryptoKeyUsageWrapKey,
4157 blink::WebCryptoKeyUsageSign | blink::WebCryptoKeyUsageWrapKey,
4160 // Import the wrapping key.
4161 blink::WebCryptoKey wrapping_key = blink::WebCryptoKey::createNull();
4162 ASSERT_EQ(Status::Success(),
4163 ImportKey(blink::WebCryptoKeyFormatRaw,
4164 CryptoData(std::vector<uint8>(16)),
4165 unwrap_algorithm,
4166 true,
4167 blink::WebCryptoKeyUsageUnwrapKey,
4168 &wrapping_key));
4170 // The JWK plaintext is:
4171 // { "kty": "RSA","alg": "RS256","n": "...","e": "AQAB"}
4173 const char* kWrappedJwk =
4174 "CE8DAEF99E977EE58958B8C4494755C846E883B2ECA575C5366622839AF71AB30875F152"
4175 "E8E33E15A7817A3A2874EB53EFE05C774D98BC936BA9BA29BEB8BB3F3C3CE2323CB3359D"
4176 "E3F426605CF95CCF0E01E870ABD7E35F62E030B5FB6E520A5885514D1D850FB64B57806D"
4177 "1ADA57C6E27DF345D8292D80F6B074F1BE51C4CF3D76ECC8886218551308681B44FAC60B"
4178 "8CF6EA439BC63239103D0AE81ADB96F908680586C6169284E32EB7DD09D31103EBDAC0C2"
4179 "40C72DCF0AEA454113CC47457B13305B25507CBEAB9BDC8D8E0F867F9167F9DCEF0D9F9B"
4180 "30F2EE83CEDFD51136852C8A5939B768";
4182 for (size_t i = 0; i < arraysize(bad_usages); ++i) {
4183 SCOPED_TRACE(i);
4185 blink::WebCryptoKey key = blink::WebCryptoKey::createNull();
4187 ASSERT_EQ(Status::ErrorCreateKeyBadUsages(),
4188 UnwrapKey(blink::WebCryptoKeyFormatJwk,
4189 CryptoData(HexStringToBytes(kWrappedJwk)),
4190 wrapping_key,
4191 unwrap_algorithm,
4192 webcrypto::CreateRsaHashedImportAlgorithm(
4193 blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
4194 blink::WebCryptoAlgorithmIdSha256),
4195 true,
4196 bad_usages[i],
4197 &key));
4201 // Generate an AES-CBC key with invalid usages. AES-CBC supports:
4202 // 'encrypt', 'decrypt', 'wrapKey', 'unwrapKey'
4203 TEST_F(SharedCryptoTest, MAYBE(GenerateAesKeyBadUsages)) {
4204 blink::WebCryptoKeyUsageMask bad_usages[] = {
4205 blink::WebCryptoKeyUsageSign, blink::WebCryptoKeyUsageVerify,
4206 blink::WebCryptoKeyUsageDecrypt | blink::WebCryptoKeyUsageVerify,
4209 for (size_t i = 0; i < arraysize(bad_usages); ++i) {
4210 SCOPED_TRACE(i);
4212 blink::WebCryptoKey key = blink::WebCryptoKey::createNull();
4214 ASSERT_EQ(Status::ErrorCreateKeyBadUsages(),
4215 GenerateSecretKey(
4216 CreateAesCbcKeyGenAlgorithm(128), true, bad_usages[i], &key));
4220 // Generate an RSA-SSA key pair with invalid usages. RSA-SSA supports:
4221 // 'sign', 'verify'
4222 TEST_F(SharedCryptoTest, MAYBE(GenerateRsaSsaBadUsages)) {
4223 blink::WebCryptoKeyUsageMask bad_usages[] = {
4224 blink::WebCryptoKeyUsageDecrypt,
4225 blink::WebCryptoKeyUsageVerify | blink::WebCryptoKeyUsageDecrypt,
4226 blink::WebCryptoKeyUsageWrapKey,
4229 const unsigned int modulus_length = 256;
4230 const std::vector<uint8> public_exponent = HexStringToBytes("010001");
4232 for (size_t i = 0; i < arraysize(bad_usages); ++i) {
4233 SCOPED_TRACE(i);
4235 blink::WebCryptoKey public_key = blink::WebCryptoKey::createNull();
4236 blink::WebCryptoKey private_key = blink::WebCryptoKey::createNull();
4238 ASSERT_EQ(Status::ErrorCreateKeyBadUsages(),
4239 GenerateKeyPair(CreateRsaHashedKeyGenAlgorithm(
4240 blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
4241 blink::WebCryptoAlgorithmIdSha256,
4242 modulus_length,
4243 public_exponent),
4244 true,
4245 bad_usages[i],
4246 &public_key,
4247 &private_key));
4251 // Generate an RSA-SSA key pair. The public and private keys should select the
4252 // key usages which are applicable, and not have the exact same usages as was
4253 // specified to GenerateKey
4254 TEST_F(SharedCryptoTest, MAYBE(GenerateRsaSsaKeyPairIntersectUsages)) {
4255 const unsigned int modulus_length = 256;
4256 const std::vector<uint8> public_exponent = HexStringToBytes("010001");
4258 blink::WebCryptoKey public_key = blink::WebCryptoKey::createNull();
4259 blink::WebCryptoKey private_key = blink::WebCryptoKey::createNull();
4261 ASSERT_EQ(Status::Success(),
4262 GenerateKeyPair(
4263 CreateRsaHashedKeyGenAlgorithm(
4264 blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
4265 blink::WebCryptoAlgorithmIdSha256,
4266 modulus_length,
4267 public_exponent),
4268 true,
4269 blink::WebCryptoKeyUsageSign | blink::WebCryptoKeyUsageVerify,
4270 &public_key,
4271 &private_key));
4273 EXPECT_EQ(blink::WebCryptoKeyUsageVerify, public_key.usages());
4274 EXPECT_EQ(blink::WebCryptoKeyUsageSign, private_key.usages());
4276 // Try again but this time without the Verify usages.
4277 ASSERT_EQ(Status::Success(),
4278 GenerateKeyPair(CreateRsaHashedKeyGenAlgorithm(
4279 blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
4280 blink::WebCryptoAlgorithmIdSha256,
4281 modulus_length,
4282 public_exponent),
4283 true,
4284 blink::WebCryptoKeyUsageSign,
4285 &public_key,
4286 &private_key));
4288 EXPECT_EQ(0, public_key.usages());
4289 EXPECT_EQ(blink::WebCryptoKeyUsageSign, private_key.usages());
4292 // Generate an AES-CBC key and an RSA key pair. Use the AES-CBC key to wrap the
4293 // key pair (using SPKI format for public key, PKCS8 format for private key).
4294 // Then unwrap the wrapped key pair and verify that the key data is the same.
4295 TEST_F(SharedCryptoTest, MAYBE(WrapUnwrapRoundtripSpkiPkcs8UsingAesCbc)) {
4296 if (!SupportsRsaKeyImport())
4297 return;
4299 // Generate the wrapping key.
4300 blink::WebCryptoKey wrapping_key = blink::WebCryptoKey::createNull();
4301 ASSERT_EQ(Status::Success(),
4302 GenerateSecretKey(CreateAesCbcKeyGenAlgorithm(128),
4303 true,
4304 blink::WebCryptoKeyUsageWrapKey |
4305 blink::WebCryptoKeyUsageUnwrapKey,
4306 &wrapping_key));
4308 // Generate an RSA key pair to be wrapped.
4309 const unsigned int modulus_length = 256;
4310 const std::vector<uint8> public_exponent = HexStringToBytes("010001");
4312 blink::WebCryptoKey public_key = blink::WebCryptoKey::createNull();
4313 blink::WebCryptoKey private_key = blink::WebCryptoKey::createNull();
4314 ASSERT_EQ(Status::Success(),
4315 GenerateKeyPair(CreateRsaHashedKeyGenAlgorithm(
4316 blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
4317 blink::WebCryptoAlgorithmIdSha256,
4318 modulus_length,
4319 public_exponent),
4320 true,
4322 &public_key,
4323 &private_key));
4325 // Export key pair as SPKI + PKCS8
4326 std::vector<uint8> public_key_spki;
4327 ASSERT_EQ(
4328 Status::Success(),
4329 ExportKey(blink::WebCryptoKeyFormatSpki, public_key, &public_key_spki));
4331 std::vector<uint8> private_key_pkcs8;
4332 ASSERT_EQ(
4333 Status::Success(),
4334 ExportKey(
4335 blink::WebCryptoKeyFormatPkcs8, private_key, &private_key_pkcs8));
4337 // Wrap the key pair.
4338 blink::WebCryptoAlgorithm wrap_algorithm =
4339 CreateAesCbcAlgorithm(std::vector<uint8>(16, 0));
4341 std::vector<uint8> wrapped_public_key;
4342 ASSERT_EQ(Status::Success(),
4343 WrapKey(blink::WebCryptoKeyFormatSpki,
4344 public_key,
4345 wrapping_key,
4346 wrap_algorithm,
4347 &wrapped_public_key));
4349 std::vector<uint8> wrapped_private_key;
4350 ASSERT_EQ(Status::Success(),
4351 WrapKey(blink::WebCryptoKeyFormatPkcs8,
4352 private_key,
4353 wrapping_key,
4354 wrap_algorithm,
4355 &wrapped_private_key));
4357 // Unwrap the key pair.
4358 blink::WebCryptoAlgorithm rsa_import_algorithm =
4359 CreateRsaHashedImportAlgorithm(blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
4360 blink::WebCryptoAlgorithmIdSha256);
4362 blink::WebCryptoKey unwrapped_public_key = blink::WebCryptoKey::createNull();
4364 ASSERT_EQ(Status::Success(),
4365 UnwrapKey(blink::WebCryptoKeyFormatSpki,
4366 CryptoData(wrapped_public_key),
4367 wrapping_key,
4368 wrap_algorithm,
4369 rsa_import_algorithm,
4370 true,
4372 &unwrapped_public_key));
4374 blink::WebCryptoKey unwrapped_private_key = blink::WebCryptoKey::createNull();
4376 ASSERT_EQ(Status::Success(),
4377 UnwrapKey(blink::WebCryptoKeyFormatPkcs8,
4378 CryptoData(wrapped_private_key),
4379 wrapping_key,
4380 wrap_algorithm,
4381 rsa_import_algorithm,
4382 true,
4384 &unwrapped_private_key));
4386 // Export unwrapped key pair as SPKI + PKCS8
4387 std::vector<uint8> unwrapped_public_key_spki;
4388 ASSERT_EQ(Status::Success(),
4389 ExportKey(blink::WebCryptoKeyFormatSpki,
4390 unwrapped_public_key,
4391 &unwrapped_public_key_spki));
4393 std::vector<uint8> unwrapped_private_key_pkcs8;
4394 ASSERT_EQ(Status::Success(),
4395 ExportKey(blink::WebCryptoKeyFormatPkcs8,
4396 unwrapped_private_key,
4397 &unwrapped_private_key_pkcs8));
4399 EXPECT_EQ(public_key_spki, unwrapped_public_key_spki);
4400 EXPECT_EQ(private_key_pkcs8, unwrapped_private_key_pkcs8);
4402 EXPECT_NE(public_key_spki, wrapped_public_key);
4403 EXPECT_NE(private_key_pkcs8, wrapped_private_key);
4406 } // namespace webcrypto
4408 } // namespace content