Home | History | Annotate | Download | only in test
      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.
      4 
      5 #include "content/child/webcrypto/test/test_helpers.h"
      6 
      7 #include <algorithm>
      8 
      9 #include "base/files/file_util.h"
     10 #include "base/json/json_reader.h"
     11 #include "base/json/json_writer.h"
     12 #include "base/logging.h"
     13 #include "base/path_service.h"
     14 #include "base/stl_util.h"
     15 #include "base/strings/string_number_conversions.h"
     16 #include "base/strings/string_util.h"
     17 #include "base/values.h"
     18 #include "content/child/webcrypto/algorithm_dispatch.h"
     19 #include "content/child/webcrypto/crypto_data.h"
     20 #include "content/child/webcrypto/jwk.h"
     21 #include "content/child/webcrypto/status.h"
     22 #include "content/child/webcrypto/webcrypto_util.h"
     23 #include "content/public/common/content_paths.h"
     24 #include "third_party/WebKit/public/platform/WebCryptoAlgorithmParams.h"
     25 #include "third_party/WebKit/public/platform/WebCryptoKeyAlgorithm.h"
     26 #include "third_party/re2/re2/re2.h"
     27 
     28 #if !defined(USE_OPENSSL)
     29 #include <nss.h>
     30 #include <pk11pub.h>
     31 
     32 #include "crypto/nss_util.h"
     33 #include "crypto/scoped_nss_types.h"
     34 #endif
     35 
     36 namespace content {
     37 
     38 namespace webcrypto {
     39 
     40 void PrintTo(const Status& status, ::std::ostream* os) {
     41   if (status.IsSuccess())
     42     *os << "Success";
     43   else
     44     *os << "Error type: " << status.error_type()
     45         << " Error details: " << status.error_details();
     46 }
     47 
     48 bool operator==(const Status& a, const Status& b) {
     49   if (a.IsSuccess() != b.IsSuccess())
     50     return false;
     51   if (a.IsSuccess())
     52     return true;
     53   return a.error_type() == b.error_type() &&
     54          a.error_details() == b.error_details();
     55 }
     56 
     57 bool operator!=(const Status& a, const Status& b) {
     58   return !(a == b);
     59 }
     60 
     61 void PrintTo(const CryptoData& data, ::std::ostream* os) {
     62   *os << "[" << base::HexEncode(data.bytes(), data.byte_length()) << "]";
     63 }
     64 
     65 bool operator==(const CryptoData& a, const CryptoData& b) {
     66   return a.byte_length() == b.byte_length() &&
     67          memcmp(a.bytes(), b.bytes(), a.byte_length()) == 0;
     68 }
     69 
     70 bool operator!=(const CryptoData& a, const CryptoData& b) {
     71   return !(a == b);
     72 }
     73 
     74 bool SupportsAesGcm() {
     75   std::vector<uint8_t> key_raw(16, 0);
     76 
     77   blink::WebCryptoKey key = blink::WebCryptoKey::createNull();
     78   Status status = ImportKey(blink::WebCryptoKeyFormatRaw,
     79                             CryptoData(key_raw),
     80                             CreateAlgorithm(blink::WebCryptoAlgorithmIdAesGcm),
     81                             true,
     82                             blink::WebCryptoKeyUsageEncrypt,
     83                             &key);
     84 
     85   if (status.IsError())
     86     EXPECT_EQ(blink::WebCryptoErrorTypeNotSupported, status.error_type());
     87   return status.IsSuccess();
     88 }
     89 
     90 bool SupportsRsaOaep() {
     91 #if defined(USE_OPENSSL)
     92   return true;
     93 #else
     94   crypto::EnsureNSSInit();
     95   // TODO(eroman): Exclude version test for OS_CHROMEOS
     96 #if defined(USE_NSS)
     97   if (!NSS_VersionCheck("3.16.2"))
     98     return false;
     99 #endif
    100   crypto::ScopedPK11Slot slot(PK11_GetInternalKeySlot());
    101   return !!PK11_DoesMechanism(slot.get(), CKM_RSA_PKCS_OAEP);
    102 #endif
    103 }
    104 
    105 bool SupportsRsaPrivateKeyImport() {
    106 // TODO(eroman): Exclude version test for OS_CHROMEOS
    107 #if defined(USE_NSS)
    108   crypto::EnsureNSSInit();
    109   if (!NSS_VersionCheck("3.16.2")) {
    110     LOG(WARNING) << "RSA key import is not supported by this version of NSS. "
    111                     "Skipping some tests";
    112     return false;
    113   }
    114 #endif
    115   return true;
    116 }
    117 
    118 blink::WebCryptoAlgorithm CreateRsaHashedKeyGenAlgorithm(
    119     blink::WebCryptoAlgorithmId algorithm_id,
    120     const blink::WebCryptoAlgorithmId hash_id,
    121     unsigned int modulus_length,
    122     const std::vector<uint8_t>& public_exponent) {
    123   DCHECK(algorithm_id == blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5 ||
    124          algorithm_id == blink::WebCryptoAlgorithmIdRsaOaep);
    125   DCHECK(blink::WebCryptoAlgorithm::isHash(hash_id));
    126   return blink::WebCryptoAlgorithm::adoptParamsAndCreate(
    127       algorithm_id,
    128       new blink::WebCryptoRsaHashedKeyGenParams(
    129           CreateAlgorithm(hash_id),
    130           modulus_length,
    131           vector_as_array(&public_exponent),
    132           public_exponent.size()));
    133 }
    134 
    135 std::vector<uint8_t> Corrupted(const std::vector<uint8_t>& input) {
    136   std::vector<uint8_t> corrupted_data(input);
    137   if (corrupted_data.empty())
    138     corrupted_data.push_back(0);
    139   corrupted_data[corrupted_data.size() / 2] ^= 0x01;
    140   return corrupted_data;
    141 }
    142 
    143 std::vector<uint8_t> HexStringToBytes(const std::string& hex) {
    144   std::vector<uint8_t> bytes;
    145   base::HexStringToBytes(hex, &bytes);
    146   return bytes;
    147 }
    148 
    149 std::vector<uint8_t> MakeJsonVector(const std::string& json_string) {
    150   return std::vector<uint8_t>(json_string.begin(), json_string.end());
    151 }
    152 
    153 std::vector<uint8_t> MakeJsonVector(const base::DictionaryValue& dict) {
    154   std::string json;
    155   base::JSONWriter::Write(&dict, &json);
    156   return MakeJsonVector(json);
    157 }
    158 
    159 ::testing::AssertionResult ReadJsonTestFile(const char* test_file_name,
    160                                             scoped_ptr<base::Value>* value) {
    161   base::FilePath test_data_dir;
    162   if (!PathService::Get(DIR_TEST_DATA, &test_data_dir))
    163     return ::testing::AssertionFailure() << "Couldn't retrieve test dir";
    164 
    165   base::FilePath file_path =
    166       test_data_dir.AppendASCII("webcrypto").AppendASCII(test_file_name);
    167 
    168   std::string file_contents;
    169   if (!base::ReadFileToString(file_path, &file_contents)) {
    170     return ::testing::AssertionFailure()
    171            << "Couldn't read test file: " << file_path.value();
    172   }
    173 
    174   // Strip C++ style comments out of the "json" file, otherwise it cannot be
    175   // parsed.
    176   re2::RE2::GlobalReplace(&file_contents, re2::RE2("\\s*//.*"), "");
    177 
    178   // Parse the JSON to a dictionary.
    179   value->reset(base::JSONReader::Read(file_contents));
    180   if (!value->get()) {
    181     return ::testing::AssertionFailure()
    182            << "Couldn't parse test file JSON: " << file_path.value();
    183   }
    184 
    185   return ::testing::AssertionSuccess();
    186 }
    187 
    188 ::testing::AssertionResult ReadJsonTestFileToList(
    189     const char* test_file_name,
    190     scoped_ptr<base::ListValue>* list) {
    191   // Read the JSON.
    192   scoped_ptr<base::Value> json;
    193   ::testing::AssertionResult result = ReadJsonTestFile(test_file_name, &json);
    194   if (!result)
    195     return result;
    196 
    197   // Cast to an ListValue.
    198   base::ListValue* list_value = NULL;
    199   if (!json->GetAsList(&list_value) || !list_value)
    200     return ::testing::AssertionFailure() << "The JSON was not a list";
    201 
    202   list->reset(list_value);
    203   ignore_result(json.release());
    204 
    205   return ::testing::AssertionSuccess();
    206 }
    207 
    208 std::vector<uint8_t> GetBytesFromHexString(base::DictionaryValue* dict,
    209                                            const char* property_name) {
    210   std::string hex_string;
    211   if (!dict->GetString(property_name, &hex_string)) {
    212     EXPECT_TRUE(false) << "Couldn't get string property: " << property_name;
    213     return std::vector<uint8_t>();
    214   }
    215 
    216   return HexStringToBytes(hex_string);
    217 }
    218 
    219 blink::WebCryptoAlgorithm GetDigestAlgorithm(base::DictionaryValue* dict,
    220                                              const char* property_name) {
    221   std::string algorithm_name;
    222   if (!dict->GetString(property_name, &algorithm_name)) {
    223     EXPECT_TRUE(false) << "Couldn't get string property: " << property_name;
    224     return blink::WebCryptoAlgorithm::createNull();
    225   }
    226 
    227   struct {
    228     const char* name;
    229     blink::WebCryptoAlgorithmId id;
    230   } kDigestNameToId[] = {
    231         {"sha-1", blink::WebCryptoAlgorithmIdSha1},
    232         {"sha-256", blink::WebCryptoAlgorithmIdSha256},
    233         {"sha-384", blink::WebCryptoAlgorithmIdSha384},
    234         {"sha-512", blink::WebCryptoAlgorithmIdSha512},
    235     };
    236 
    237   for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kDigestNameToId); ++i) {
    238     if (kDigestNameToId[i].name == algorithm_name)
    239       return CreateAlgorithm(kDigestNameToId[i].id);
    240   }
    241 
    242   return blink::WebCryptoAlgorithm::createNull();
    243 }
    244 
    245 // Creates a comparator for |bufs| which operates on indices rather than values.
    246 class CompareUsingIndex {
    247  public:
    248   explicit CompareUsingIndex(const std::vector<std::vector<uint8_t> >* bufs)
    249       : bufs_(bufs) {}
    250 
    251   bool operator()(size_t i1, size_t i2) { return (*bufs_)[i1] < (*bufs_)[i2]; }
    252 
    253  private:
    254   const std::vector<std::vector<uint8_t> >* bufs_;
    255 };
    256 
    257 bool CopiesExist(const std::vector<std::vector<uint8_t> >& bufs) {
    258   // Sort the indices of |bufs| into a separate vector. This reduces the amount
    259   // of data copied versus sorting |bufs| directly.
    260   std::vector<size_t> sorted_indices(bufs.size());
    261   for (size_t i = 0; i < sorted_indices.size(); ++i)
    262     sorted_indices[i] = i;
    263   std::sort(
    264       sorted_indices.begin(), sorted_indices.end(), CompareUsingIndex(&bufs));
    265 
    266   // Scan for adjacent duplicates.
    267   for (size_t i = 1; i < sorted_indices.size(); ++i) {
    268     if (bufs[sorted_indices[i]] == bufs[sorted_indices[i - 1]])
    269       return true;
    270   }
    271   return false;
    272 }
    273 
    274 blink::WebCryptoAlgorithm CreateAesKeyGenAlgorithm(
    275     blink::WebCryptoAlgorithmId aes_alg_id,
    276     unsigned short length) {
    277   return blink::WebCryptoAlgorithm::adoptParamsAndCreate(
    278       aes_alg_id, new blink::WebCryptoAesKeyGenParams(length));
    279 }
    280 
    281 // The following key pair is comprised of the SPKI (public key) and PKCS#8
    282 // (private key) representations of the key pair provided in Example 1 of the
    283 // NIST test vectors at
    284 // ftp://ftp.rsa.com/pub/rsalabs/tmp/pkcs1v15sign-vectors.txt
    285 const unsigned int kModulusLengthBits = 1024;
    286 const char* const kPublicKeySpkiDerHex =
    287     "30819f300d06092a864886f70d010101050003818d0030818902818100a5"
    288     "6e4a0e701017589a5187dc7ea841d156f2ec0e36ad52a44dfeb1e61f7ad9"
    289     "91d8c51056ffedb162b4c0f283a12a88a394dff526ab7291cbb307ceabfc"
    290     "e0b1dfd5cd9508096d5b2b8b6df5d671ef6377c0921cb23c270a70e2598e"
    291     "6ff89d19f105acc2d3f0cb35f29280e1386b6f64c4ef22e1e1f20d0ce8cf"
    292     "fb2249bd9a21370203010001";
    293 const char* const kPrivateKeyPkcs8DerHex =
    294     "30820275020100300d06092a864886f70d01010105000482025f3082025b"
    295     "02010002818100a56e4a0e701017589a5187dc7ea841d156f2ec0e36ad52"
    296     "a44dfeb1e61f7ad991d8c51056ffedb162b4c0f283a12a88a394dff526ab"
    297     "7291cbb307ceabfce0b1dfd5cd9508096d5b2b8b6df5d671ef6377c0921c"
    298     "b23c270a70e2598e6ff89d19f105acc2d3f0cb35f29280e1386b6f64c4ef"
    299     "22e1e1f20d0ce8cffb2249bd9a2137020301000102818033a5042a90b27d"
    300     "4f5451ca9bbbd0b44771a101af884340aef9885f2a4bbe92e894a724ac3c"
    301     "568c8f97853ad07c0266c8c6a3ca0929f1e8f11231884429fc4d9ae55fee"
    302     "896a10ce707c3ed7e734e44727a39574501a532683109c2abacaba283c31"
    303     "b4bd2f53c3ee37e352cee34f9e503bd80c0622ad79c6dcee883547c6a3b3"
    304     "25024100e7e8942720a877517273a356053ea2a1bc0c94aa72d55c6e8629"
    305     "6b2dfc967948c0a72cbccca7eacb35706e09a1df55a1535bd9b3cc34160b"
    306     "3b6dcd3eda8e6443024100b69dca1cf7d4d7ec81e75b90fcca874abcde12"
    307     "3fd2700180aa90479b6e48de8d67ed24f9f19d85ba275874f542cd20dc72"
    308     "3e6963364a1f9425452b269a6799fd024028fa13938655be1f8a159cbaca"
    309     "5a72ea190c30089e19cd274a556f36c4f6e19f554b34c077790427bbdd8d"
    310     "d3ede2448328f385d81b30e8e43b2fffa02786197902401a8b38f398fa71"
    311     "2049898d7fb79ee0a77668791299cdfa09efc0e507acb21ed74301ef5bfd"
    312     "48be455eaeb6e1678255827580a8e4e8e14151d1510a82a3f2e729024027"
    313     "156aba4126d24a81f3a528cbfb27f56886f840a9f6e86e17a44b94fe9319"
    314     "584b8e22fdde1e5a2e3bd8aa5ba8d8584194eb2190acf832b847f13a3d24"
    315     "a79f4d";
    316 // The modulus and exponent (in hex) of kPublicKeySpkiDerHex
    317 const char* const kPublicKeyModulusHex =
    318     "A56E4A0E701017589A5187DC7EA841D156F2EC0E36AD52A44DFEB1E61F7AD991D8C51056"
    319     "FFEDB162B4C0F283A12A88A394DFF526AB7291CBB307CEABFCE0B1DFD5CD9508096D5B2B"
    320     "8B6DF5D671EF6377C0921CB23C270A70E2598E6FF89D19F105ACC2D3F0CB35F29280E138"
    321     "6B6F64C4EF22E1E1F20D0CE8CFFB2249BD9A2137";
    322 const char* const kPublicKeyExponentHex = "010001";
    323 
    324 blink::WebCryptoKey ImportSecretKeyFromRaw(
    325     const std::vector<uint8_t>& key_raw,
    326     const blink::WebCryptoAlgorithm& algorithm,
    327     blink::WebCryptoKeyUsageMask usage) {
    328   blink::WebCryptoKey key = blink::WebCryptoKey::createNull();
    329   bool extractable = true;
    330   EXPECT_EQ(Status::Success(),
    331             ImportKey(blink::WebCryptoKeyFormatRaw,
    332                       CryptoData(key_raw),
    333                       algorithm,
    334                       extractable,
    335                       usage,
    336                       &key));
    337 
    338   EXPECT_FALSE(key.isNull());
    339   EXPECT_TRUE(key.handle());
    340   EXPECT_EQ(blink::WebCryptoKeyTypeSecret, key.type());
    341   EXPECT_EQ(algorithm.id(), key.algorithm().id());
    342   EXPECT_EQ(extractable, key.extractable());
    343   EXPECT_EQ(usage, key.usages());
    344   return key;
    345 }
    346 
    347 void ImportRsaKeyPair(const std::vector<uint8_t>& spki_der,
    348                       const std::vector<uint8_t>& pkcs8_der,
    349                       const blink::WebCryptoAlgorithm& algorithm,
    350                       bool extractable,
    351                       blink::WebCryptoKeyUsageMask public_key_usage_mask,
    352                       blink::WebCryptoKeyUsageMask private_key_usage_mask,
    353                       blink::WebCryptoKey* public_key,
    354                       blink::WebCryptoKey* private_key) {
    355   ASSERT_EQ(Status::Success(),
    356             ImportKey(blink::WebCryptoKeyFormatSpki,
    357                       CryptoData(spki_der),
    358                       algorithm,
    359                       true,
    360                       public_key_usage_mask,
    361                       public_key));
    362   EXPECT_FALSE(public_key->isNull());
    363   EXPECT_TRUE(public_key->handle());
    364   EXPECT_EQ(blink::WebCryptoKeyTypePublic, public_key->type());
    365   EXPECT_EQ(algorithm.id(), public_key->algorithm().id());
    366   EXPECT_TRUE(public_key->extractable());
    367   EXPECT_EQ(public_key_usage_mask, public_key->usages());
    368 
    369   ASSERT_EQ(Status::Success(),
    370             ImportKey(blink::WebCryptoKeyFormatPkcs8,
    371                       CryptoData(pkcs8_der),
    372                       algorithm,
    373                       extractable,
    374                       private_key_usage_mask,
    375                       private_key));
    376   EXPECT_FALSE(private_key->isNull());
    377   EXPECT_TRUE(private_key->handle());
    378   EXPECT_EQ(blink::WebCryptoKeyTypePrivate, private_key->type());
    379   EXPECT_EQ(algorithm.id(), private_key->algorithm().id());
    380   EXPECT_EQ(extractable, private_key->extractable());
    381   EXPECT_EQ(private_key_usage_mask, private_key->usages());
    382 }
    383 
    384 Status ImportKeyJwkFromDict(const base::DictionaryValue& dict,
    385                             const blink::WebCryptoAlgorithm& algorithm,
    386                             bool extractable,
    387                             blink::WebCryptoKeyUsageMask usage_mask,
    388                             blink::WebCryptoKey* key) {
    389   return ImportKey(blink::WebCryptoKeyFormatJwk,
    390                    CryptoData(MakeJsonVector(dict)),
    391                    algorithm,
    392                    extractable,
    393                    usage_mask,
    394                    key);
    395 }
    396 
    397 scoped_ptr<base::DictionaryValue> GetJwkDictionary(
    398     const std::vector<uint8_t>& json) {
    399   base::StringPiece json_string(
    400       reinterpret_cast<const char*>(vector_as_array(&json)), json.size());
    401   base::Value* value = base::JSONReader::Read(json_string);
    402   EXPECT_TRUE(value);
    403   base::DictionaryValue* dict_value = NULL;
    404   value->GetAsDictionary(&dict_value);
    405   return scoped_ptr<base::DictionaryValue>(dict_value);
    406 }
    407 
    408 // Verifies the input dictionary contains the expected values. Exact matches are
    409 // required on the fields examined.
    410 ::testing::AssertionResult VerifyJwk(
    411     const scoped_ptr<base::DictionaryValue>& dict,
    412     const std::string& kty_expected,
    413     const std::string& alg_expected,
    414     blink::WebCryptoKeyUsageMask use_mask_expected) {
    415   // ---- kty
    416   std::string value_string;
    417   if (!dict->GetString("kty", &value_string))
    418     return ::testing::AssertionFailure() << "Missing 'kty'";
    419   if (value_string != kty_expected)
    420     return ::testing::AssertionFailure() << "Expected 'kty' to be "
    421                                          << kty_expected << "but found "
    422                                          << value_string;
    423 
    424   // ---- alg
    425   if (!dict->GetString("alg", &value_string))
    426     return ::testing::AssertionFailure() << "Missing 'alg'";
    427   if (value_string != alg_expected)
    428     return ::testing::AssertionFailure() << "Expected 'alg' to be "
    429                                          << alg_expected << " but found "
    430                                          << value_string;
    431 
    432   // ---- ext
    433   // always expect ext == true in this case
    434   bool ext_value;
    435   if (!dict->GetBoolean("ext", &ext_value))
    436     return ::testing::AssertionFailure() << "Missing 'ext'";
    437   if (!ext_value)
    438     return ::testing::AssertionFailure()
    439            << "Expected 'ext' to be true but found false";
    440 
    441   // ---- key_ops
    442   base::ListValue* key_ops;
    443   if (!dict->GetList("key_ops", &key_ops))
    444     return ::testing::AssertionFailure() << "Missing 'key_ops'";
    445   blink::WebCryptoKeyUsageMask key_ops_mask = 0;
    446   Status status = GetWebCryptoUsagesFromJwkKeyOps(key_ops, &key_ops_mask);
    447   if (status.IsError())
    448     return ::testing::AssertionFailure() << "Failure extracting 'key_ops'";
    449   if (key_ops_mask != use_mask_expected)
    450     return ::testing::AssertionFailure()
    451            << "Expected 'key_ops' mask to be " << use_mask_expected
    452            << " but found " << key_ops_mask << " (" << value_string << ")";
    453 
    454   return ::testing::AssertionSuccess();
    455 }
    456 
    457 ::testing::AssertionResult VerifySecretJwk(
    458     const std::vector<uint8_t>& json,
    459     const std::string& alg_expected,
    460     const std::string& k_expected_hex,
    461     blink::WebCryptoKeyUsageMask use_mask_expected) {
    462   scoped_ptr<base::DictionaryValue> dict = GetJwkDictionary(json);
    463   if (!dict.get() || dict->empty())
    464     return ::testing::AssertionFailure() << "JSON parsing failed";
    465 
    466   // ---- k
    467   std::string value_string;
    468   if (!dict->GetString("k", &value_string))
    469     return ::testing::AssertionFailure() << "Missing 'k'";
    470   std::string k_value;
    471   if (!Base64DecodeUrlSafe(value_string, &k_value))
    472     return ::testing::AssertionFailure() << "Base64DecodeUrlSafe(k) failed";
    473   if (!LowerCaseEqualsASCII(base::HexEncode(k_value.data(), k_value.size()),
    474                             k_expected_hex.c_str())) {
    475     return ::testing::AssertionFailure() << "Expected 'k' to be "
    476                                          << k_expected_hex
    477                                          << " but found something different";
    478   }
    479 
    480   return VerifyJwk(dict, "oct", alg_expected, use_mask_expected);
    481 }
    482 
    483 ::testing::AssertionResult VerifyPublicJwk(
    484     const std::vector<uint8_t>& json,
    485     const std::string& alg_expected,
    486     const std::string& n_expected_hex,
    487     const std::string& e_expected_hex,
    488     blink::WebCryptoKeyUsageMask use_mask_expected) {
    489   scoped_ptr<base::DictionaryValue> dict = GetJwkDictionary(json);
    490   if (!dict.get() || dict->empty())
    491     return ::testing::AssertionFailure() << "JSON parsing failed";
    492 
    493   // ---- n
    494   std::string value_string;
    495   if (!dict->GetString("n", &value_string))
    496     return ::testing::AssertionFailure() << "Missing 'n'";
    497   std::string n_value;
    498   if (!Base64DecodeUrlSafe(value_string, &n_value))
    499     return ::testing::AssertionFailure() << "Base64DecodeUrlSafe(n) failed";
    500   if (base::HexEncode(n_value.data(), n_value.size()) != n_expected_hex) {
    501     return ::testing::AssertionFailure() << "'n' does not match the expected "
    502                                             "value";
    503   }
    504   // TODO(padolph): LowerCaseEqualsASCII() does not work for above!
    505 
    506   // ---- e
    507   if (!dict->GetString("e", &value_string))
    508     return ::testing::AssertionFailure() << "Missing 'e'";
    509   std::string e_value;
    510   if (!Base64DecodeUrlSafe(value_string, &e_value))
    511     return ::testing::AssertionFailure() << "Base64DecodeUrlSafe(e) failed";
    512   if (!LowerCaseEqualsASCII(base::HexEncode(e_value.data(), e_value.size()),
    513                             e_expected_hex.c_str())) {
    514     return ::testing::AssertionFailure() << "Expected 'e' to be "
    515                                          << e_expected_hex
    516                                          << " but found something different";
    517   }
    518 
    519   return VerifyJwk(dict, "RSA", alg_expected, use_mask_expected);
    520 }
    521 
    522 void ImportExportJwkSymmetricKey(
    523     int key_len_bits,
    524     const blink::WebCryptoAlgorithm& import_algorithm,
    525     blink::WebCryptoKeyUsageMask usages,
    526     const std::string& jwk_alg) {
    527   std::vector<uint8_t> json;
    528   std::string key_hex;
    529 
    530   // Hardcoded pseudo-random bytes to use for keys of different lengths.
    531   switch (key_len_bits) {
    532     case 128:
    533       key_hex = "3f1e7cd4f6f8543f6b1e16002e688623";
    534       break;
    535     case 256:
    536       key_hex =
    537           "bd08286b81a74783fd1ccf46b7e05af84ee25ae021210074159e0c4d9d907692";
    538       break;
    539     case 384:
    540       key_hex =
    541           "a22c5441c8b185602283d64c7221de1d0951e706bfc09539435ec0e0ed614e1d40"
    542           "6623f2b31d31819fec30993380dd82";
    543       break;
    544     case 512:
    545       key_hex =
    546           "5834f639000d4cf82de124fbfd26fb88d463e99f839a76ba41ac88967c80a3f61e"
    547           "1239a452e573dba0750e988152988576efd75b8d0229b7aca2ada2afd392ee";
    548       break;
    549     default:
    550       FAIL() << "Unexpected key_len_bits" << key_len_bits;
    551   }
    552 
    553   // Import a raw key.
    554   blink::WebCryptoKey key = ImportSecretKeyFromRaw(
    555       HexStringToBytes(key_hex), import_algorithm, usages);
    556 
    557   // Export the key in JWK format and validate.
    558   ASSERT_EQ(Status::Success(),
    559             ExportKey(blink::WebCryptoKeyFormatJwk, key, &json));
    560   EXPECT_TRUE(VerifySecretJwk(json, jwk_alg, key_hex, usages));
    561 
    562   // Import the JWK-formatted key.
    563   ASSERT_EQ(Status::Success(),
    564             ImportKey(blink::WebCryptoKeyFormatJwk,
    565                       CryptoData(json),
    566                       import_algorithm,
    567                       true,
    568                       usages,
    569                       &key));
    570   EXPECT_TRUE(key.handle());
    571   EXPECT_EQ(blink::WebCryptoKeyTypeSecret, key.type());
    572   EXPECT_EQ(import_algorithm.id(), key.algorithm().id());
    573   EXPECT_EQ(true, key.extractable());
    574   EXPECT_EQ(usages, key.usages());
    575 
    576   // Export the key in raw format and compare to the original.
    577   std::vector<uint8_t> key_raw_out;
    578   ASSERT_EQ(Status::Success(),
    579             ExportKey(blink::WebCryptoKeyFormatRaw, key, &key_raw_out));
    580   EXPECT_BYTES_EQ_HEX(key_hex, key_raw_out);
    581 }
    582 
    583 }  // namespace webcrypto
    584 
    585 }  // namesapce content
    586