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"
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)
36 #include "crypto/scoped_nss_types.h"
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
44 #define MAYBE(test_name) test_name
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)
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())
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())
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) {
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) {
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,
111 CreateAlgorithm(blink::WebCryptoAlgorithmIdAesGcm),
113 blink::WebCryptoKeyUsageEncrypt,
116 if (status.IsError())
117 EXPECT_EQ(blink::WebCryptoErrorTypeNotSupported, status.error_type());
118 return status.IsSuccess();
121 bool SupportsRsaOaep() {
122 #if defined(USE_OPENSSL)
125 // TODO(eroman): Exclude version test for OS_CHROMEOS
127 if (!NSS_VersionCheck("3.16.2"))
130 crypto::ScopedPK11Slot slot(PK11_GetInternalKeySlot());
131 return !!PK11_DoesMechanism(slot.get(), CKM_RSA_PKCS_OAEP);
135 bool SupportsRsaKeyImport() {
136 // TODO(eroman): Exclude version test for OS_CHROMEOS
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";
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(
157 new blink::WebCryptoRsaHashedKeyGenParams(
158 CreateAlgorithm(hash_id),
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),
191 Uint8VectorStart(additional_data),
192 additional_data.size(),
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);
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) {
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
262 re2::RE2::GlobalReplace(&file_contents, re2::RE2("\\s*//.*"), "");
264 // Parse the JSON to a dictionary.
265 value->reset(base::JSONReader::Read(file_contents));
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) {
279 scoped_ptr<base::Value> json;
280 ::testing::AssertionResult result = ReadJsonTestFile(test_file_name, &json);
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();
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) {
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) {
354 dict->SetString("kty", "RSA");
355 dict->SetString("alg", "RS256");
356 dict->SetString("use", "sig");
357 dict->SetBoolean("ext", false);
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
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]))
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,
392 blink::WebCryptoAlgorithm CreateAesGcmKeyGenAlgorithm(
393 unsigned short key_length_bits) {
394 EXPECT_TRUE(SupportsAesGcm());
395 return CreateAesKeyGenAlgorithm(blink::WebCryptoAlgorithmIdAesGcm,
399 blink::WebCryptoAlgorithm CreateAesKwKeyGenAlgorithm(
400 unsigned short key_length_bits) {
401 return CreateAesKeyGenAlgorithm(blink::WebCryptoAlgorithmIdAesKw,
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"
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 {
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,
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());
476 void ImportRsaKeyPair(const std::vector<uint8>& spki_der,
477 const std::vector<uint8>& pkcs8_der,
478 const blink::WebCryptoAlgorithm& algorithm,
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),
489 public_key_usage_mask,
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),
503 private_key_usage_mask,
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())
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(),
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,
576 blink::WebCryptoKeyUsageMask usage_mask,
577 blink::WebCryptoKey* key) {
578 return ImportKey(blink::WebCryptoKeyFormatJwk,
586 Status ImportKeyJwkFromDict(const base::DictionaryValue& dict,
587 const blink::WebCryptoAlgorithm& algorithm,
589 blink::WebCryptoKeyUsageMask usage_mask,
590 blink::WebCryptoKey* key) {
591 return ImportKeyJwk(CryptoData(MakeJsonVector(dict)),
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);
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) {
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 "
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 "
635 // always expect ext == true in this case
637 if (!dict->GetBoolean("ext", &ext_value))
638 return ::testing::AssertionFailure() << "Missing 'ext'";
640 return ::testing::AssertionFailure()
641 << "Expected 'ext' to be true but found false";
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";
671 std::string value_string;
672 if (!dict->GetString("k", &value_string))
673 return ::testing::AssertionFailure() << "Missing 'k'";
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 "
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";
700 std::string value_string;
701 if (!dict->GetString("n", &value_string))
702 return ::testing::AssertionFailure() << "Missing 'n'";
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 "
710 // TODO(padolph): LowerCaseEqualsASCII() does not work for above!
713 if (!dict->GetString("e", &value_string))
714 return ::testing::AssertionFailure() << "Missing 'e'";
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 "
722 << " but found something different";
725 return VerifyJwk(dict, "RSA", alg_expected, use_mask_expected);
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";
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
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(
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,
896 CryptoData(test_message),
898 EXPECT_TRUE(signature_match);
900 // Ensure truncated signature does not verify by passing one less byte.
903 VerifySignature(algorithm,
905 CryptoData(Uint8VectorStart(output), output.size() - 1),
906 CryptoData(test_message),
908 EXPECT_FALSE(signature_match);
910 // Ensure truncated signature does not verify by passing no bytes.
911 EXPECT_EQ(Status::Success(),
912 VerifySignature(algorithm,
915 CryptoData(test_message),
917 EXPECT_FALSE(signature_match);
919 // Ensure extra long signature does not cause issues and fails.
920 const unsigned char kLongSignature[1024] = {0};
923 VerifySignature(algorithm,
925 CryptoData(kLongSignature, sizeof(kLongSignature)),
926 CryptoData(test_message),
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),
956 EXPECT_EQ(Status::ErrorIncorrectSizeAesCbcIv(),
957 Decrypt(webcrypto::CreateAesCbcAlgorithm(iv),
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),
972 EXPECT_EQ(Status::ErrorIncorrectSizeAesCbcIv(),
973 Decrypt(webcrypto::CreateAesCbcAlgorithm(iv),
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
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),
1006 blink::WebCryptoKeyUsageEncrypt,
1010 // Fail exporting the key in SPKI and PKCS#8 formats (not allowed for secret
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(
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;
1050 EXPECT_EQ(Status::Success(),
1051 Encrypt(webcrypto::CreateAesCbcAlgorithm(test_iv),
1053 CryptoData(test_plain_text),
1055 EXPECT_BYTES_EQ(test_cipher_text, output);
1058 EXPECT_EQ(Status::Success(),
1059 Decrypt(webcrypto::CreateAesCbcAlgorithm(test_iv),
1061 CryptoData(test_cipher_text),
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),
1073 CryptoData(&test_cipher_text[0],
1074 test_cipher_text.size() - kAesCbcBlockSize),
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) {
1082 Status::OperationError(),
1083 Decrypt(CreateAesCbcAlgorithm(test_iv),
1085 CryptoData(&test_cipher_text[0], test_cipher_text.size() - 3),
1091 TEST_F(SharedCryptoTest, MAYBE(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) {
1107 // Generate a small sample of keys.
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, MAYBE(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) {
1131 EXPECT_EQ(Status::ErrorGenerateKeyLength(),
1133 CreateAesCbcKeyGenAlgorithm(kKeyLen[i]), true, 0, &key));
1134 EXPECT_EQ(Status::ErrorGenerateKeyLength(),
1136 CreateAesKwKeyGenAlgorithm(kKeyLen[i]), true, 0, &key));
1137 if (SupportsAesGcm()) {
1138 EXPECT_EQ(Status::ErrorGenerateKeyLength(),
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);
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.
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);
1243 SCOPED_TRACE(test_index);
1244 dict.SetString("alg", test_case[test_index].jwk_alg);
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,
1251 test_case[test_index].usage,
1253 EXPECT_EQ(test_case[test_index].usage, key.usages());
1256 // Test discrete multiple usages.
1257 dict.SetString("alg", "A128CBC");
1259 key_ops->AppendString("encrypt");
1260 key_ops->AppendString("decrypt");
1261 EXPECT_EQ(Status::Success(),
1262 ImportKeyJwkFromDict(dict,
1265 blink::WebCryptoKeyUsageDecrypt |
1266 blink::WebCryptoKeyUsageEncrypt,
1268 EXPECT_EQ(blink::WebCryptoKeyUsageDecrypt | blink::WebCryptoKeyUsageEncrypt,
1271 // Test constrained key usage (input usage is a subset of JWK usage).
1273 key_ops->AppendString("encrypt");
1274 key_ops->AppendString("decrypt");
1275 EXPECT_EQ(Status::Success(),
1276 ImportKeyJwkFromDict(dict,
1279 blink::WebCryptoKeyUsageDecrypt,
1281 EXPECT_EQ(blink::WebCryptoKeyUsageDecrypt, key.usages());
1283 // Test failure if input usage is NOT a strict subset of the JWK usage.
1285 key_ops->AppendString("encrypt");
1286 EXPECT_EQ(Status::ErrorJwkKeyopsInconsistent(),
1287 ImportKeyJwkFromDict(dict,
1290 blink::WebCryptoKeyUsageEncrypt |
1291 blink::WebCryptoKeyUsageDecrypt,
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(
1305 blink::WebCryptoKeyUsageSign | blink::WebCryptoKeyUsageVerify,
1308 // Test JWK composite 'sig' use
1309 dict.Remove("key_ops", NULL);
1310 dict.SetString("use", "sig");
1311 EXPECT_EQ(Status::Success(),
1312 ImportKeyJwkFromDict(
1316 blink::WebCryptoKeyUsageSign | blink::WebCryptoKeyUsageVerify,
1318 EXPECT_EQ(blink::WebCryptoKeyUsageSign | blink::WebCryptoKeyUsageVerify,
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,
1328 blink::WebCryptoKeyUsageDecrypt |
1329 blink::WebCryptoKeyUsageEncrypt |
1330 blink::WebCryptoKeyUsageWrapKey |
1331 blink::WebCryptoKeyUsageUnwrapKey,
1333 EXPECT_EQ(blink::WebCryptoKeyUsageDecrypt | blink::WebCryptoKeyUsageEncrypt |
1334 blink::WebCryptoKeyUsageWrapKey |
1335 blink::WebCryptoKeyUsageUnwrapKey,
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
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.
1356 Status::ErrorImportEmptyKeyData(),
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\","
1366 EXPECT_EQ(Status::ErrorJwkNotDictionary(),
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
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();
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);
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())
1522 const bool supports_rsa_oaep = SupportsRsaOaep();
1523 if (!supports_rsa_oaep) {
1524 LOG(WARNING) << "RSA-OAEP not supported on this platform. Skipping some"
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);
1573 SCOPED_TRACE(test_index);
1574 const TestCase& test = kTests[test_index];
1575 if (!supports_rsa_oaep &&
1576 test.algorithm.id() == blink::WebCryptoAlgorithmIdRsaOaep) {
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)),
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,
1596 kPublicKeyModulusHex,
1597 kPublicKeyExponentHex,
1600 // Import the JWK back in to create a new key
1601 blink::WebCryptoKey public_key2 = blink::WebCryptoKey::createNull();
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,
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);
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.
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);
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
1720 Status::ErrorJwkExtInconsistent(),
1721 ImportKeyJwk(CryptoData(json_vec), algorithm, true, usage_mask, &key));
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
1737 EXPECT_EQ(Status::ErrorJwkAlgorithmInconsistent(),
1738 ImportKeyJwk(CryptoData(json_vec),
1739 CreateAlgorithm(blink::WebCryptoAlgorithmIdAesCbc),
1741 blink::WebCryptoKeyUsageEncrypt,
1744 // Fail: Input algorithm (HMAC SHA1) is inconsistent with JWK value
1747 Status::ErrorJwkAlgorithmInconsistent(),
1748 ImportKeyJwk(CryptoData(json_vec),
1749 CreateHmacImportAlgorithm(blink::WebCryptoAlgorithmIdSha1),
1754 // Pass: JWK alg missing but input algorithm specified: use input value
1755 dict.Remove("alg", NULL);
1756 EXPECT_EQ(Status::Success(),
1757 ImportKeyJwkFromDict(
1759 CreateHmacImportAlgorithm(blink::WebCryptoAlgorithmIdSha256),
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),
1772 blink::WebCryptoKeyUsageEncrypt,
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;
1780 Status::ErrorCreateKeyBadUsages(),
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
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");
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),
1830 CryptoData(message_raw),
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);
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[] = {
1878 {key_hex_128, aes_cbc_alg,
1879 blink::WebCryptoKeyUsageEncrypt | blink::WebCryptoKeyUsageDecrypt,
1882 {key_hex_256, aes_cbc_alg, blink::WebCryptoKeyUsageDecrypt, "A256CBC"},
1884 {key_hex_128, aes_gcm_alg,
1885 blink::WebCryptoKeyUsageEncrypt | blink::WebCryptoKeyUsageDecrypt,
1888 {key_hex_256, aes_gcm_alg, blink::WebCryptoKeyUsageDecrypt, "A256GCM"},
1890 {key_hex_128, aes_kw_alg,
1891 blink::WebCryptoKeyUsageWrapKey | blink::WebCryptoKeyUsageUnwrapKey,
1894 {key_hex_256, aes_kw_alg,
1895 blink::WebCryptoKeyUsageWrapKey | blink::WebCryptoKeyUsageUnwrapKey,
1898 {key_hex_256, hmac_sha_1_alg,
1899 blink::WebCryptoKeyUsageSign | blink::WebCryptoKeyUsageVerify, "HS1"},
1901 {key_hex_384, hmac_sha_384_alg, blink::WebCryptoKeyUsageSign, "HS384"},
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,
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);
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()) {
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.
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,
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())
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),
2007 blink::WebCryptoKeyUsageVerify,
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(
2017 CryptoData(key.algorithm().rsaHashedParams()->publicExponent()));
2019 // Failing case: Empty SPKI data
2021 Status::ErrorImportEmptyKeyData(),
2022 ImportKey(blink::WebCryptoKeyFormatSpki,
2023 CryptoData(std::vector<uint8>()),
2024 CreateAlgorithm(blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5),
2026 blink::WebCryptoKeyUsageVerify,
2029 // Failing case: Bad DER encoding.
2031 Status::DataError(),
2032 ImportKey(blink::WebCryptoKeyFormatSpki,
2033 CryptoData(HexStringToBytes("618333c4cb")),
2034 CreateAlgorithm(blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5),
2036 blink::WebCryptoKeyUsageVerify,
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),
2045 blink::WebCryptoKeyUsageEncrypt,
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),
2068 blink::WebCryptoKeyUsageVerify,
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
2083 TEST_F(SharedCryptoTest, MAYBE(ImportExportPkcs8)) {
2084 if (!SupportsRsaKeyImport())
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),
2096 blink::WebCryptoKeyUsageSign,
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(
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),
2123 blink::WebCryptoKeyUsageSign,
2126 // Failing case: Bad DER encoding.
2128 Status::DataError(),
2129 ImportKey(blink::WebCryptoKeyFormatPkcs8,
2130 CryptoData(HexStringToBytes("618333c4cb")),
2131 CreateAlgorithm(blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5),
2133 blink::WebCryptoKeyUsageSign,
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),
2145 blink::WebCryptoKeyUsageSign,
2149 // Tests JWK import and export by doing a roundtrip key conversion and ensuring
2152 // PKCS8 --> JWK --> PKCS8
2153 TEST_F(SharedCryptoTest, MAYBE(ImportRsaPrivateKeyJwkToPkcs8RoundTrip)) {
2154 if (!SupportsRsaKeyImport())
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),
2165 blink::WebCryptoKeyUsageSign,
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
2174 const char* expected_jwk =
2175 "{\"alg\":\"RS1\",\"d\":\"M6UEKpCyfU9UUcqbu9C0R3GhAa-IQ0Cu-YhfKku-"
2176 "kuiUpySsPFaMj5eFOtB8AmbIxqPKCSnx6PESMYhEKfxNmuVf7olqEM5wfD7X5zTkRyejlXRQ"
2177 "GlMmgxCcKrrKuig8MbS9L1PD7jfjUs7jT55QO9gMBiKtecbc7og1R8ajsyU\",\"dp\":"
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),
2202 blink::WebCryptoKeyUsageSign,
2205 std::vector<uint8> exported_key_pkcs8;
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
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
2221 TEST_F(SharedCryptoTest, MAYBE(ImportMultipleRSAPrivateKeysJwk)) {
2222 if (!SupportsRsaKeyImport())
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
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.
2256 ImportKeyJwkFromDict(*key_jwk,
2257 CreateRsaHashedImportAlgorithm(
2258 blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
2259 blink::WebCryptoAlgorithmIdSha256),
2261 blink::WebCryptoKeyUsageSign,
2264 live_keys.push_back(private_key);
2267 modulus_length_bits,
2269 private_key.algorithm().rsaHashedParams()->modulusLengthBits()));
2271 // Export to PKCS8 and verify that it matches expectation.
2272 std::vector<uint8> exported_key_pkcs8;
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";
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),
2310 blink::WebCryptoKeyUsageSign,
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),
2334 blink::WebCryptoKeyUsageSign,
2338 // Import a JWK RSA private key with some optional parameters missing (q, dp,
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");
2354 "pW5KDnAQF1iaUYfcfqhB0Vby7A42rVKkTf6x5h962ZHYxRBW_-2xYrTA8oOhKoijlN_"
2355 "1JqtykcuzB86r_OCx39XNlQgJbVsri2311nHvY3fAkhyyPCcKcOJZjm_4nRnxBazC0_"
2356 "DLNfKSgOE4a29kxO8i4eHyDQzoz_siSb2aITc");
2357 dict.SetString("e", "AQAB");
2360 "M6UEKpCyfU9UUcqbu9C0R3GhAa-IQ0Cu-YhfKku-"
2361 "kuiUpySsPFaMj5eFOtB8AmbIxqPKCSnx6PESMYhEKfxNmuVf7olqEM5wfD7X5zTkRyejlXRQ"
2362 "GlMmgxCcKrrKuig8MbS9L1PD7jfjUs7jT55QO9gMBiKtecbc7og1R8ajsyU");
2366 "iUJyCod1Fyc6NWBT6iobwMlKpy1VxuhilrLfyWeUjApyy8zKfqyzVwbgmh31W"
2367 "hU1vZs8w0Fgs7bc0-2o5kQw");
2369 ASSERT_EQ(Status::ErrorJwkIncompleteOptionalRsaPrivateKey(),
2370 ImportKeyJwkFromDict(dict,
2371 CreateRsaHashedImportAlgorithm(
2372 blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
2373 blink::WebCryptoAlgorithmIdSha1),
2375 blink::WebCryptoKeyUsageSign,
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
2384 // TODO(eroman): http://crbug/com/374927
2385 TEST_F(SharedCryptoTest, MAYBE(ImportRsaPrivateKeyJwkIncorrectOptionalEmpty)) {
2386 if (!SupportsRsaKeyImport())
2389 blink::WebCryptoKey key = blink::WebCryptoKey::createNull();
2391 base::DictionaryValue dict;
2392 dict.SetString("kty", "RSA");
2393 dict.SetString("alg", "RS1");
2397 "pW5KDnAQF1iaUYfcfqhB0Vby7A42rVKkTf6x5h962ZHYxRBW_-2xYrTA8oOhKoijlN_"
2398 "1JqtykcuzB86r_OCx39XNlQgJbVsri2311nHvY3fAkhyyPCcKcOJZjm_4nRnxBazC0_"
2399 "DLNfKSgOE4a29kxO8i4eHyDQzoz_siSb2aITc");
2400 dict.SetString("e", "AQAB");
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),
2417 blink::WebCryptoKeyUsageSign,
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,
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(),
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;
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),
2476 EXPECT_EQ(modulus_length,
2477 public_key.algorithm().rsaHashedParams()->modulusLengthBits());
2479 std::vector<uint8> private_key_pkcs8;
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),
2494 EXPECT_EQ(modulus_length,
2495 private_key.algorithm().rsaHashedParams()->modulusLengthBits());
2498 // Fail with bad modulus.
2500 CreateRsaHashedKeyGenAlgorithm(blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
2501 blink::WebCryptoAlgorithmIdSha256,
2504 EXPECT_EQ(Status::ErrorGenerateRsaZeroModulus(),
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);
2512 CreateRsaHashedKeyGenAlgorithm(blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
2513 blink::WebCryptoAlgorithmIdSha256,
2516 EXPECT_EQ(Status::ErrorGenerateKeyPublicExponent(),
2518 algorithm, extractable, usage_mask, &public_key, &private_key));
2520 // Fail with bad exponent: empty.
2521 const std::vector<uint8> empty_exponent;
2523 CreateRsaHashedKeyGenAlgorithm(blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
2524 blink::WebCryptoAlgorithmIdSha256,
2527 EXPECT_EQ(Status::ErrorGenerateKeyPublicExponent(),
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);
2534 CreateRsaHashedKeyGenAlgorithm(blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
2535 blink::WebCryptoAlgorithmIdSha256,
2537 exponent_with_leading_zeros);
2538 EXPECT_EQ(Status::ErrorGenerateKeyPublicExponent(),
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());
2547 CreateRsaHashedKeyGenAlgorithm(blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
2548 blink::WebCryptoAlgorithmIdSha256,
2550 exponent_with_leading_zeros);
2551 EXPECT_EQ(Status::Success(),
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)
2565 CreateRsaHashedKeyGenAlgorithm(blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
2566 blink::WebCryptoAlgorithmIdSha1,
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
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.
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,
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();
2631 algorithm, extractable, usage_mask, &public_key, &private_key)
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.
2651 for (size_t i = 0; i < arraysize(kPublicExponents); ++i) {
2653 blink::WebCryptoAlgorithm algorithm = CreateRsaHashedKeyGenAlgorithm(
2654 blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
2655 blink::WebCryptoAlgorithmIdSha256,
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(),
2664 algorithm, true, 0, &public_key, &private_key));
2668 TEST_F(SharedCryptoTest, MAYBE(RsaSsaSignVerifyFailures)) {
2669 if (!SupportsRsaKeyImport())
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),
2683 blink::WebCryptoKeyUsageVerify,
2684 blink::WebCryptoKeyUsageSign,
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(),
2704 CryptoData(Uint8VectorStart(signature), signature.size() - 1),
2707 EXPECT_FALSE(signature_match);
2709 // Ensure truncated signature does not verify by passing no bytes.
2710 EXPECT_EQ(Status::Success(),
2711 VerifySignature(algorithm,
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,
2724 CryptoData(corrupt_sig),
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,
2736 CryptoData(kLongSignature, sizeof(kLongSignature)),
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,
2749 CryptoData(signature),
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),
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),
2777 blink::WebCryptoKeyUsageVerify,
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());
2791 EXPECT_EQ(Status::Success(),
2793 CreateAlgorithm(blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5),
2795 CryptoData(signature),
2798 EXPECT_FALSE(is_match);
2801 TEST_F(SharedCryptoTest, MAYBE(RsaSignVerifyKnownAnswer)) {
2802 if (!SupportsRsaKeyImport())
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),
2819 blink::WebCryptoKeyUsageVerify,
2820 blink::WebCryptoKeyUsageSign,
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");
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,
2850 CryptoData(test_signature),
2851 CryptoData(test_message),
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)),
2869 blink::WebCryptoKeyUsageWrapKey,
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)),
2883 blink::WebCryptoKeyUsageWrapKey,
2886 // Import a 256-bit Key Encryption Key (KEK)
2888 "e11fe66380d90fa9ebefb74e0478e78f95664d0c67ca20ce4a0b5842863ac46f";
2889 ASSERT_EQ(Status::Success(),
2890 ImportKey(blink::WebCryptoKeyFormatRaw,
2891 CryptoData(HexStringToBytes(key_raw_hex_in)),
2894 blink::WebCryptoKeyUsageWrapKey,
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("")),
2906 blink::WebCryptoKeyUsageWrapKey,
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)),
2916 blink::WebCryptoKeyUsageWrapKey,
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)),
2926 blink::WebCryptoKeyUsageWrapKey,
2929 // Fail import of 260-bit KEK
2931 "72d4e475ff34215416c9ad9c8281247a4d730c5f275ac23f376e73e3bce8d7d5a";
2932 EXPECT_EQ(Status::ErrorImportAesKeyLength(),
2933 ImportKey(blink::WebCryptoKeyFormatRaw,
2934 CryptoData(HexStringToBytes(key_raw_hex_in)),
2937 blink::WebCryptoKeyUsageWrapKey,
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
2955 blink::WebCryptoKey wrapping_key = ImportSecretKeyFromRaw(
2957 webcrypto::CreateAlgorithm(blink::WebCryptoAlgorithmIdAesKw),
2958 blink::WebCryptoKeyUsageUnwrapKey);
2960 Status::ErrorUnexpected(),
2961 UnwrapKey(blink::WebCryptoKeyFormatRaw,
2962 CryptoData(test_ciphertext),
2964 webcrypto::CreateAlgorithm(blink::WebCryptoAlgorithmIdAesCbc),
2965 webcrypto::CreateAlgorithm(blink::WebCryptoAlgorithmIdAesCbc),
2967 blink::WebCryptoKeyUsageEncrypt,
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(
2990 blink::WebCryptoKeyUsageWrapKey | blink::WebCryptoKeyUsageUnwrapKey);
2992 // Import the key to be wrapped.
2993 blink::WebCryptoKey key = ImportSecretKeyFromRaw(
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,
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();
3012 UnwrapKey(blink::WebCryptoKeyFormatRaw,
3013 CryptoData(test_ciphertext),
3016 CreateHmacImportAlgorithm(blink::WebCryptoAlgorithmIdSha1),
3018 blink::WebCryptoKeyUsageSign,
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
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();
3057 UnwrapKey(blink::WebCryptoKeyFormatRaw,
3058 CryptoData(test_ciphertext),
3061 CreateHmacImportAlgorithm(blink::WebCryptoAlgorithmIdSha1),
3063 blink::WebCryptoKeyUsageSign | blink::WebCryptoKeyUsageVerify,
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,
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),
3079 CryptoData(test_message),
3082 EXPECT_GT(signature.size(), 0u);
3085 ASSERT_EQ(Status::Success(),
3086 VerifySignature(CreateAlgorithm(blink::WebCryptoAlgorithmIdHmac),
3088 CryptoData(signature),
3089 CryptoData(test_message),
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(
3111 blink::WebCryptoKeyUsageWrapKey | blink::WebCryptoKeyUsageUnwrapKey);
3112 // Import the key to be wrapped.
3113 blink::WebCryptoKey key = ImportSecretKeyFromRaw(
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),
3129 blink::WebCryptoKeyUsageEncrypt,
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),
3142 blink::WebCryptoKeyUsageEncrypt,
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(
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();
3169 Status::OperationError(),
3170 UnwrapKey(blink::WebCryptoKeyFormatRaw,
3171 CryptoData(Corrupted(test_ciphertext)),
3174 webcrypto::CreateAlgorithm(blink::WebCryptoAlgorithmIdAesCbc),
3176 blink::WebCryptoKeyUsageEncrypt,
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();
3208 UnwrapKey(blink::WebCryptoKeyFormatJwk,
3209 CryptoData(wrapped_key_data),
3212 CreateHmacImportAlgorithm(blink::WebCryptoAlgorithmIdSha256),
3214 blink::WebCryptoKeyUsageVerify,
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);
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, MAYBE(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";
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 blink::WebCryptoKey key = ImportSecretKeyFromRaw(
3269 CreateAlgorithm(blink::WebCryptoAlgorithmIdAesGcm),
3270 blink::WebCryptoKeyUsageEncrypt | blink::WebCryptoKeyUsageDecrypt);
3272 // Verify exported raw key is identical to the imported data
3273 std::vector<uint8> raw_key;
3274 EXPECT_EQ(Status::Success(),
3275 ExportKey(blink::WebCryptoKeyFormatRaw, key, &raw_key));
3277 EXPECT_BYTES_EQ(test_key, raw_key);
3280 std::vector<uint8> cipher_text;
3281 std::vector<uint8> authentication_tag;
3282 EXPECT_EQ(Status::Success(),
3285 test_additional_data,
3289 &authentication_tag));
3291 EXPECT_BYTES_EQ(test_cipher_text, cipher_text);
3292 EXPECT_BYTES_EQ(test_authentication_tag, authentication_tag);
3295 std::vector<uint8> plain_text;
3296 EXPECT_EQ(Status::Success(),
3299 test_additional_data,
3302 test_authentication_tag,
3304 EXPECT_BYTES_EQ(test_plain_text, plain_text);
3306 // Decryption should fail if any of the inputs are tampered with.
3307 EXPECT_EQ(Status::OperationError(),
3310 test_additional_data,
3313 test_authentication_tag,
3315 EXPECT_EQ(Status::OperationError(),
3318 Corrupted(test_additional_data),
3321 test_authentication_tag,
3323 EXPECT_EQ(Status::OperationError(),
3326 test_additional_data,
3328 Corrupted(test_cipher_text),
3329 test_authentication_tag,
3331 EXPECT_EQ(Status::OperationError(),
3334 test_additional_data,
3337 Corrupted(test_authentication_tag),
3340 // Try different incorrect tag lengths
3341 uint8 kAlternateTagLengths[] = {0, 8, 96, 120, 128, 160, 255};
3342 for (size_t tag_i = 0; tag_i < arraysize(kAlternateTagLengths); ++tag_i) {
3343 unsigned int wrong_tag_size_bits = kAlternateTagLengths[tag_i];
3344 if (test_tag_size_bits == wrong_tag_size_bits)
3346 EXPECT_NE(Status::Success(),
3349 test_additional_data,
3350 wrong_tag_size_bits,
3352 test_authentication_tag,
3358 // AES 192-bit is not allowed: http://crbug.com/381829
3359 TEST_F(SharedCryptoTest, MAYBE(ImportAesCbc192Raw)) {
3360 std::vector<uint8> key_raw(24, 0);
3361 blink::WebCryptoKey key = blink::WebCryptoKey::createNull();
3362 Status status = ImportKey(blink::WebCryptoKeyFormatRaw,
3363 CryptoData(key_raw),
3364 CreateAlgorithm(blink::WebCryptoAlgorithmIdAesCbc),
3366 blink::WebCryptoKeyUsageEncrypt,
3368 ASSERT_EQ(Status::ErrorAes192BitUnsupported(), status);
3371 // AES 192-bit is not allowed: http://crbug.com/381829
3372 TEST_F(SharedCryptoTest, MAYBE(ImportAesCbc192Jwk)) {
3373 blink::WebCryptoKey key = blink::WebCryptoKey::createNull();
3375 base::DictionaryValue dict;
3376 dict.SetString("kty", "oct");
3377 dict.SetString("alg", "A192CBC");
3378 dict.SetString("k", "YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFh");
3381 Status::ErrorAes192BitUnsupported(),
3382 ImportKeyJwkFromDict(dict,
3383 CreateAlgorithm(blink::WebCryptoAlgorithmIdAesCbc),
3385 blink::WebCryptoKeyUsageEncrypt,
3389 // AES 192-bit is not allowed: http://crbug.com/381829
3390 TEST_F(SharedCryptoTest, MAYBE(GenerateAesCbc192)) {
3391 blink::WebCryptoKey key = blink::WebCryptoKey::createNull();
3392 Status status = GenerateSecretKey(CreateAesCbcKeyGenAlgorithm(192),
3394 blink::WebCryptoKeyUsageEncrypt,
3396 ASSERT_EQ(Status::ErrorAes192BitUnsupported(), status);
3399 // AES 192-bit is not allowed: http://crbug.com/381829
3400 TEST_F(SharedCryptoTest, MAYBE(UnwrapAesCbc192)) {
3401 std::vector<uint8> wrapping_key_data(16, 0);
3402 std::vector<uint8> wrapped_key = HexStringToBytes(
3403 "1A07ACAB6C906E50883173C29441DB1DE91D34F45C435B5F99C822867FB3956F");
3405 blink::WebCryptoKey wrapping_key =
3406 ImportSecretKeyFromRaw(wrapping_key_data,
3407 CreateAlgorithm(blink::WebCryptoAlgorithmIdAesKw),
3408 blink::WebCryptoKeyUsageUnwrapKey);
3410 blink::WebCryptoKey unwrapped_key = blink::WebCryptoKey::createNull();
3411 ASSERT_EQ(Status::ErrorAes192BitUnsupported(),
3412 UnwrapKey(blink::WebCryptoKeyFormatRaw,
3413 CryptoData(wrapped_key),
3415 CreateAlgorithm(blink::WebCryptoAlgorithmIdAesKw),
3416 CreateAlgorithm(blink::WebCryptoAlgorithmIdAesCbc),
3418 blink::WebCryptoKeyUsageEncrypt,
3422 class SharedCryptoRsaOaepTest : public ::testing::Test {
3424 SharedCryptoRsaOaepTest() { Init(); }
3426 scoped_ptr<base::DictionaryValue> CreatePublicKeyJwkDict() {
3427 scoped_ptr<base::DictionaryValue> jwk(new base::DictionaryValue());
3428 jwk->SetString("kty", "RSA");
3430 Base64EncodeUrlSafe(HexStringToBytes(kPublicKeyModulusHex)));
3432 "e", Base64EncodeUrlSafe(HexStringToBytes(kPublicKeyExponentHex)));
3437 // Import a PKCS#8 private key that uses RSAPrivateKey with the
3438 // id-rsaEncryption OID.
3439 TEST_F(SharedCryptoRsaOaepTest, ImportPkcs8WithRsaEncryption) {
3440 if (!SupportsRsaOaep()) {
3441 LOG(WARNING) << "RSA-OAEP support not present; skipping.";
3445 blink::WebCryptoKey private_key = blink::WebCryptoKey::createNull();
3446 ASSERT_EQ(Status::Success(),
3447 ImportKey(blink::WebCryptoKeyFormatPkcs8,
3448 CryptoData(HexStringToBytes(kPrivateKeyPkcs8DerHex)),
3449 CreateRsaHashedImportAlgorithm(
3450 blink::WebCryptoAlgorithmIdRsaOaep,
3451 blink::WebCryptoAlgorithmIdSha1),
3453 blink::WebCryptoKeyUsageDecrypt,
3457 TEST_F(SharedCryptoRsaOaepTest, ImportPublicJwkWithNoAlg) {
3458 if (!SupportsRsaOaep()) {
3459 LOG(WARNING) << "RSA-OAEP support not present; skipping.";
3463 scoped_ptr<base::DictionaryValue> jwk(CreatePublicKeyJwkDict());
3465 blink::WebCryptoKey public_key = blink::WebCryptoKey::createNull();
3466 ASSERT_EQ(Status::Success(),
3467 ImportKeyJwkFromDict(*jwk.get(),
3468 CreateRsaHashedImportAlgorithm(
3469 blink::WebCryptoAlgorithmIdRsaOaep,
3470 blink::WebCryptoAlgorithmIdSha1),
3472 blink::WebCryptoKeyUsageEncrypt,
3476 TEST_F(SharedCryptoRsaOaepTest, ImportPublicJwkWithMatchingAlg) {
3477 if (!SupportsRsaOaep()) {
3478 LOG(WARNING) << "RSA-OAEP support not present; skipping.";
3482 scoped_ptr<base::DictionaryValue> jwk(CreatePublicKeyJwkDict());
3483 jwk->SetString("alg", "RSA-OAEP");
3485 blink::WebCryptoKey public_key = blink::WebCryptoKey::createNull();
3486 ASSERT_EQ(Status::Success(),
3487 ImportKeyJwkFromDict(*jwk.get(),
3488 CreateRsaHashedImportAlgorithm(
3489 blink::WebCryptoAlgorithmIdRsaOaep,
3490 blink::WebCryptoAlgorithmIdSha1),
3492 blink::WebCryptoKeyUsageEncrypt,
3496 TEST_F(SharedCryptoRsaOaepTest, ImportPublicJwkWithMismatchedAlgFails) {
3497 if (!SupportsRsaOaep()) {
3498 LOG(WARNING) << "RSA-OAEP support not present; skipping.";
3502 scoped_ptr<base::DictionaryValue> jwk(CreatePublicKeyJwkDict());
3503 jwk->SetString("alg", "RSA-OAEP-512");
3505 blink::WebCryptoKey public_key = blink::WebCryptoKey::createNull();
3506 ASSERT_EQ(Status::ErrorJwkAlgorithmInconsistent(),
3507 ImportKeyJwkFromDict(*jwk.get(),
3508 CreateRsaHashedImportAlgorithm(
3509 blink::WebCryptoAlgorithmIdRsaOaep,
3510 blink::WebCryptoAlgorithmIdSha1),
3512 blink::WebCryptoKeyUsageEncrypt,
3516 TEST_F(SharedCryptoRsaOaepTest, ImportPublicJwkWithMismatchedTypeFails) {
3517 if (!SupportsRsaOaep()) {
3518 LOG(WARNING) << "RSA-OAEP support not present; skipping.";
3522 scoped_ptr<base::DictionaryValue> jwk(CreatePublicKeyJwkDict());
3523 jwk->SetString("kty", "oct");
3524 jwk->SetString("alg", "RSA-OAEP");
3526 blink::WebCryptoKey public_key = blink::WebCryptoKey::createNull();
3527 ASSERT_EQ(Status::ErrorJwkPropertyMissing("k"),
3528 ImportKeyJwkFromDict(*jwk.get(),
3529 CreateRsaHashedImportAlgorithm(
3530 blink::WebCryptoAlgorithmIdRsaOaep,
3531 blink::WebCryptoAlgorithmIdSha1),
3533 blink::WebCryptoKeyUsageEncrypt,
3537 TEST_F(SharedCryptoRsaOaepTest, ExportPublicJwk) {
3538 if (!SupportsRsaOaep()) {
3539 LOG(WARNING) << "RSA-OAEP support not present; skipping.";
3544 blink::WebCryptoAlgorithmId hash_alg;
3545 const char* expected_jwk_alg;
3546 } kTestData[] = {{blink::WebCryptoAlgorithmIdSha1, "RSA-OAEP"},
3547 {blink::WebCryptoAlgorithmIdSha256, "RSA-OAEP-256"},
3548 {blink::WebCryptoAlgorithmIdSha384, "RSA-OAEP-384"},
3549 {blink::WebCryptoAlgorithmIdSha512, "RSA-OAEP-512"}};
3550 for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kTestData); ++i) {
3551 const TestData& test_data = kTestData[i];
3552 SCOPED_TRACE(test_data.expected_jwk_alg);
3554 scoped_ptr<base::DictionaryValue> jwk(CreatePublicKeyJwkDict());
3555 jwk->SetString("alg", test_data.expected_jwk_alg);
3557 // Import the key in a known-good format
3558 blink::WebCryptoKey public_key = blink::WebCryptoKey::createNull();
3559 ASSERT_EQ(Status::Success(),
3560 ImportKeyJwkFromDict(
3562 CreateRsaHashedImportAlgorithm(
3563 blink::WebCryptoAlgorithmIdRsaOaep, test_data.hash_alg),
3565 blink::WebCryptoKeyUsageEncrypt,
3568 // Now export the key as JWK and verify its contents
3569 std::vector<uint8> jwk_data;
3570 ASSERT_EQ(Status::Success(),
3571 ExportKey(blink::WebCryptoKeyFormatJwk, public_key, &jwk_data));
3572 EXPECT_TRUE(VerifyPublicJwk(jwk_data,
3573 test_data.expected_jwk_alg,
3574 kPublicKeyModulusHex,
3575 kPublicKeyExponentHex,
3576 blink::WebCryptoKeyUsageEncrypt));
3580 TEST_F(SharedCryptoRsaOaepTest, EncryptDecryptKnownAnswerTest) {
3581 if (!SupportsRsaOaep()) {
3582 LOG(WARNING) << "RSA-OAEP support not present; skipping.";
3586 scoped_ptr<base::ListValue> tests;
3587 ASSERT_TRUE(ReadJsonTestFileToList("rsa_oaep.json", &tests));
3589 for (size_t test_index = 0; test_index < tests->GetSize(); ++test_index) {
3590 SCOPED_TRACE(test_index);
3592 base::DictionaryValue* test = NULL;
3593 ASSERT_TRUE(tests->GetDictionary(test_index, &test));
3595 blink::WebCryptoAlgorithm digest_algorithm =
3596 GetDigestAlgorithm(test, "hash");
3597 ASSERT_FALSE(digest_algorithm.isNull());
3598 std::vector<uint8> public_key_der =
3599 GetBytesFromHexString(test, "public_key");
3600 std::vector<uint8> private_key_der =
3601 GetBytesFromHexString(test, "private_key");
3602 std::vector<uint8> ciphertext = GetBytesFromHexString(test, "ciphertext");
3603 std::vector<uint8> plaintext = GetBytesFromHexString(test, "plaintext");
3604 std::vector<uint8> label = GetBytesFromHexString(test, "label");
3606 blink::WebCryptoAlgorithm import_algorithm = CreateRsaHashedImportAlgorithm(
3607 blink::WebCryptoAlgorithmIdRsaOaep, digest_algorithm.id());
3608 blink::WebCryptoKey public_key = blink::WebCryptoKey::createNull();
3609 blink::WebCryptoKey private_key = blink::WebCryptoKey::createNull();
3611 ASSERT_NO_FATAL_FAILURE(ImportRsaKeyPair(public_key_der,
3615 blink::WebCryptoKeyUsageEncrypt,
3616 blink::WebCryptoKeyUsageDecrypt,
3620 blink::WebCryptoAlgorithm op_algorithm = CreateRsaOaepAlgorithm(label);
3621 std::vector<uint8> decrypted_data;
3622 ASSERT_EQ(Status::Success(),
3623 Decrypt(op_algorithm,
3625 CryptoData(ciphertext),
3627 EXPECT_BYTES_EQ(plaintext, decrypted_data);
3628 std::vector<uint8> encrypted_data;
3632 op_algorithm, public_key, CryptoData(plaintext), &encrypted_data));
3633 std::vector<uint8> redecrypted_data;
3634 ASSERT_EQ(Status::Success(),
3635 Decrypt(op_algorithm,
3637 CryptoData(encrypted_data),
3638 &redecrypted_data));
3639 EXPECT_BYTES_EQ(plaintext, redecrypted_data);
3643 TEST_F(SharedCryptoRsaOaepTest, EncryptWithLargeMessageFails) {
3644 if (!SupportsRsaOaep()) {
3645 LOG(WARNING) << "RSA-OAEP support not present; skipping.";
3649 const blink::WebCryptoAlgorithmId kHash = blink::WebCryptoAlgorithmIdSha1;
3650 const size_t kHashSize = 20;
3652 scoped_ptr<base::DictionaryValue> jwk(CreatePublicKeyJwkDict());
3654 blink::WebCryptoKey public_key = blink::WebCryptoKey::createNull();
3655 ASSERT_EQ(Status::Success(),
3656 ImportKeyJwkFromDict(*jwk.get(),
3657 CreateRsaHashedImportAlgorithm(
3658 blink::WebCryptoAlgorithmIdRsaOaep, kHash),
3660 blink::WebCryptoKeyUsageEncrypt,
3663 // The maximum size of an encrypted message is:
3665 // - 1 (leading octet)
3666 // - hash size (maskedSeed)
3667 // - hash size (lHash portion of maskedDB)
3668 // - 1 (at least one octet for the padding string)
3669 size_t kMaxMessageSize = (kModulusLengthBits / 8) - 2 - (2 * kHashSize);
3671 // The label has no influence on the maximum message size. For simplicity,
3672 // use the empty string.
3673 std::vector<uint8> label;
3674 blink::WebCryptoAlgorithm op_algorithm = CreateRsaOaepAlgorithm(label);
3676 // Test that a message just before the boundary succeeds.
3677 std::string large_message;
3678 large_message.resize(kMaxMessageSize - 1, 'A');
3680 std::vector<uint8> ciphertext;
3684 op_algorithm, public_key, CryptoData(large_message), &ciphertext));
3686 // Test that a message at the boundary succeeds.
3687 large_message.resize(kMaxMessageSize, 'A');
3693 op_algorithm, public_key, CryptoData(large_message), &ciphertext));
3695 // Test that a message greater than the largest size fails.
3696 large_message.resize(kMaxMessageSize + 1, 'A');
3700 Status::OperationError(),
3702 op_algorithm, public_key, CryptoData(large_message), &ciphertext));
3705 // Ensures that if the selected hash algorithm for the RSA-OAEP message is too
3706 // large, then it is rejected, independent of the actual message to be
3708 // For example, a 1024-bit RSA key is too small to accomodate a message that
3709 // uses OAEP with SHA-512, since it requires 1040 bits to encode
3710 // (2 * hash size + 2 padding bytes).
3711 TEST_F(SharedCryptoRsaOaepTest, EncryptWithLargeDigestFails) {
3712 if (!SupportsRsaOaep()) {
3713 LOG(WARNING) << "RSA-OAEP support not present; skipping.";
3717 const blink::WebCryptoAlgorithmId kHash = blink::WebCryptoAlgorithmIdSha512;
3719 scoped_ptr<base::DictionaryValue> jwk(CreatePublicKeyJwkDict());
3721 blink::WebCryptoKey public_key = blink::WebCryptoKey::createNull();
3722 ASSERT_EQ(Status::Success(),
3723 ImportKeyJwkFromDict(*jwk.get(),
3724 CreateRsaHashedImportAlgorithm(
3725 blink::WebCryptoAlgorithmIdRsaOaep, kHash),
3727 blink::WebCryptoKeyUsageEncrypt,
3730 // The label has no influence on the maximum message size. For simplicity,
3731 // use the empty string.
3732 std::vector<uint8> label;
3733 blink::WebCryptoAlgorithm op_algorithm = CreateRsaOaepAlgorithm(label);
3735 std::string small_message("A");
3736 std::vector<uint8> ciphertext;
3737 // This is an operation error, as the internal consistency checking of the
3738 // algorithm parameters is up to the implementation.
3740 Status::OperationError(),
3742 op_algorithm, public_key, CryptoData(small_message), &ciphertext));
3745 TEST_F(SharedCryptoRsaOaepTest, DecryptWithLargeMessageFails) {
3746 if (!SupportsRsaOaep()) {
3747 LOG(WARNING) << "RSA-OAEP support not present; skipping.";
3751 blink::WebCryptoKey private_key = blink::WebCryptoKey::createNull();
3752 ASSERT_EQ(Status::Success(),
3753 ImportKey(blink::WebCryptoKeyFormatPkcs8,
3754 CryptoData(HexStringToBytes(kPrivateKeyPkcs8DerHex)),
3755 CreateRsaHashedImportAlgorithm(
3756 blink::WebCryptoAlgorithmIdRsaOaep,
3757 blink::WebCryptoAlgorithmIdSha1),
3759 blink::WebCryptoKeyUsageDecrypt,
3762 // The label has no influence on the maximum message size. For simplicity,
3763 // use the empty string.
3764 std::vector<uint8> label;
3765 blink::WebCryptoAlgorithm op_algorithm = CreateRsaOaepAlgorithm(label);
3767 std::string large_dummy_message(kModulusLengthBits / 8, 'A');
3768 std::vector<uint8> plaintext;
3770 ASSERT_EQ(Status::OperationError(),
3771 Decrypt(op_algorithm,
3773 CryptoData(large_dummy_message),
3777 TEST_F(SharedCryptoRsaOaepTest, WrapUnwrapRawKey) {
3778 if (!SupportsRsaOaep()) {
3779 LOG(WARNING) << "RSA-OAEP support not present; skipping.";
3783 blink::WebCryptoAlgorithm import_algorithm = CreateRsaHashedImportAlgorithm(
3784 blink::WebCryptoAlgorithmIdRsaOaep, blink::WebCryptoAlgorithmIdSha1);
3785 blink::WebCryptoKey public_key = blink::WebCryptoKey::createNull();
3786 blink::WebCryptoKey private_key = blink::WebCryptoKey::createNull();
3788 ASSERT_NO_FATAL_FAILURE(ImportRsaKeyPair(
3789 HexStringToBytes(kPublicKeySpkiDerHex),
3790 HexStringToBytes(kPrivateKeyPkcs8DerHex),
3793 blink::WebCryptoKeyUsageEncrypt | blink::WebCryptoKeyUsageWrapKey,
3794 blink::WebCryptoKeyUsageDecrypt | blink::WebCryptoKeyUsageUnwrapKey,
3798 std::vector<uint8> label;
3799 blink::WebCryptoAlgorithm wrapping_algorithm = CreateRsaOaepAlgorithm(label);
3801 const std::string key_hex = "000102030405060708090A0B0C0D0E0F";
3802 const blink::WebCryptoAlgorithm key_algorithm =
3803 webcrypto::CreateAlgorithm(blink::WebCryptoAlgorithmIdAesCbc);
3805 blink::WebCryptoKey key =
3806 ImportSecretKeyFromRaw(HexStringToBytes(key_hex),
3808 blink::WebCryptoKeyUsageEncrypt);
3809 ASSERT_FALSE(key.isNull());
3811 std::vector<uint8> wrapped_key;
3812 ASSERT_EQ(Status::Success(),
3813 WrapKey(blink::WebCryptoKeyFormatRaw,
3819 // Verify that |wrapped_key| can be decrypted and yields the key data.
3820 // Because |private_key| supports both decrypt and unwrap, this is valid.
3821 std::vector<uint8> decrypted_key;
3822 ASSERT_EQ(Status::Success(),
3823 Decrypt(wrapping_algorithm,
3825 CryptoData(wrapped_key),
3827 EXPECT_BYTES_EQ_HEX(key_hex, decrypted_key);
3829 // Now attempt to unwrap the key, which should also decrypt the data.
3830 blink::WebCryptoKey unwrapped_key = blink::WebCryptoKey::createNull();
3831 ASSERT_EQ(Status::Success(),
3832 UnwrapKey(blink::WebCryptoKeyFormatRaw,
3833 CryptoData(wrapped_key),
3838 blink::WebCryptoKeyUsageEncrypt,
3840 ASSERT_FALSE(unwrapped_key.isNull());
3842 std::vector<uint8> raw_key;
3843 ASSERT_EQ(Status::Success(),
3844 ExportKey(blink::WebCryptoKeyFormatRaw, unwrapped_key, &raw_key));
3845 EXPECT_BYTES_EQ_HEX(key_hex, raw_key);
3848 TEST_F(SharedCryptoRsaOaepTest, WrapUnwrapJwkSymKey) {
3849 if (!SupportsRsaOaep()) {
3850 LOG(WARNING) << "RSA-OAEP support not present; skipping.";
3854 // The public and private portions of a 2048-bit RSA key with the
3855 // id-rsaEncryption OID
3856 const char kPublicKey2048SpkiDerHex[] =
3857 "30820122300d06092a864886f70d01010105000382010f003082010a0282010100c5d8ce"
3858 "137a38168c8ab70229cfa5accc640567159750a312ce2e7d54b6e2fdd59b300c6a6c9764"
3859 "f8de6f00519cdb90111453d273a967462786480621f9e7cee5b73d63358448e7183a3a68"
3860 "e991186359f26aa88fbca5f53e673e502e4c5a2ba5068aeba60c9d0c44d872458d1b1e2f"
3861 "7f339f986076d516e93dc750f0b7680b6f5f02bc0d5590495be04c4ae59d34ba17bc5d08"
3862 "a93c75cfda2828f4a55b153af912038438276cb4a14f8116ca94db0ea9893652d02fc606"
3863 "36f19975e3d79a4d8ea8bfed6f8e0a24b63d243b08ea70a086ad56dd6341d733711c89ca"
3864 "749d4a80b3e6ecd2f8e53731eadeac2ea77788ee55d7b4b47c0f2523fbd61b557c16615d"
3866 const char kPrivateKey2048Pkcs8DerHex[] =
3867 "308204bd020100300d06092a864886f70d0101010500048204a7308204a3020100028201"
3868 "0100c5d8ce137a38168c8ab70229cfa5accc640567159750a312ce2e7d54b6e2fdd59b30"
3869 "0c6a6c9764f8de6f00519cdb90111453d273a967462786480621f9e7cee5b73d63358448"
3870 "e7183a3a68e991186359f26aa88fbca5f53e673e502e4c5a2ba5068aeba60c9d0c44d872"
3871 "458d1b1e2f7f339f986076d516e93dc750f0b7680b6f5f02bc0d5590495be04c4ae59d34"
3872 "ba17bc5d08a93c75cfda2828f4a55b153af912038438276cb4a14f8116ca94db0ea98936"
3873 "52d02fc60636f19975e3d79a4d8ea8bfed6f8e0a24b63d243b08ea70a086ad56dd6341d7"
3874 "33711c89ca749d4a80b3e6ecd2f8e53731eadeac2ea77788ee55d7b4b47c0f2523fbd61b"
3875 "557c16615d5d02030100010282010074b70feb41a0b0fcbc207670400556c9450042ede3"
3876 "d4383fb1ce8f3558a6d4641d26dd4c333fa4db842d2b9cf9d2354d3e16ad027a9f682d8c"
3877 "f4145a1ad97b9edcd8a41c402bd9d8db10f62f43df854cdccbbb2100834f083f53ed6d42"
3878 "b1b729a59072b004a4e945fc027db15e9c121d1251464d320d4774d5732df6b3dbf751f4"
3879 "9b19c9db201e19989c883bbaad5333db47f64f6f7a95b8d4936b10d945aa3f794cfaab62"
3880 "e7d47686129358914f3b8085f03698a650ab5b8c7e45813f2b0515ec05b6e5195b6a7c2a"
3881 "0d36969745f431ded4fd059f6aa361a4649541016d356297362b778e90f077d48815b339"
3882 "ec6f43aba345df93e67fcb6c2cb5b4544e9be902818100e9c90abe5f9f32468c5b6d630c"
3883 "54a4d7d75e29a72cf792f21e242aac78fd7995c42dfd4ae871d2619ff7096cb05baa78e3"
3884 "23ecab338401a8059adf7a0d8be3b21edc9a9c82c5605634a2ec81ec053271721351868a"
3885 "4c2e50c689d7cef94e31ff23658af5843366e2b289c5bf81d72756a7b93487dd8770d69c"
3886 "1f4e089d6d89f302818100d8a58a727c4e209132afd9933b98c89aca862a01cc0be74133"
3887 "bee517909e5c379e526895ac4af11780c1fe91194c777c9670b6423f0f5a32fd7691a622"
3888 "113eef4bed2ef863363a335fd55b0e75088c582437237d7f3ed3f0a643950237bc6e6277"
3889 "ccd0d0a1b4170aa1047aa7ffa7c8c54be10e8c7327ae2e0885663963817f6f02818100e5"
3890 "aed9ba4d71b7502e6748a1ce247ecb7bd10c352d6d9256031cdf3c11a65e44b0b7ca2945"
3891 "134671195af84c6b3bb3d10ebf65ae916f38bd5dbc59a0ad1c69b8beaf57cb3a8335f19b"
3892 "c7117b576987b48331cd9fd3d1a293436b7bb5e1a35c6560de4b5688ea834367cb0997eb"
3893 "b578f59ed4cb724c47dba94d3b484c1876dcd70281807f15bc7d2406007cac2b138a96af"
3894 "2d1e00276b84da593132c253fcb73212732dfd25824c2a615bc3d9b7f2c8d2fa542d3562"
3895 "b0c7738e61eeff580a6056239fb367ea9e5efe73d4f846033602e90c36a78db6fa8ea792"
3896 "0769675ec58e237bd994d189c8045a96f5dd3a4f12547257ce224e3c9af830a4da3c0eab"
3897 "9227a0035ae9028180067caea877e0b23090fc689322b71fbcce63d6596e66ab5fcdbaa0"
3898 "0d49e93aba8effb4518c2da637f209028401a68f344865b4956b032c69acde51d29177ca"
3899 "3db99fdbf5e74848ed4fa7bdfc2ebb60e2aaa5354770a763e1399ab7a2099762d525fea0"
3900 "37f3e1972c45a477e66db95c9609bb27f862700ef93379930786cf751b";
3901 blink::WebCryptoAlgorithm import_algorithm = CreateRsaHashedImportAlgorithm(
3902 blink::WebCryptoAlgorithmIdRsaOaep, blink::WebCryptoAlgorithmIdSha1);
3903 blink::WebCryptoKey public_key = blink::WebCryptoKey::createNull();
3904 blink::WebCryptoKey private_key = blink::WebCryptoKey::createNull();
3906 ASSERT_NO_FATAL_FAILURE(ImportRsaKeyPair(
3907 HexStringToBytes(kPublicKey2048SpkiDerHex),
3908 HexStringToBytes(kPrivateKey2048Pkcs8DerHex),
3911 blink::WebCryptoKeyUsageEncrypt | blink::WebCryptoKeyUsageWrapKey,
3912 blink::WebCryptoKeyUsageDecrypt | blink::WebCryptoKeyUsageUnwrapKey,
3916 std::vector<uint8> label;
3917 blink::WebCryptoAlgorithm wrapping_algorithm = CreateRsaOaepAlgorithm(label);
3919 const std::string key_hex = "000102030405060708090a0b0c0d0e0f";
3920 const blink::WebCryptoAlgorithm key_algorithm =
3921 webcrypto::CreateAlgorithm(blink::WebCryptoAlgorithmIdAesCbc);
3923 blink::WebCryptoKey key =
3924 ImportSecretKeyFromRaw(HexStringToBytes(key_hex),
3926 blink::WebCryptoKeyUsageEncrypt);
3927 ASSERT_FALSE(key.isNull());
3929 std::vector<uint8> wrapped_key;
3930 ASSERT_EQ(Status::Success(),
3931 WrapKey(blink::WebCryptoKeyFormatJwk,
3937 // Verify that |wrapped_key| can be decrypted and yields a valid JWK object.
3938 // Because |private_key| supports both decrypt and unwrap, this is valid.
3939 std::vector<uint8> decrypted_jwk;
3940 ASSERT_EQ(Status::Success(),
3941 Decrypt(wrapping_algorithm,
3943 CryptoData(wrapped_key),
3945 EXPECT_TRUE(VerifySecretJwk(
3946 decrypted_jwk, "A128CBC", key_hex, blink::WebCryptoKeyUsageEncrypt));
3948 // Now attempt to unwrap the key, which should also decrypt the data.
3949 blink::WebCryptoKey unwrapped_key = blink::WebCryptoKey::createNull();
3950 ASSERT_EQ(Status::Success(),
3951 UnwrapKey(blink::WebCryptoKeyFormatJwk,
3952 CryptoData(wrapped_key),
3957 blink::WebCryptoKeyUsageEncrypt,
3959 ASSERT_FALSE(unwrapped_key.isNull());
3961 std::vector<uint8> raw_key;
3962 ASSERT_EQ(Status::Success(),
3963 ExportKey(blink::WebCryptoKeyFormatRaw, unwrapped_key, &raw_key));
3964 EXPECT_BYTES_EQ_HEX(key_hex, raw_key);
3967 // Try importing an RSA-SSA public key with unsupported key usages using SPKI
3968 // format. RSA-SSA public keys only support the 'verify' usage.
3969 TEST_F(SharedCryptoTest, MAYBE(ImportRsaSsaPublicKeyBadUsage_SPKI)) {
3970 const blink::WebCryptoAlgorithm algorithm =
3971 CreateRsaHashedImportAlgorithm(blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
3972 blink::WebCryptoAlgorithmIdSha256);
3974 blink::WebCryptoKeyUsageMask bad_usages[] = {
3975 blink::WebCryptoKeyUsageSign,
3976 blink::WebCryptoKeyUsageSign | blink::WebCryptoKeyUsageVerify,
3977 blink::WebCryptoKeyUsageEncrypt,
3978 blink::WebCryptoKeyUsageEncrypt | blink::WebCryptoKeyUsageDecrypt,
3981 for (size_t i = 0; i < arraysize(bad_usages); ++i) {
3984 blink::WebCryptoKey public_key = blink::WebCryptoKey::createNull();
3985 ASSERT_EQ(Status::ErrorCreateKeyBadUsages(),
3986 ImportKey(blink::WebCryptoKeyFormatSpki,
3987 CryptoData(HexStringToBytes(kPublicKeySpkiDerHex)),
3995 // Try importing an RSA-SSA public key with unsupported key usages using JWK
3996 // format. RSA-SSA public keys only support the 'verify' usage.
3997 TEST_F(SharedCryptoTest, MAYBE(ImportRsaSsaPublicKeyBadUsage_JWK)) {
3998 const blink::WebCryptoAlgorithm algorithm =
3999 CreateRsaHashedImportAlgorithm(blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
4000 blink::WebCryptoAlgorithmIdSha256);
4002 blink::WebCryptoKeyUsageMask bad_usages[] = {
4003 blink::WebCryptoKeyUsageSign,
4004 blink::WebCryptoKeyUsageSign | blink::WebCryptoKeyUsageVerify,
4005 blink::WebCryptoKeyUsageEncrypt,
4006 blink::WebCryptoKeyUsageEncrypt | blink::WebCryptoKeyUsageDecrypt,
4009 base::DictionaryValue dict;
4010 RestoreJwkRsaDictionary(&dict);
4011 dict.Remove("use", NULL);
4012 dict.SetString("alg", "RS256");
4014 for (size_t i = 0; i < arraysize(bad_usages); ++i) {
4017 blink::WebCryptoKey public_key = blink::WebCryptoKey::createNull();
4018 ASSERT_EQ(Status::ErrorCreateKeyBadUsages(),
4019 ImportKeyJwkFromDict(
4020 dict, algorithm, false, bad_usages[i], &public_key));
4024 // Try importing an AES-CBC key with unsupported key usages using raw
4025 // format. AES-CBC keys support the following usages:
4026 // 'encrypt', 'decrypt', 'wrapKey', 'unwrapKey'
4027 TEST_F(SharedCryptoTest, MAYBE(ImportAesCbcKeyBadUsage_Raw)) {
4028 const blink::WebCryptoAlgorithm algorithm =
4029 CreateAlgorithm(blink::WebCryptoAlgorithmIdAesCbc);
4031 blink::WebCryptoKeyUsageMask bad_usages[] = {
4032 blink::WebCryptoKeyUsageSign,
4033 blink::WebCryptoKeyUsageSign | blink::WebCryptoKeyUsageDecrypt,
4034 blink::WebCryptoKeyUsageDeriveBits,
4035 blink::WebCryptoKeyUsageUnwrapKey | blink::WebCryptoKeyUsageVerify,
4038 std::vector<uint8> key_bytes(16);
4040 for (size_t i = 0; i < arraysize(bad_usages); ++i) {
4043 blink::WebCryptoKey key = blink::WebCryptoKey::createNull();
4044 ASSERT_EQ(Status::ErrorCreateKeyBadUsages(),
4045 ImportKey(blink::WebCryptoKeyFormatRaw,
4046 CryptoData(key_bytes),
4054 // Try importing an AES-KW key with unsupported key usages using raw
4055 // format. AES-KW keys support the following usages:
4056 // 'wrapKey', 'unwrapKey'
4057 TEST_F(SharedCryptoTest, MAYBE(ImportAesKwKeyBadUsage_Raw)) {
4058 const blink::WebCryptoAlgorithm algorithm =
4059 CreateAlgorithm(blink::WebCryptoAlgorithmIdAesKw);
4061 blink::WebCryptoKeyUsageMask bad_usages[] = {
4062 blink::WebCryptoKeyUsageEncrypt,
4063 blink::WebCryptoKeyUsageDecrypt,
4064 blink::WebCryptoKeyUsageSign,
4065 blink::WebCryptoKeyUsageSign | blink::WebCryptoKeyUsageUnwrapKey,
4066 blink::WebCryptoKeyUsageDeriveBits,
4067 blink::WebCryptoKeyUsageUnwrapKey | blink::WebCryptoKeyUsageVerify,
4070 std::vector<uint8> key_bytes(16);
4072 for (size_t i = 0; i < arraysize(bad_usages); ++i) {
4075 blink::WebCryptoKey key = blink::WebCryptoKey::createNull();
4076 ASSERT_EQ(Status::ErrorCreateKeyBadUsages(),
4077 ImportKey(blink::WebCryptoKeyFormatRaw,
4078 CryptoData(key_bytes),
4086 // Try unwrapping an HMAC key with unsupported usages using JWK format and
4087 // AES-KW. HMAC keys support the following usages:
4089 TEST_F(SharedCryptoTest, MAYBE(UnwrapHmacKeyBadUsage_JWK)) {
4090 const blink::WebCryptoAlgorithm unwrap_algorithm =
4091 CreateAlgorithm(blink::WebCryptoAlgorithmIdAesKw);
4093 blink::WebCryptoKeyUsageMask bad_usages[] = {
4094 blink::WebCryptoKeyUsageEncrypt,
4095 blink::WebCryptoKeyUsageDecrypt,
4096 blink::WebCryptoKeyUsageWrapKey,
4097 blink::WebCryptoKeyUsageSign | blink::WebCryptoKeyUsageWrapKey,
4098 blink::WebCryptoKeyUsageVerify | blink::WebCryptoKeyUsageDeriveKey,
4101 // Import the wrapping key.
4102 blink::WebCryptoKey wrapping_key = blink::WebCryptoKey::createNull();
4103 ASSERT_EQ(Status::Success(),
4104 ImportKey(blink::WebCryptoKeyFormatRaw,
4105 CryptoData(std::vector<uint8>(16)),
4108 blink::WebCryptoKeyUsageUnwrapKey,
4111 // The JWK plain text is:
4112 // { "kty": "oct","alg": "HS256","k": "GADWrMRHwQfoNaXU5fZvTg=="}
4113 const char* kWrappedJwk =
4114 "0AA245F17064FFB2A7A094436A39BEBFC962C627303D1327EA750CE9F917688C2782A943"
4115 "7AE7586547AC490E8AE7D5B02D63868D5C3BB57D36C4C8C5BF3962ACEC6F42E767E5706"
4118 for (size_t i = 0; i < arraysize(bad_usages); ++i) {
4121 blink::WebCryptoKey key = blink::WebCryptoKey::createNull();
4123 ASSERT_EQ(Status::ErrorCreateKeyBadUsages(),
4124 UnwrapKey(blink::WebCryptoKeyFormatJwk,
4125 CryptoData(HexStringToBytes(kWrappedJwk)),
4128 webcrypto::CreateHmacImportAlgorithm(
4129 blink::WebCryptoAlgorithmIdSha256),
4136 // Try unwrapping an RSA-SSA public key with unsupported usages using JWK format
4137 // and AES-KW. RSA-SSA public keys support the following usages:
4139 TEST_F(SharedCryptoTest, MAYBE(UnwrapRsaSsaPublicKeyBadUsage_JWK)) {
4140 const blink::WebCryptoAlgorithm unwrap_algorithm =
4141 CreateAlgorithm(blink::WebCryptoAlgorithmIdAesKw);
4143 blink::WebCryptoKeyUsageMask bad_usages[] = {
4144 blink::WebCryptoKeyUsageEncrypt,
4145 blink::WebCryptoKeyUsageSign,
4146 blink::WebCryptoKeyUsageDecrypt,
4147 blink::WebCryptoKeyUsageWrapKey,
4148 blink::WebCryptoKeyUsageSign | blink::WebCryptoKeyUsageWrapKey,
4151 // Import the wrapping key.
4152 blink::WebCryptoKey wrapping_key = blink::WebCryptoKey::createNull();
4153 ASSERT_EQ(Status::Success(),
4154 ImportKey(blink::WebCryptoKeyFormatRaw,
4155 CryptoData(std::vector<uint8>(16)),
4158 blink::WebCryptoKeyUsageUnwrapKey,
4161 // The JWK plaintext is:
4162 // { "kty": "RSA","alg": "RS256","n": "...","e": "AQAB"}
4164 const char* kWrappedJwk =
4165 "CE8DAEF99E977EE58958B8C4494755C846E883B2ECA575C5366622839AF71AB30875F152"
4166 "E8E33E15A7817A3A2874EB53EFE05C774D98BC936BA9BA29BEB8BB3F3C3CE2323CB3359D"
4167 "E3F426605CF95CCF0E01E870ABD7E35F62E030B5FB6E520A5885514D1D850FB64B57806D"
4168 "1ADA57C6E27DF345D8292D80F6B074F1BE51C4CF3D76ECC8886218551308681B44FAC60B"
4169 "8CF6EA439BC63239103D0AE81ADB96F908680586C6169284E32EB7DD09D31103EBDAC0C2"
4170 "40C72DCF0AEA454113CC47457B13305B25507CBEAB9BDC8D8E0F867F9167F9DCEF0D9F9B"
4171 "30F2EE83CEDFD51136852C8A5939B768";
4173 for (size_t i = 0; i < arraysize(bad_usages); ++i) {
4176 blink::WebCryptoKey key = blink::WebCryptoKey::createNull();
4178 ASSERT_EQ(Status::ErrorCreateKeyBadUsages(),
4179 UnwrapKey(blink::WebCryptoKeyFormatJwk,
4180 CryptoData(HexStringToBytes(kWrappedJwk)),
4183 webcrypto::CreateRsaHashedImportAlgorithm(
4184 blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
4185 blink::WebCryptoAlgorithmIdSha256),
4192 // Generate an AES-CBC key with invalid usages. AES-CBC supports:
4193 // 'encrypt', 'decrypt', 'wrapKey', 'unwrapKey'
4194 TEST_F(SharedCryptoTest, MAYBE(GenerateAesKeyBadUsages)) {
4195 blink::WebCryptoKeyUsageMask bad_usages[] = {
4196 blink::WebCryptoKeyUsageSign, blink::WebCryptoKeyUsageVerify,
4197 blink::WebCryptoKeyUsageDecrypt | blink::WebCryptoKeyUsageVerify,
4200 for (size_t i = 0; i < arraysize(bad_usages); ++i) {
4203 blink::WebCryptoKey key = blink::WebCryptoKey::createNull();
4205 ASSERT_EQ(Status::ErrorCreateKeyBadUsages(),
4207 CreateAesCbcKeyGenAlgorithm(128), true, bad_usages[i], &key));
4211 // Generate an RSA-SSA key pair with invalid usages. RSA-SSA supports:
4213 TEST_F(SharedCryptoTest, MAYBE(GenerateRsaSsaBadUsages)) {
4214 blink::WebCryptoKeyUsageMask bad_usages[] = {
4215 blink::WebCryptoKeyUsageDecrypt,
4216 blink::WebCryptoKeyUsageVerify | blink::WebCryptoKeyUsageDecrypt,
4217 blink::WebCryptoKeyUsageWrapKey,
4220 const unsigned int modulus_length = 256;
4221 const std::vector<uint8> public_exponent = HexStringToBytes("010001");
4223 for (size_t i = 0; i < arraysize(bad_usages); ++i) {
4226 blink::WebCryptoKey public_key = blink::WebCryptoKey::createNull();
4227 blink::WebCryptoKey private_key = blink::WebCryptoKey::createNull();
4229 ASSERT_EQ(Status::ErrorCreateKeyBadUsages(),
4230 GenerateKeyPair(CreateRsaHashedKeyGenAlgorithm(
4231 blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
4232 blink::WebCryptoAlgorithmIdSha256,
4242 // Generate an RSA-SSA key pair. The public and private keys should select the
4243 // key usages which are applicable, and not have the exact same usages as was
4244 // specified to GenerateKey
4245 TEST_F(SharedCryptoTest, MAYBE(GenerateRsaSsaKeyPairIntersectUsages)) {
4246 const unsigned int modulus_length = 256;
4247 const std::vector<uint8> public_exponent = HexStringToBytes("010001");
4249 blink::WebCryptoKey public_key = blink::WebCryptoKey::createNull();
4250 blink::WebCryptoKey private_key = blink::WebCryptoKey::createNull();
4252 ASSERT_EQ(Status::Success(),
4254 CreateRsaHashedKeyGenAlgorithm(
4255 blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
4256 blink::WebCryptoAlgorithmIdSha256,
4260 blink::WebCryptoKeyUsageSign | blink::WebCryptoKeyUsageVerify,
4264 EXPECT_EQ(blink::WebCryptoKeyUsageVerify, public_key.usages());
4265 EXPECT_EQ(blink::WebCryptoKeyUsageSign, private_key.usages());
4267 // Try again but this time without the Verify usages.
4268 ASSERT_EQ(Status::Success(),
4269 GenerateKeyPair(CreateRsaHashedKeyGenAlgorithm(
4270 blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
4271 blink::WebCryptoAlgorithmIdSha256,
4275 blink::WebCryptoKeyUsageSign,
4279 EXPECT_EQ(0, public_key.usages());
4280 EXPECT_EQ(blink::WebCryptoKeyUsageSign, private_key.usages());
4283 // Generate an AES-CBC key and an RSA key pair. Use the AES-CBC key to wrap the
4284 // key pair (using SPKI format for public key, PKCS8 format for private key).
4285 // Then unwrap the wrapped key pair and verify that the key data is the same.
4286 TEST_F(SharedCryptoTest, MAYBE(WrapUnwrapRoundtripSpkiPkcs8UsingAesCbc)) {
4287 if (!SupportsRsaKeyImport())
4290 // Generate the wrapping key.
4291 blink::WebCryptoKey wrapping_key = blink::WebCryptoKey::createNull();
4292 ASSERT_EQ(Status::Success(),
4293 GenerateSecretKey(CreateAesCbcKeyGenAlgorithm(128),
4295 blink::WebCryptoKeyUsageWrapKey |
4296 blink::WebCryptoKeyUsageUnwrapKey,
4299 // Generate an RSA key pair to be wrapped.
4300 const unsigned int modulus_length = 256;
4301 const std::vector<uint8> public_exponent = HexStringToBytes("010001");
4303 blink::WebCryptoKey public_key = blink::WebCryptoKey::createNull();
4304 blink::WebCryptoKey private_key = blink::WebCryptoKey::createNull();
4305 ASSERT_EQ(Status::Success(),
4306 GenerateKeyPair(CreateRsaHashedKeyGenAlgorithm(
4307 blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
4308 blink::WebCryptoAlgorithmIdSha256,
4316 // Export key pair as SPKI + PKCS8
4317 std::vector<uint8> public_key_spki;
4320 ExportKey(blink::WebCryptoKeyFormatSpki, public_key, &public_key_spki));
4322 std::vector<uint8> private_key_pkcs8;
4326 blink::WebCryptoKeyFormatPkcs8, private_key, &private_key_pkcs8));
4328 // Wrap the key pair.
4329 blink::WebCryptoAlgorithm wrap_algorithm =
4330 CreateAesCbcAlgorithm(std::vector<uint8>(16, 0));
4332 std::vector<uint8> wrapped_public_key;
4333 ASSERT_EQ(Status::Success(),
4334 WrapKey(blink::WebCryptoKeyFormatSpki,
4338 &wrapped_public_key));
4340 std::vector<uint8> wrapped_private_key;
4341 ASSERT_EQ(Status::Success(),
4342 WrapKey(blink::WebCryptoKeyFormatPkcs8,
4346 &wrapped_private_key));
4348 // Unwrap the key pair.
4349 blink::WebCryptoAlgorithm rsa_import_algorithm =
4350 CreateRsaHashedImportAlgorithm(blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5,
4351 blink::WebCryptoAlgorithmIdSha256);
4353 blink::WebCryptoKey unwrapped_public_key = blink::WebCryptoKey::createNull();
4355 ASSERT_EQ(Status::Success(),
4356 UnwrapKey(blink::WebCryptoKeyFormatSpki,
4357 CryptoData(wrapped_public_key),
4360 rsa_import_algorithm,
4363 &unwrapped_public_key));
4365 blink::WebCryptoKey unwrapped_private_key = blink::WebCryptoKey::createNull();
4367 ASSERT_EQ(Status::Success(),
4368 UnwrapKey(blink::WebCryptoKeyFormatPkcs8,
4369 CryptoData(wrapped_private_key),
4372 rsa_import_algorithm,
4375 &unwrapped_private_key));
4377 // Export unwrapped key pair as SPKI + PKCS8
4378 std::vector<uint8> unwrapped_public_key_spki;
4379 ASSERT_EQ(Status::Success(),
4380 ExportKey(blink::WebCryptoKeyFormatSpki,
4381 unwrapped_public_key,
4382 &unwrapped_public_key_spki));
4384 std::vector<uint8> unwrapped_private_key_pkcs8;
4385 ASSERT_EQ(Status::Success(),
4386 ExportKey(blink::WebCryptoKeyFormatPkcs8,
4387 unwrapped_private_key,
4388 &unwrapped_private_key_pkcs8));
4390 EXPECT_EQ(public_key_spki, unwrapped_public_key_spki);
4391 EXPECT_EQ(private_key_pkcs8, unwrapped_private_key_pkcs8);
4393 EXPECT_NE(public_key_spki, wrapped_public_key);
4394 EXPECT_NE(private_key_pkcs8, wrapped_private_key);
4397 } // namespace webcrypto
4399 } // namespace content