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/test/test_helpers.h"
9 #include "base/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/status.h"
21 #include "content/child/webcrypto/webcrypto_util.h"
22 #include "content/public/common/content_paths.h"
23 #include "third_party/WebKit/public/platform/WebCryptoAlgorithmParams.h"
24 #include "third_party/WebKit/public/platform/WebCryptoKeyAlgorithm.h"
25 #include "third_party/re2/re2/re2.h"
27 #if !defined(USE_OPENSSL)
31 #include "crypto/nss_util.h"
32 #include "crypto/scoped_nss_types.h"
39 void PrintTo(const Status
& status
, ::std::ostream
* os
) {
40 if (status
.IsSuccess())
43 *os
<< "Error type: " << status
.error_type()
44 << " Error details: " << status
.error_details();
47 bool operator==(const Status
& a
, const Status
& b
) {
48 if (a
.IsSuccess() != b
.IsSuccess())
52 return a
.error_type() == b
.error_type() &&
53 a
.error_details() == b
.error_details();
56 bool operator!=(const Status
& a
, const Status
& b
) {
60 void PrintTo(const CryptoData
& data
, ::std::ostream
* os
) {
61 *os
<< "[" << base::HexEncode(data
.bytes(), data
.byte_length()) << "]";
64 bool operator==(const CryptoData
& a
, const CryptoData
& b
) {
65 return a
.byte_length() == b
.byte_length() &&
66 memcmp(a
.bytes(), b
.bytes(), a
.byte_length()) == 0;
69 bool operator!=(const CryptoData
& a
, const CryptoData
& b
) {
73 bool SupportsAesGcm() {
74 std::vector
<uint8_t> key_raw(16, 0);
76 blink::WebCryptoKey key
= blink::WebCryptoKey::createNull();
77 Status status
= ImportKey(blink::WebCryptoKeyFormatRaw
,
79 CreateAlgorithm(blink::WebCryptoAlgorithmIdAesGcm
),
81 blink::WebCryptoKeyUsageEncrypt
,
85 EXPECT_EQ(blink::WebCryptoErrorTypeNotSupported
, status
.error_type());
86 return status
.IsSuccess();
89 bool SupportsRsaOaep() {
90 #if defined(USE_OPENSSL)
93 crypto::EnsureNSSInit();
94 // TODO(eroman): Exclude version test for OS_CHROMEOS
96 if (!NSS_VersionCheck("3.16.2"))
99 crypto::ScopedPK11Slot
slot(PK11_GetInternalKeySlot());
100 return !!PK11_DoesMechanism(slot
.get(), CKM_RSA_PKCS_OAEP
);
104 bool SupportsRsaPrivateKeyImport() {
105 // TODO(eroman): Exclude version test for OS_CHROMEOS
107 crypto::EnsureNSSInit();
108 if (!NSS_VersionCheck("3.16.2")) {
109 LOG(WARNING
) << "RSA key import is not supported by this version of NSS. "
110 "Skipping some tests";
117 blink::WebCryptoAlgorithm
CreateRsaHashedKeyGenAlgorithm(
118 blink::WebCryptoAlgorithmId algorithm_id
,
119 const blink::WebCryptoAlgorithmId hash_id
,
120 unsigned int modulus_length
,
121 const std::vector
<uint8_t>& public_exponent
) {
122 DCHECK(algorithm_id
== blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5
||
123 algorithm_id
== blink::WebCryptoAlgorithmIdRsaOaep
);
124 DCHECK(blink::WebCryptoAlgorithm::isHash(hash_id
));
125 return blink::WebCryptoAlgorithm::adoptParamsAndCreate(
127 new blink::WebCryptoRsaHashedKeyGenParams(
128 CreateAlgorithm(hash_id
),
130 vector_as_array(&public_exponent
),
131 public_exponent
.size()));
134 std::vector
<uint8_t> Corrupted(const std::vector
<uint8_t>& input
) {
135 std::vector
<uint8_t> corrupted_data(input
);
136 if (corrupted_data
.empty())
137 corrupted_data
.push_back(0);
138 corrupted_data
[corrupted_data
.size() / 2] ^= 0x01;
139 return corrupted_data
;
142 std::vector
<uint8_t> HexStringToBytes(const std::string
& hex
) {
143 std::vector
<uint8_t> bytes
;
144 base::HexStringToBytes(hex
, &bytes
);
148 std::vector
<uint8_t> MakeJsonVector(const std::string
& json_string
) {
149 return std::vector
<uint8_t>(json_string
.begin(), json_string
.end());
152 std::vector
<uint8_t> MakeJsonVector(const base::DictionaryValue
& dict
) {
154 base::JSONWriter::Write(&dict
, &json
);
155 return MakeJsonVector(json
);
158 ::testing::AssertionResult
ReadJsonTestFile(const char* test_file_name
,
159 scoped_ptr
<base::Value
>* value
) {
160 base::FilePath test_data_dir
;
161 if (!PathService::Get(DIR_TEST_DATA
, &test_data_dir
))
162 return ::testing::AssertionFailure() << "Couldn't retrieve test dir";
164 base::FilePath file_path
=
165 test_data_dir
.AppendASCII("webcrypto").AppendASCII(test_file_name
);
167 std::string file_contents
;
168 if (!base::ReadFileToString(file_path
, &file_contents
)) {
169 return ::testing::AssertionFailure()
170 << "Couldn't read test file: " << file_path
.value();
173 // Strip C++ style comments out of the "json" file, otherwise it cannot be
175 re2::RE2::GlobalReplace(&file_contents
, re2::RE2("\\s*//.*"), "");
177 // Parse the JSON to a dictionary.
178 value
->reset(base::JSONReader::Read(file_contents
));
180 return ::testing::AssertionFailure()
181 << "Couldn't parse test file JSON: " << file_path
.value();
184 return ::testing::AssertionSuccess();
187 ::testing::AssertionResult
ReadJsonTestFileToList(
188 const char* test_file_name
,
189 scoped_ptr
<base::ListValue
>* list
) {
191 scoped_ptr
<base::Value
> json
;
192 ::testing::AssertionResult result
= ReadJsonTestFile(test_file_name
, &json
);
196 // Cast to an ListValue.
197 base::ListValue
* list_value
= NULL
;
198 if (!json
->GetAsList(&list_value
) || !list_value
)
199 return ::testing::AssertionFailure() << "The JSON was not a list";
201 list
->reset(list_value
);
202 ignore_result(json
.release());
204 return ::testing::AssertionSuccess();
207 std::vector
<uint8_t> GetBytesFromHexString(base::DictionaryValue
* dict
,
208 const char* property_name
) {
209 std::string hex_string
;
210 if (!dict
->GetString(property_name
, &hex_string
)) {
211 EXPECT_TRUE(false) << "Couldn't get string property: " << property_name
;
212 return std::vector
<uint8_t>();
215 return HexStringToBytes(hex_string
);
218 blink::WebCryptoAlgorithm
GetDigestAlgorithm(base::DictionaryValue
* dict
,
219 const char* property_name
) {
220 std::string algorithm_name
;
221 if (!dict
->GetString(property_name
, &algorithm_name
)) {
222 EXPECT_TRUE(false) << "Couldn't get string property: " << property_name
;
223 return blink::WebCryptoAlgorithm::createNull();
228 blink::WebCryptoAlgorithmId id
;
229 } kDigestNameToId
[] = {
230 {"sha-1", blink::WebCryptoAlgorithmIdSha1
},
231 {"sha-256", blink::WebCryptoAlgorithmIdSha256
},
232 {"sha-384", blink::WebCryptoAlgorithmIdSha384
},
233 {"sha-512", blink::WebCryptoAlgorithmIdSha512
},
236 for (size_t i
= 0; i
< ARRAYSIZE_UNSAFE(kDigestNameToId
); ++i
) {
237 if (kDigestNameToId
[i
].name
== algorithm_name
)
238 return CreateAlgorithm(kDigestNameToId
[i
].id
);
241 return blink::WebCryptoAlgorithm::createNull();
244 // Creates a comparator for |bufs| which operates on indices rather than values.
245 class CompareUsingIndex
{
247 explicit CompareUsingIndex(const std::vector
<std::vector
<uint8_t> >* bufs
)
250 bool operator()(size_t i1
, size_t i2
) { return (*bufs_
)[i1
] < (*bufs_
)[i2
]; }
253 const std::vector
<std::vector
<uint8_t> >* bufs_
;
256 bool CopiesExist(const std::vector
<std::vector
<uint8_t> >& bufs
) {
257 // Sort the indices of |bufs| into a separate vector. This reduces the amount
258 // of data copied versus sorting |bufs| directly.
259 std::vector
<size_t> sorted_indices(bufs
.size());
260 for (size_t i
= 0; i
< sorted_indices
.size(); ++i
)
261 sorted_indices
[i
] = i
;
263 sorted_indices
.begin(), sorted_indices
.end(), CompareUsingIndex(&bufs
));
265 // Scan for adjacent duplicates.
266 for (size_t i
= 1; i
< sorted_indices
.size(); ++i
) {
267 if (bufs
[sorted_indices
[i
]] == bufs
[sorted_indices
[i
- 1]])
273 blink::WebCryptoAlgorithm
CreateAesKeyGenAlgorithm(
274 blink::WebCryptoAlgorithmId aes_alg_id
,
275 unsigned short length
) {
276 return blink::WebCryptoAlgorithm::adoptParamsAndCreate(
277 aes_alg_id
, new blink::WebCryptoAesKeyGenParams(length
));
280 // The following key pair is comprised of the SPKI (public key) and PKCS#8
281 // (private key) representations of the key pair provided in Example 1 of the
282 // NIST test vectors at
283 // ftp://ftp.rsa.com/pub/rsalabs/tmp/pkcs1v15sign-vectors.txt
284 const unsigned int kModulusLengthBits
= 1024;
285 const char* const kPublicKeySpkiDerHex
=
286 "30819f300d06092a864886f70d010101050003818d0030818902818100a5"
287 "6e4a0e701017589a5187dc7ea841d156f2ec0e36ad52a44dfeb1e61f7ad9"
288 "91d8c51056ffedb162b4c0f283a12a88a394dff526ab7291cbb307ceabfc"
289 "e0b1dfd5cd9508096d5b2b8b6df5d671ef6377c0921cb23c270a70e2598e"
290 "6ff89d19f105acc2d3f0cb35f29280e1386b6f64c4ef22e1e1f20d0ce8cf"
291 "fb2249bd9a21370203010001";
292 const char* const kPrivateKeyPkcs8DerHex
=
293 "30820275020100300d06092a864886f70d01010105000482025f3082025b"
294 "02010002818100a56e4a0e701017589a5187dc7ea841d156f2ec0e36ad52"
295 "a44dfeb1e61f7ad991d8c51056ffedb162b4c0f283a12a88a394dff526ab"
296 "7291cbb307ceabfce0b1dfd5cd9508096d5b2b8b6df5d671ef6377c0921c"
297 "b23c270a70e2598e6ff89d19f105acc2d3f0cb35f29280e1386b6f64c4ef"
298 "22e1e1f20d0ce8cffb2249bd9a2137020301000102818033a5042a90b27d"
299 "4f5451ca9bbbd0b44771a101af884340aef9885f2a4bbe92e894a724ac3c"
300 "568c8f97853ad07c0266c8c6a3ca0929f1e8f11231884429fc4d9ae55fee"
301 "896a10ce707c3ed7e734e44727a39574501a532683109c2abacaba283c31"
302 "b4bd2f53c3ee37e352cee34f9e503bd80c0622ad79c6dcee883547c6a3b3"
303 "25024100e7e8942720a877517273a356053ea2a1bc0c94aa72d55c6e8629"
304 "6b2dfc967948c0a72cbccca7eacb35706e09a1df55a1535bd9b3cc34160b"
305 "3b6dcd3eda8e6443024100b69dca1cf7d4d7ec81e75b90fcca874abcde12"
306 "3fd2700180aa90479b6e48de8d67ed24f9f19d85ba275874f542cd20dc72"
307 "3e6963364a1f9425452b269a6799fd024028fa13938655be1f8a159cbaca"
308 "5a72ea190c30089e19cd274a556f36c4f6e19f554b34c077790427bbdd8d"
309 "d3ede2448328f385d81b30e8e43b2fffa02786197902401a8b38f398fa71"
310 "2049898d7fb79ee0a77668791299cdfa09efc0e507acb21ed74301ef5bfd"
311 "48be455eaeb6e1678255827580a8e4e8e14151d1510a82a3f2e729024027"
312 "156aba4126d24a81f3a528cbfb27f56886f840a9f6e86e17a44b94fe9319"
313 "584b8e22fdde1e5a2e3bd8aa5ba8d8584194eb2190acf832b847f13a3d24"
315 // The modulus and exponent (in hex) of kPublicKeySpkiDerHex
316 const char* const kPublicKeyModulusHex
=
317 "A56E4A0E701017589A5187DC7EA841D156F2EC0E36AD52A44DFEB1E61F7AD991D8C51056"
318 "FFEDB162B4C0F283A12A88A394DFF526AB7291CBB307CEABFCE0B1DFD5CD9508096D5B2B"
319 "8B6DF5D671EF6377C0921CB23C270A70E2598E6FF89D19F105ACC2D3F0CB35F29280E138"
320 "6B6F64C4EF22E1E1F20D0CE8CFFB2249BD9A2137";
321 const char* const kPublicKeyExponentHex
= "010001";
323 blink::WebCryptoKey
ImportSecretKeyFromRaw(
324 const std::vector
<uint8_t>& key_raw
,
325 const blink::WebCryptoAlgorithm
& algorithm
,
326 blink::WebCryptoKeyUsageMask usage
) {
327 blink::WebCryptoKey key
= blink::WebCryptoKey::createNull();
328 bool extractable
= true;
329 EXPECT_EQ(Status::Success(),
330 ImportKey(blink::WebCryptoKeyFormatRaw
,
337 EXPECT_FALSE(key
.isNull());
338 EXPECT_TRUE(key
.handle());
339 EXPECT_EQ(blink::WebCryptoKeyTypeSecret
, key
.type());
340 EXPECT_EQ(algorithm
.id(), key
.algorithm().id());
341 EXPECT_EQ(extractable
, key
.extractable());
342 EXPECT_EQ(usage
, key
.usages());
346 void ImportRsaKeyPair(const std::vector
<uint8_t>& spki_der
,
347 const std::vector
<uint8_t>& pkcs8_der
,
348 const blink::WebCryptoAlgorithm
& algorithm
,
350 blink::WebCryptoKeyUsageMask public_key_usage_mask
,
351 blink::WebCryptoKeyUsageMask private_key_usage_mask
,
352 blink::WebCryptoKey
* public_key
,
353 blink::WebCryptoKey
* private_key
) {
354 ASSERT_EQ(Status::Success(),
355 ImportKey(blink::WebCryptoKeyFormatSpki
,
356 CryptoData(spki_der
),
359 public_key_usage_mask
,
361 EXPECT_FALSE(public_key
->isNull());
362 EXPECT_TRUE(public_key
->handle());
363 EXPECT_EQ(blink::WebCryptoKeyTypePublic
, public_key
->type());
364 EXPECT_EQ(algorithm
.id(), public_key
->algorithm().id());
365 EXPECT_TRUE(public_key
->extractable());
366 EXPECT_EQ(public_key_usage_mask
, public_key
->usages());
368 ASSERT_EQ(Status::Success(),
369 ImportKey(blink::WebCryptoKeyFormatPkcs8
,
370 CryptoData(pkcs8_der
),
373 private_key_usage_mask
,
375 EXPECT_FALSE(private_key
->isNull());
376 EXPECT_TRUE(private_key
->handle());
377 EXPECT_EQ(blink::WebCryptoKeyTypePrivate
, private_key
->type());
378 EXPECT_EQ(algorithm
.id(), private_key
->algorithm().id());
379 EXPECT_EQ(extractable
, private_key
->extractable());
380 EXPECT_EQ(private_key_usage_mask
, private_key
->usages());
383 Status
ImportKeyJwkFromDict(const base::DictionaryValue
& dict
,
384 const blink::WebCryptoAlgorithm
& algorithm
,
386 blink::WebCryptoKeyUsageMask usage_mask
,
387 blink::WebCryptoKey
* key
) {
388 return ImportKey(blink::WebCryptoKeyFormatJwk
,
389 CryptoData(MakeJsonVector(dict
)),
396 scoped_ptr
<base::DictionaryValue
> GetJwkDictionary(
397 const std::vector
<uint8_t>& json
) {
398 base::StringPiece
json_string(
399 reinterpret_cast<const char*>(vector_as_array(&json
)), json
.size());
400 base::Value
* value
= base::JSONReader::Read(json_string
);
402 base::DictionaryValue
* dict_value
= NULL
;
403 value
->GetAsDictionary(&dict_value
);
404 return scoped_ptr
<base::DictionaryValue
>(dict_value
);
407 // Verifies the input dictionary contains the expected values. Exact matches are
408 // required on the fields examined.
409 ::testing::AssertionResult
VerifyJwk(
410 const scoped_ptr
<base::DictionaryValue
>& dict
,
411 const std::string
& kty_expected
,
412 const std::string
& alg_expected
,
413 blink::WebCryptoKeyUsageMask use_mask_expected
) {
415 std::string value_string
;
416 if (!dict
->GetString("kty", &value_string
))
417 return ::testing::AssertionFailure() << "Missing 'kty'";
418 if (value_string
!= kty_expected
)
419 return ::testing::AssertionFailure() << "Expected 'kty' to be "
420 << kty_expected
<< "but found "
424 if (!dict
->GetString("alg", &value_string
))
425 return ::testing::AssertionFailure() << "Missing 'alg'";
426 if (value_string
!= alg_expected
)
427 return ::testing::AssertionFailure() << "Expected 'alg' to be "
428 << alg_expected
<< " but found "
432 // always expect ext == true in this case
434 if (!dict
->GetBoolean("ext", &ext_value
))
435 return ::testing::AssertionFailure() << "Missing 'ext'";
437 return ::testing::AssertionFailure()
438 << "Expected 'ext' to be true but found false";
441 base::ListValue
* key_ops
;
442 if (!dict
->GetList("key_ops", &key_ops
))
443 return ::testing::AssertionFailure() << "Missing 'key_ops'";
444 blink::WebCryptoKeyUsageMask key_ops_mask
= 0;
445 Status status
= GetWebCryptoUsagesFromJwkKeyOps(key_ops
, &key_ops_mask
);
446 if (status
.IsError())
447 return ::testing::AssertionFailure() << "Failure extracting 'key_ops'";
448 if (key_ops_mask
!= use_mask_expected
)
449 return ::testing::AssertionFailure()
450 << "Expected 'key_ops' mask to be " << use_mask_expected
451 << " but found " << key_ops_mask
<< " (" << value_string
<< ")";
453 return ::testing::AssertionSuccess();
456 ::testing::AssertionResult
VerifySecretJwk(
457 const std::vector
<uint8_t>& json
,
458 const std::string
& alg_expected
,
459 const std::string
& k_expected_hex
,
460 blink::WebCryptoKeyUsageMask use_mask_expected
) {
461 scoped_ptr
<base::DictionaryValue
> dict
= GetJwkDictionary(json
);
462 if (!dict
.get() || dict
->empty())
463 return ::testing::AssertionFailure() << "JSON parsing failed";
466 std::string value_string
;
467 if (!dict
->GetString("k", &value_string
))
468 return ::testing::AssertionFailure() << "Missing 'k'";
470 if (!Base64DecodeUrlSafe(value_string
, &k_value
))
471 return ::testing::AssertionFailure() << "Base64DecodeUrlSafe(k) failed";
472 if (!LowerCaseEqualsASCII(base::HexEncode(k_value
.data(), k_value
.size()),
473 k_expected_hex
.c_str())) {
474 return ::testing::AssertionFailure() << "Expected 'k' to be "
476 << " but found something different";
479 return VerifyJwk(dict
, "oct", alg_expected
, use_mask_expected
);
482 ::testing::AssertionResult
VerifyPublicJwk(
483 const std::vector
<uint8_t>& json
,
484 const std::string
& alg_expected
,
485 const std::string
& n_expected_hex
,
486 const std::string
& e_expected_hex
,
487 blink::WebCryptoKeyUsageMask use_mask_expected
) {
488 scoped_ptr
<base::DictionaryValue
> dict
= GetJwkDictionary(json
);
489 if (!dict
.get() || dict
->empty())
490 return ::testing::AssertionFailure() << "JSON parsing failed";
493 std::string value_string
;
494 if (!dict
->GetString("n", &value_string
))
495 return ::testing::AssertionFailure() << "Missing 'n'";
497 if (!Base64DecodeUrlSafe(value_string
, &n_value
))
498 return ::testing::AssertionFailure() << "Base64DecodeUrlSafe(n) failed";
499 if (base::HexEncode(n_value
.data(), n_value
.size()) != n_expected_hex
) {
500 return ::testing::AssertionFailure() << "'n' does not match the expected "
503 // TODO(padolph): LowerCaseEqualsASCII() does not work for above!
506 if (!dict
->GetString("e", &value_string
))
507 return ::testing::AssertionFailure() << "Missing 'e'";
509 if (!Base64DecodeUrlSafe(value_string
, &e_value
))
510 return ::testing::AssertionFailure() << "Base64DecodeUrlSafe(e) failed";
511 if (!LowerCaseEqualsASCII(base::HexEncode(e_value
.data(), e_value
.size()),
512 e_expected_hex
.c_str())) {
513 return ::testing::AssertionFailure() << "Expected 'e' to be "
515 << " but found something different";
518 return VerifyJwk(dict
, "RSA", alg_expected
, use_mask_expected
);
521 void ImportExportJwkSymmetricKey(
523 const blink::WebCryptoAlgorithm
& import_algorithm
,
524 blink::WebCryptoKeyUsageMask usages
,
525 const std::string
& jwk_alg
) {
526 std::vector
<uint8_t> json
;
529 // Hardcoded pseudo-random bytes to use for keys of different lengths.
530 switch (key_len_bits
) {
532 key_hex
= "3f1e7cd4f6f8543f6b1e16002e688623";
536 "bd08286b81a74783fd1ccf46b7e05af84ee25ae021210074159e0c4d9d907692";
540 "a22c5441c8b185602283d64c7221de1d0951e706bfc09539435ec0e0ed614e1d40"
541 "6623f2b31d31819fec30993380dd82";
545 "5834f639000d4cf82de124fbfd26fb88d463e99f839a76ba41ac88967c80a3f61e"
546 "1239a452e573dba0750e988152988576efd75b8d0229b7aca2ada2afd392ee";
549 FAIL() << "Unexpected key_len_bits" << key_len_bits
;
553 blink::WebCryptoKey key
= ImportSecretKeyFromRaw(
554 HexStringToBytes(key_hex
), import_algorithm
, usages
);
556 // Export the key in JWK format and validate.
557 ASSERT_EQ(Status::Success(),
558 ExportKey(blink::WebCryptoKeyFormatJwk
, key
, &json
));
559 EXPECT_TRUE(VerifySecretJwk(json
, jwk_alg
, key_hex
, usages
));
561 // Import the JWK-formatted key.
562 ASSERT_EQ(Status::Success(),
563 ImportKey(blink::WebCryptoKeyFormatJwk
,
569 EXPECT_TRUE(key
.handle());
570 EXPECT_EQ(blink::WebCryptoKeyTypeSecret
, key
.type());
571 EXPECT_EQ(import_algorithm
.id(), key
.algorithm().id());
572 EXPECT_EQ(true, key
.extractable());
573 EXPECT_EQ(usages
, key
.usages());
575 // Export the key in raw format and compare to the original.
576 std::vector
<uint8_t> key_raw_out
;
577 ASSERT_EQ(Status::Success(),
578 ExportKey(blink::WebCryptoKeyFormatRaw
, key
, &key_raw_out
));
579 EXPECT_BYTES_EQ_HEX(key_hex
, key_raw_out
);
582 } // namespace webcrypto
584 } // namesapce content