0

Make //crypto factories return std::unique_ptr<>s

Rather than make callers use base::WrapUnique or .reset(),
have //crypto functions that create new instances return them
in std::unique_ptr<>s

Also fixup NULL vs nullptr where it matters most, and remove
superflous .get() tests from the unique_ptr<>s

BUG=none
R=davidben@chromium.org

Review-Url: https://codereview.chromium.org/2095523002
Cr-Commit-Position: refs/heads/master@{#402368}
This commit is contained in:
rsleevi
2016-06-27 18:51:52 -07:00
committed by Commit bot
parent 4e58d3d7f3
commit ffe5a13751
44 changed files with 285 additions and 315 deletions

@@ -44,11 +44,11 @@ class BrowsingDataChannelIDHelperTest
channel_id_store->SetChannelID( channel_id_store->SetChannelID(
base::WrapUnique(new net::ChannelIDStore::ChannelID( base::WrapUnique(new net::ChannelIDStore::ChannelID(
"https://www.google.com:443", base::Time(), "https://www.google.com:443", base::Time(),
base::WrapUnique(crypto::ECPrivateKey::Create())))); crypto::ECPrivateKey::Create())));
channel_id_store->SetChannelID( channel_id_store->SetChannelID(
base::WrapUnique(new net::ChannelIDStore::ChannelID( base::WrapUnique(new net::ChannelIDStore::ChannelID(
"https://www.youtube.com:443", base::Time(), "https://www.youtube.com:443", base::Time(),
base::WrapUnique(crypto::ECPrivateKey::Create())))); crypto::ECPrivateKey::Create())));
} }
void FetchCallback( void FetchCallback(
@@ -142,7 +142,7 @@ TEST_F(BrowsingDataChannelIDHelperTest, CannedEmpty) {
ASSERT_TRUE(helper->empty()); ASSERT_TRUE(helper->empty());
helper->AddChannelID(net::ChannelIDStore::ChannelID( helper->AddChannelID(net::ChannelIDStore::ChannelID(
origin, base::Time(), base::WrapUnique(crypto::ECPrivateKey::Create()))); origin, base::Time(), crypto::ECPrivateKey::Create()));
ASSERT_FALSE(helper->empty()); ASSERT_FALSE(helper->empty());
helper->Reset(); helper->Reset();
ASSERT_TRUE(helper->empty()); ASSERT_TRUE(helper->empty());

@@ -493,8 +493,7 @@ class RemoveChannelIDTester : public net::SSLConfigService::Observer {
base::Time creation_time) { base::Time creation_time) {
GetChannelIDStore()->SetChannelID( GetChannelIDStore()->SetChannelID(
base::WrapUnique(new net::ChannelIDStore::ChannelID( base::WrapUnique(new net::ChannelIDStore::ChannelID(
server_identifier, creation_time, server_identifier, creation_time, crypto::ECPrivateKey::Create())));
base::WrapUnique(crypto::ECPrivateKey::Create()))));
} }
// Add a server bound cert for |server|, with the current time as the // Add a server bound cert for |server|, with the current time as the

@@ -110,17 +110,15 @@ class ProfileAuthDataTest : public testing::Test {
}; };
void ProfileAuthDataTest::SetUp() { void ProfileAuthDataTest::SetUp() {
channel_id_key1_.reset(crypto::ECPrivateKey::Create()); channel_id_key1_ = crypto::ECPrivateKey::Create();
channel_id_key2_.reset(crypto::ECPrivateKey::Create()); channel_id_key2_ = crypto::ECPrivateKey::Create();
PopulateBrowserContext(&login_browser_context_, kProxyAuthPassword1, PopulateBrowserContext(&login_browser_context_, kProxyAuthPassword1,
kCookieValue1, kCookieValue1, channel_id_key1_->Copy());
base::WrapUnique(channel_id_key1_->Copy()));
} }
void ProfileAuthDataTest::PopulateUserBrowserContext() { void ProfileAuthDataTest::PopulateUserBrowserContext() {
PopulateBrowserContext(&user_browser_context_, kProxyAuthPassword2, PopulateBrowserContext(&user_browser_context_, kProxyAuthPassword2,
kCookieValue2, kCookieValue2, channel_id_key2_->Copy());
base::WrapUnique(channel_id_key2_->Copy()));
} }
void ProfileAuthDataTest::Transfer( void ProfileAuthDataTest::Transfer(

@@ -31,7 +31,7 @@ CryptohomeTokenEncryptor::CryptohomeTokenEncryptor(
DCHECK(!system_salt.empty()); DCHECK(!system_salt.empty());
// TODO(davidroche): should this use the system salt for both the password // TODO(davidroche): should this use the system salt for both the password
// and the salt value, or should this use a separate salt value? // and the salt value, or should this use a separate salt value?
system_salt_key_.reset(PassphraseToKey(system_salt_, system_salt_)); system_salt_key_ = PassphraseToKey(system_salt_, system_salt_);
} }
CryptohomeTokenEncryptor::~CryptohomeTokenEncryptor() { CryptohomeTokenEncryptor::~CryptohomeTokenEncryptor() {
@@ -67,7 +67,7 @@ std::string CryptohomeTokenEncryptor::DecryptWithSystemSalt(
encrypted_token_hex); encrypted_token_hex);
} }
crypto::SymmetricKey* CryptohomeTokenEncryptor::PassphraseToKey( std::unique_ptr<crypto::SymmetricKey> CryptohomeTokenEncryptor::PassphraseToKey(
const std::string& passphrase, const std::string& passphrase,
const std::string& salt) { const std::string& salt) {
return crypto::SymmetricKey::DeriveKeyFromPassword( return crypto::SymmetricKey::DeriveKeyFromPassword(

@@ -47,8 +47,9 @@ class CryptohomeTokenEncryptor : public TokenEncryptor {
private: private:
// Converts |passphrase| to a SymmetricKey using the given |salt|. // Converts |passphrase| to a SymmetricKey using the given |salt|.
crypto::SymmetricKey* PassphraseToKey(const std::string& passphrase, std::unique_ptr<crypto::SymmetricKey> PassphraseToKey(
const std::string& salt); const std::string& passphrase,
const std::string& salt);
// Encrypts (AES) the token given |key| and |salt|. // Encrypts (AES) the token given |key| and |salt|.
std::string EncryptTokenWithKey(crypto::SymmetricKey* key, std::string EncryptTokenWithKey(crypto::SymmetricKey* key,

@@ -98,14 +98,13 @@ class LocalExtensionCacheTest : public testing::Test {
base::FilePath* filename) { base::FilePath* filename) {
std::string data(size, 0); std::string data(size, 0);
crypto::SecureHash* hash = std::unique_ptr<crypto::SecureHash> hash =
crypto::SecureHash::Create(crypto::SecureHash::SHA256); crypto::SecureHash::Create(crypto::SecureHash::SHA256);
hash->Update(data.c_str(), size); hash->Update(data.c_str(), size);
uint8_t output[crypto::kSHA256Length]; uint8_t output[crypto::kSHA256Length];
hash->Finish(output, sizeof(output)); hash->Finish(output, sizeof(output));
const std::string hex_hash = const std::string hex_hash =
base::ToLowerASCII(base::HexEncode(output, sizeof(output))); base::ToLowerASCII(base::HexEncode(output, sizeof(output)));
delete hash;
const base::FilePath file = const base::FilePath file =
GetExtensionFileName(dir, id, version, hex_hash); GetExtensionFileName(dir, id, version, hex_hash);

@@ -9,7 +9,6 @@
#include "base/bind.h" #include "base/bind.h"
#include "base/files/file_util.h" #include "base/files/file_util.h"
#include "base/files/scoped_temp_dir.h" #include "base/files/scoped_temp_dir.h"
#include "base/memory/ptr_util.h"
#include "base/memory/ref_counted.h" #include "base/memory/ref_counted.h"
#include "base/memory/scoped_vector.h" #include "base/memory/scoped_vector.h"
#include "base/message_loop/message_loop.h" #include "base/message_loop/message_loop.h"
@@ -84,11 +83,9 @@ TEST_F(QuotaPolicyChannelIDStoreTest, TestPersistence) {
crypto::ECPrivateKey::Create()); crypto::ECPrivateKey::Create());
std::unique_ptr<crypto::ECPrivateKey> foo_key(crypto::ECPrivateKey::Create()); std::unique_ptr<crypto::ECPrivateKey> foo_key(crypto::ECPrivateKey::Create());
store_->AddChannelID(net::DefaultChannelIDStore::ChannelID( store_->AddChannelID(net::DefaultChannelIDStore::ChannelID(
"google.com", base::Time::FromInternalValue(1), "google.com", base::Time::FromInternalValue(1), goog_key->Copy()));
base::WrapUnique(goog_key->Copy())));
store_->AddChannelID(net::DefaultChannelIDStore::ChannelID( store_->AddChannelID(net::DefaultChannelIDStore::ChannelID(
"foo.com", base::Time::FromInternalValue(3), "foo.com", base::Time::FromInternalValue(3), foo_key->Copy()));
base::WrapUnique(foo_key->Copy())));
std::vector<std::unique_ptr<net::DefaultChannelIDStore::ChannelID>> std::vector<std::unique_ptr<net::DefaultChannelIDStore::ChannelID>>
channel_ids; channel_ids;
@@ -143,10 +140,10 @@ TEST_F(QuotaPolicyChannelIDStoreTest, TestPersistence) {
TEST_F(QuotaPolicyChannelIDStoreTest, TestPolicy) { TEST_F(QuotaPolicyChannelIDStoreTest, TestPolicy) {
store_->AddChannelID(net::DefaultChannelIDStore::ChannelID( store_->AddChannelID(net::DefaultChannelIDStore::ChannelID(
"google.com", base::Time::FromInternalValue(1), "google.com", base::Time::FromInternalValue(1),
base::WrapUnique(crypto::ECPrivateKey::Create()))); crypto::ECPrivateKey::Create()));
store_->AddChannelID(net::DefaultChannelIDStore::ChannelID( store_->AddChannelID(net::DefaultChannelIDStore::ChannelID(
"nonpersistent.com", base::Time::FromInternalValue(3), "nonpersistent.com", base::Time::FromInternalValue(3),
base::WrapUnique(crypto::ECPrivateKey::Create()))); crypto::ECPrivateKey::Create()));
std::vector<std::unique_ptr<net::DefaultChannelIDStore::ChannelID>> std::vector<std::unique_ptr<net::DefaultChannelIDStore::ChannelID>>
channel_ids; channel_ids;
@@ -176,10 +173,10 @@ TEST_F(QuotaPolicyChannelIDStoreTest, TestPolicy) {
// being committed to disk. // being committed to disk.
store_->AddChannelID(net::DefaultChannelIDStore::ChannelID( store_->AddChannelID(net::DefaultChannelIDStore::ChannelID(
"nonpersistent.com", base::Time::FromInternalValue(5), "nonpersistent.com", base::Time::FromInternalValue(5),
base::WrapUnique(crypto::ECPrivateKey::Create()))); crypto::ECPrivateKey::Create()));
store_->AddChannelID(net::DefaultChannelIDStore::ChannelID( store_->AddChannelID(net::DefaultChannelIDStore::ChannelID(
"persistent.com", base::Time::FromInternalValue(7), "persistent.com", base::Time::FromInternalValue(7),
base::WrapUnique(crypto::ECPrivateKey::Create()))); crypto::ECPrivateKey::Create()));
// Now close the store, and the nonpersistent.com channel IDs should be // Now close the store, and the nonpersistent.com channel IDs should be
// deleted according to policy. // deleted according to policy.

@@ -111,7 +111,7 @@ CrxFile::ValidateError CrxFile::ValidateSignature(
base::ScopedFILE file(base::OpenFile(crx_path, "rb")); base::ScopedFILE file(base::OpenFile(crx_path, "rb"));
std::unique_ptr<crypto::SecureHash> hash; std::unique_ptr<crypto::SecureHash> hash;
if (!expected_hash.empty()) if (!expected_hash.empty())
hash.reset(crypto::SecureHash::Create(crypto::SecureHash::SHA256)); hash = crypto::SecureHash::Create(crypto::SecureHash::SHA256);
if (!file.get()) if (!file.get())
return ValidateError::CRX_FILE_NOT_READABLE; return ValidateError::CRX_FILE_NOT_READABLE;

@@ -77,12 +77,10 @@ crypto::SymmetricKey* GetEncryptionKey() {
// Create an encryption key from our password and salt. The key is // Create an encryption key from our password and salt. The key is
// intentionally leaked. // intentionally leaked.
cached_encryption_key = cached_encryption_key = crypto::SymmetricKey::DeriveKeyFromPassword(
crypto::SymmetricKey::DeriveKeyFromPassword(crypto::SymmetricKey::AES, crypto::SymmetricKey::AES, password, salt,
password, kEncryptionIterations, kDerivedKeySizeInBits)
salt, .release();
kEncryptionIterations,
kDerivedKeySizeInBits);
ANNOTATE_LEAKING_OBJECT_PTR(cached_encryption_key); ANNOTATE_LEAKING_OBJECT_PTR(cached_encryption_key);
DCHECK(cached_encryption_key); DCHECK(cached_encryption_key);
return cached_encryption_key; return cached_encryption_key;

@@ -208,7 +208,7 @@ std::string BaseFile::DebugString() const {
DownloadInterruptReason BaseFile::CalculatePartialHash( DownloadInterruptReason BaseFile::CalculatePartialHash(
const std::string& hash_to_expect) { const std::string& hash_to_expect) {
secure_hash_.reset(crypto::SecureHash::Create(crypto::SecureHash::SHA256)); secure_hash_ = crypto::SecureHash::Create(crypto::SecureHash::SHA256);
if (bytes_so_far_ == 0) if (bytes_so_far_ == 0)
return DOWNLOAD_INTERRUPT_REASON_NONE; return DOWNLOAD_INTERRUPT_REASON_NONE;

@@ -31,7 +31,6 @@
#include "base/format_macros.h" #include "base/format_macros.h"
#include "base/guid.h" #include "base/guid.h"
#include "base/logging.h" #include "base/logging.h"
#include "base/memory/ptr_util.h"
#include "base/metrics/histogram.h" #include "base/metrics/histogram.h"
#include "base/stl_util.h" #include "base/stl_util.h"
#include "base/strings/string_util.h" #include "base/strings/string_util.h"
@@ -1175,9 +1174,9 @@ void DownloadItemImpl::Start(
int64_t offset = new_create_info.save_info->offset; int64_t offset = new_create_info.save_info->offset;
std::unique_ptr<crypto::SecureHash> hash_state = std::unique_ptr<crypto::SecureHash> hash_state =
base::WrapUnique(new_create_info.save_info->hash_state new_create_info.save_info->hash_state
? new_create_info.save_info->hash_state->Clone() ? new_create_info.save_info->hash_state->Clone()
: nullptr); : nullptr;
// Interrupted downloads also need a target path. // Interrupted downloads also need a target path.
if (target_path_.empty()) { if (target_path_.empty()) {

@@ -13,8 +13,6 @@
#include <stddef.h> #include <stddef.h>
#include <stdint.h> #include <stdint.h>
#include <memory>
#include "base/logging.h" #include "base/logging.h"
#include "crypto/auto_cbb.h" #include "crypto/auto_cbb.h"
#include "crypto/openssl_util.h" #include "crypto/openssl_util.h"
@@ -43,13 +41,13 @@ bool ExportKeyWithBio(const void* key,
return false; return false;
ScopedBIO bio(BIO_new(BIO_s_mem())); ScopedBIO bio(BIO_new(BIO_s_mem()));
if (!bio.get()) if (!bio)
return false; return false;
if (!export_fn(bio.get(), key)) if (!export_fn(bio.get(), key))
return false; return false;
char* data = NULL; char* data = nullptr;
long len = BIO_get_mem_data(bio.get(), &data); long len = BIO_get_mem_data(bio.get(), &data);
if (!data || len < 0) if (!data || len < 0)
return false; return false;
@@ -65,28 +63,21 @@ ECPrivateKey::~ECPrivateKey() {
EVP_PKEY_free(key_); EVP_PKEY_free(key_);
} }
ECPrivateKey* ECPrivateKey::Copy() const {
std::unique_ptr<ECPrivateKey> copy(new ECPrivateKey);
if (key_)
copy->key_ = EVP_PKEY_up_ref(key_);
return copy.release();
}
// static // static
ECPrivateKey* ECPrivateKey::Create() { std::unique_ptr<ECPrivateKey> ECPrivateKey::Create() {
OpenSSLErrStackTracer err_tracer(FROM_HERE); OpenSSLErrStackTracer err_tracer(FROM_HERE);
ScopedEC_KEY ec_key(EC_KEY_new_by_curve_name(NID_X9_62_prime256v1)); ScopedEC_KEY ec_key(EC_KEY_new_by_curve_name(NID_X9_62_prime256v1));
if (!ec_key.get() || !EC_KEY_generate_key(ec_key.get())) if (!ec_key || !EC_KEY_generate_key(ec_key.get()))
return NULL; return nullptr;
std::unique_ptr<ECPrivateKey> result(new ECPrivateKey()); std::unique_ptr<ECPrivateKey> result(new ECPrivateKey());
result->key_ = EVP_PKEY_new(); result->key_ = EVP_PKEY_new();
if (!result->key_ || !EVP_PKEY_set1_EC_KEY(result->key_, ec_key.get())) if (!result->key_ || !EVP_PKEY_set1_EC_KEY(result->key_, ec_key.get()))
return NULL; return nullptr;
CHECK_EQ(EVP_PKEY_EC, EVP_PKEY_id(result->key_)); CHECK_EQ(EVP_PKEY_EC, EVP_PKEY_id(result->key_));
return result.release(); return result;
} }
// static // static
@@ -100,13 +91,13 @@ std::unique_ptr<ECPrivateKey> ECPrivateKey::CreateFromPrivateKeyInfo(
if (!pkey || CBS_len(&cbs) != 0 || EVP_PKEY_id(pkey.get()) != EVP_PKEY_EC) if (!pkey || CBS_len(&cbs) != 0 || EVP_PKEY_id(pkey.get()) != EVP_PKEY_EC)
return nullptr; return nullptr;
std::unique_ptr<ECPrivateKey> result(new ECPrivateKey); std::unique_ptr<ECPrivateKey> result(new ECPrivateKey());
result->key_ = pkey.release(); result->key_ = pkey.release();
return result; return result;
} }
// static // static
ECPrivateKey* ECPrivateKey::CreateFromEncryptedPrivateKeyInfo( std::unique_ptr<ECPrivateKey> ECPrivateKey::CreateFromEncryptedPrivateKeyInfo(
const std::string& password, const std::string& password,
const std::vector<uint8_t>& encrypted_private_key_info, const std::vector<uint8_t>& encrypted_private_key_info,
const std::vector<uint8_t>& subject_public_key_info) { const std::vector<uint8_t>& subject_public_key_info) {
@@ -114,16 +105,16 @@ ECPrivateKey* ECPrivateKey::CreateFromEncryptedPrivateKeyInfo(
// useful for the NSS implementation (which uses the public key's SHA1 // useful for the NSS implementation (which uses the public key's SHA1
// as a lookup key when storing the private one in its store). // as a lookup key when storing the private one in its store).
if (encrypted_private_key_info.empty()) if (encrypted_private_key_info.empty())
return NULL; return nullptr;
OpenSSLErrStackTracer err_tracer(FROM_HERE); OpenSSLErrStackTracer err_tracer(FROM_HERE);
const uint8_t* data = &encrypted_private_key_info[0]; const uint8_t* data = &encrypted_private_key_info[0];
const uint8_t* ptr = data; const uint8_t* ptr = data;
ScopedX509_SIG p8_encrypted( ScopedX509_SIG p8_encrypted(
d2i_X509_SIG(NULL, &ptr, encrypted_private_key_info.size())); d2i_X509_SIG(nullptr, &ptr, encrypted_private_key_info.size()));
if (!p8_encrypted || ptr != data + encrypted_private_key_info.size()) if (!p8_encrypted || ptr != data + encrypted_private_key_info.size())
return NULL; return nullptr;
ScopedPKCS8_PRIV_KEY_INFO p8_decrypted; ScopedPKCS8_PRIV_KEY_INFO p8_decrypted;
if (password.empty()) { if (password.empty()) {
@@ -142,15 +133,22 @@ ECPrivateKey* ECPrivateKey::CreateFromEncryptedPrivateKeyInfo(
} }
if (!p8_decrypted) if (!p8_decrypted)
return NULL; return nullptr;
// Create a new EVP_PKEY for it. // Create a new EVP_PKEY for it.
std::unique_ptr<ECPrivateKey> result(new ECPrivateKey); std::unique_ptr<ECPrivateKey> result(new ECPrivateKey());
result->key_ = EVP_PKCS82PKEY(p8_decrypted.get()); result->key_ = EVP_PKCS82PKEY(p8_decrypted.get());
if (!result->key_ || EVP_PKEY_id(result->key_) != EVP_PKEY_EC) if (!result->key_ || EVP_PKEY_id(result->key_) != EVP_PKEY_EC)
return NULL; return nullptr;
return result.release(); return result;
}
std::unique_ptr<ECPrivateKey> ECPrivateKey::Copy() const {
std::unique_ptr<ECPrivateKey> copy(new ECPrivateKey());
if (key_)
copy->key_ = EVP_PKEY_up_ref(key_);
return copy;
} }
bool ECPrivateKey::ExportPrivateKey(std::vector<uint8_t>* output) const { bool ECPrivateKey::ExportPrivateKey(std::vector<uint8_t>* output) const {
@@ -174,7 +172,7 @@ bool ECPrivateKey::ExportEncryptedPrivateKey(
OpenSSLErrStackTracer err_tracer(FROM_HERE); OpenSSLErrStackTracer err_tracer(FROM_HERE);
// Convert into a PKCS#8 object. // Convert into a PKCS#8 object.
ScopedPKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(key_)); ScopedPKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(key_));
if (!pkcs8.get()) if (!pkcs8)
return false; return false;
// Encrypt the object. // Encrypt the object.
@@ -190,7 +188,7 @@ bool ECPrivateKey::ExportEncryptedPrivateKey(
0, 0,
iterations, iterations,
pkcs8.get())); pkcs8.get()));
if (!encrypted.get()) if (!encrypted)
return false; return false;
// Write it into |*output| // Write it into |*output|
@@ -236,6 +234,6 @@ bool ECPrivateKey::ExportRawPublicKey(std::string* output) const {
return true; return true;
} }
ECPrivateKey::ECPrivateKey() : key_(NULL) {} ECPrivateKey::ECPrivateKey() : key_(nullptr) {}
} // namespace crypto } // namespace crypto

@@ -30,10 +30,10 @@ class CRYPTO_EXPORT ECPrivateKey {
public: public:
~ECPrivateKey(); ~ECPrivateKey();
// Creates a new random instance. Can return NULL if initialization fails. // Creates a new random instance. Can return nullptr if initialization fails.
// The created key will use the NIST P-256 curve. // The created key will use the NIST P-256 curve.
// TODO(mattm): Add a curve parameter. // TODO(mattm): Add a curve parameter.
static ECPrivateKey* Create(); static std::unique_ptr<ECPrivateKey> Create();
// Create a new instance by importing an existing private key. The format is // Create a new instance by importing an existing private key. The format is
// an ASN.1-encoded PrivateKeyInfo block from PKCS #8. This can return // an ASN.1-encoded PrivateKeyInfo block from PKCS #8. This can return
@@ -44,17 +44,17 @@ class CRYPTO_EXPORT ECPrivateKey {
// Creates a new instance by importing an existing key pair. // Creates a new instance by importing an existing key pair.
// The key pair is given as an ASN.1-encoded PKCS #8 EncryptedPrivateKeyInfo // The key pair is given as an ASN.1-encoded PKCS #8 EncryptedPrivateKeyInfo
// block and an X.509 SubjectPublicKeyInfo block. // block and an X.509 SubjectPublicKeyInfo block.
// Returns NULL if initialization fails. // Returns nullptr if initialization fails.
// //
// This function is deprecated. Use CreateFromPrivateKeyInfo for new code. // This function is deprecated. Use CreateFromPrivateKeyInfo for new code.
// See https://crbug.com/603319. // See https://crbug.com/603319.
static ECPrivateKey* CreateFromEncryptedPrivateKeyInfo( static std::unique_ptr<ECPrivateKey> CreateFromEncryptedPrivateKeyInfo(
const std::string& password, const std::string& password,
const std::vector<uint8_t>& encrypted_private_key_info, const std::vector<uint8_t>& encrypted_private_key_info,
const std::vector<uint8_t>& subject_public_key_info); const std::vector<uint8_t>& subject_public_key_info);
// Returns a copy of the object. // Returns a copy of the object.
ECPrivateKey* Copy() const; std::unique_ptr<ECPrivateKey> Copy() const;
EVP_PKEY* key() { return key_; } EVP_PKEY* key() { return key_; }

@@ -45,7 +45,7 @@ TEST(ECPrivateKeyUnitTest, InitRandomTest) {
static const char kPassword2[] = "test"; static const char kPassword2[] = "test";
std::unique_ptr<crypto::ECPrivateKey> keypair(crypto::ECPrivateKey::Create()); std::unique_ptr<crypto::ECPrivateKey> keypair(crypto::ECPrivateKey::Create());
ASSERT_TRUE(keypair.get()); ASSERT_TRUE(keypair);
// Re-import as a PrivateKeyInfo. // Re-import as a PrivateKeyInfo.
std::vector<uint8_t> privkey; std::vector<uint8_t> privkey;
@@ -61,16 +61,16 @@ TEST(ECPrivateKeyUnitTest, InitRandomTest) {
EXPECT_TRUE( EXPECT_TRUE(
keypair->ExportEncryptedPrivateKey(kPassword1, 1, &encrypted_privkey)); keypair->ExportEncryptedPrivateKey(kPassword1, 1, &encrypted_privkey));
EXPECT_TRUE(keypair->ExportPublicKey(&pubkey)); EXPECT_TRUE(keypair->ExportPublicKey(&pubkey));
keypair_copy.reset(crypto::ECPrivateKey::CreateFromEncryptedPrivateKeyInfo( keypair_copy = crypto::ECPrivateKey::CreateFromEncryptedPrivateKeyInfo(
kPassword1, encrypted_privkey, pubkey)); kPassword1, encrypted_privkey, pubkey);
ASSERT_TRUE(keypair_copy); ASSERT_TRUE(keypair_copy);
ExpectKeysEqual(keypair.get(), keypair_copy.get()); ExpectKeysEqual(keypair.get(), keypair_copy.get());
// Re-import as an EncryptedPrivateKeyInfo with kPassword2. // Re-import as an EncryptedPrivateKeyInfo with kPassword2.
EXPECT_TRUE( EXPECT_TRUE(
keypair->ExportEncryptedPrivateKey(kPassword2, 1, &encrypted_privkey)); keypair->ExportEncryptedPrivateKey(kPassword2, 1, &encrypted_privkey));
keypair_copy.reset(crypto::ECPrivateKey::CreateFromEncryptedPrivateKeyInfo( keypair_copy = crypto::ECPrivateKey::CreateFromEncryptedPrivateKeyInfo(
kPassword2, encrypted_privkey, pubkey)); kPassword2, encrypted_privkey, pubkey);
ASSERT_TRUE(keypair_copy); ASSERT_TRUE(keypair_copy);
ExpectKeysEqual(keypair.get(), keypair_copy.get()); ExpectKeysEqual(keypair.get(), keypair_copy.get());
} }
@@ -79,8 +79,8 @@ TEST(ECPrivateKeyUnitTest, Copy) {
std::unique_ptr<crypto::ECPrivateKey> keypair1( std::unique_ptr<crypto::ECPrivateKey> keypair1(
crypto::ECPrivateKey::Create()); crypto::ECPrivateKey::Create());
std::unique_ptr<crypto::ECPrivateKey> keypair2(keypair1->Copy()); std::unique_ptr<crypto::ECPrivateKey> keypair2(keypair1->Copy());
ASSERT_TRUE(keypair1.get()); ASSERT_TRUE(keypair1);
ASSERT_TRUE(keypair2.get()); ASSERT_TRUE(keypair2);
ExpectKeysEqual(keypair1.get(), keypair2.get()); ExpectKeysEqual(keypair1.get(), keypair2.get());
} }
@@ -206,7 +206,7 @@ TEST(ECPrivateKeyUnitTest, BadPasswordTest) {
std::unique_ptr<crypto::ECPrivateKey> keypair1( std::unique_ptr<crypto::ECPrivateKey> keypair1(
crypto::ECPrivateKey::Create()); crypto::ECPrivateKey::Create());
ASSERT_TRUE(keypair1.get()); ASSERT_TRUE(keypair1);
std::vector<uint8_t> privkey1; std::vector<uint8_t> privkey1;
std::vector<uint8_t> pubkey1; std::vector<uint8_t> pubkey1;
@@ -217,7 +217,7 @@ TEST(ECPrivateKeyUnitTest, BadPasswordTest) {
std::unique_ptr<crypto::ECPrivateKey> keypair2( std::unique_ptr<crypto::ECPrivateKey> keypair2(
crypto::ECPrivateKey::CreateFromEncryptedPrivateKeyInfo( crypto::ECPrivateKey::CreateFromEncryptedPrivateKeyInfo(
password2, privkey1, pubkey1)); password2, privkey1, pubkey1));
ASSERT_FALSE(keypair2.get()); ASSERT_FALSE(keypair2);
} }
TEST(ECPrivateKeyUnitTest, LoadNSSKeyTest) { TEST(ECPrivateKeyUnitTest, LoadNSSKeyTest) {
@@ -256,7 +256,7 @@ TEST(ECPrivateKeyUnitTest, LoadNSSKeyTest) {
std::vector<uint8_t>(std::begin(kNSSPublicKey), std::vector<uint8_t>(std::begin(kNSSPublicKey),
std::end(kNSSPublicKey)))); std::end(kNSSPublicKey))));
EXPECT_TRUE(keypair_nss.get()); EXPECT_TRUE(keypair_nss);
} }
TEST(ECPrivateKeyUnitTest, LoadOpenSSLKeyTest) { TEST(ECPrivateKeyUnitTest, LoadOpenSSLKeyTest) {
@@ -303,7 +303,7 @@ TEST(ECPrivateKeyUnitTest, LoadOpenSSLKeyTest) {
std::vector<uint8_t>(std::begin(kOpenSSLPublicKey), std::vector<uint8_t>(std::begin(kOpenSSLPublicKey),
std::end(kOpenSSLPublicKey)))); std::end(kOpenSSLPublicKey))));
EXPECT_TRUE(keypair_openssl.get()); EXPECT_TRUE(keypair_openssl);
std::vector<uint8_t> public_key; std::vector<uint8_t> public_key;
EXPECT_TRUE(keypair_openssl->ExportPublicKey(&public_key)); EXPECT_TRUE(keypair_openssl->ExportPublicKey(&public_key));
@@ -398,5 +398,5 @@ TEST(ECPrivateKeyUnitTest, LoadOldOpenSSLKeyTest) {
std::vector<uint8_t>(std::begin(kOpenSSLPublicKey), std::vector<uint8_t>(std::begin(kOpenSSLPublicKey),
std::end(kOpenSSLPublicKey)))); std::end(kOpenSSLPublicKey))));
EXPECT_TRUE(keypair_openssl.get()); EXPECT_TRUE(keypair_openssl);
} }

@@ -5,21 +5,23 @@
#include "crypto/ec_signature_creator.h" #include "crypto/ec_signature_creator.h"
#include "base/logging.h" #include "base/logging.h"
#include "base/memory/ptr_util.h"
#include "crypto/ec_signature_creator_impl.h" #include "crypto/ec_signature_creator_impl.h"
namespace crypto { namespace crypto {
namespace { namespace {
ECSignatureCreatorFactory* g_factory_ = NULL; ECSignatureCreatorFactory* g_factory_ = nullptr;
} // namespace } // namespace
// static // static
ECSignatureCreator* ECSignatureCreator::Create(ECPrivateKey* key) { std::unique_ptr<ECSignatureCreator> ECSignatureCreator::Create(
ECPrivateKey* key) {
if (g_factory_) if (g_factory_)
return g_factory_->Create(key); return g_factory_->Create(key);
return new ECSignatureCreatorImpl(key); return base::MakeUnique<ECSignatureCreatorImpl>(key);
} }
// static // static

@@ -7,6 +7,7 @@
#include <stdint.h> #include <stdint.h>
#include <memory>
#include <string> #include <string>
#include <vector> #include <vector>
@@ -21,7 +22,7 @@ class CRYPTO_EXPORT ECSignatureCreatorFactory {
public: public:
virtual ~ECSignatureCreatorFactory() {} virtual ~ECSignatureCreatorFactory() {}
virtual ECSignatureCreator* Create(ECPrivateKey* key) = 0; virtual std::unique_ptr<ECSignatureCreator> Create(ECPrivateKey* key) = 0;
}; };
// Signs data using a bare private key (as opposed to a full certificate). // Signs data using a bare private key (as opposed to a full certificate).
@@ -35,7 +36,7 @@ class CRYPTO_EXPORT ECSignatureCreator {
// instance outlives the created ECSignatureCreator. // instance outlives the created ECSignatureCreator.
// TODO(rch): This is currently hard coded to use SHA256. Ideally, we should // TODO(rch): This is currently hard coded to use SHA256. Ideally, we should
// pass in the hash algorithm identifier. // pass in the hash algorithm identifier.
static ECSignatureCreator* Create(ECPrivateKey* key); static std::unique_ptr<ECSignatureCreator> Create(ECPrivateKey* key);
// Set a factory to make the Create function return non-standard // Set a factory to make the Create function return non-standard
// ECSignatureCreator objects. Because the ECDSA algorithm involves // ECSignatureCreator objects. Because the ECDSA algorithm involves

@@ -33,9 +33,10 @@ bool ECSignatureCreatorImpl::Sign(const uint8_t* data,
ScopedEVP_MD_CTX ctx(EVP_MD_CTX_create()); ScopedEVP_MD_CTX ctx(EVP_MD_CTX_create());
size_t sig_len = 0; size_t sig_len = 0;
if (!ctx.get() || if (!ctx.get() ||
!EVP_DigestSignInit(ctx.get(), NULL, EVP_sha256(), NULL, key_->key()) || !EVP_DigestSignInit(ctx.get(), nullptr, EVP_sha256(), nullptr,
key_->key()) ||
!EVP_DigestSignUpdate(ctx.get(), data, data_len) || !EVP_DigestSignUpdate(ctx.get(), data, data_len) ||
!EVP_DigestSignFinal(ctx.get(), NULL, &sig_len)) { !EVP_DigestSignFinal(ctx.get(), nullptr, &sig_len)) {
return false; return false;
} }
@@ -43,9 +44,9 @@ bool ECSignatureCreatorImpl::Sign(const uint8_t* data,
if (!EVP_DigestSignFinal(ctx.get(), &signature->front(), &sig_len)) if (!EVP_DigestSignFinal(ctx.get(), &signature->front(), &sig_len))
return false; return false;
// NOTE: A call to EVP_DigestSignFinal() with a NULL second parameter returns // NOTE: A call to EVP_DigestSignFinal() with a nullptr second parameter
// a maximum allocation size, while the call without a NULL returns the real // returns a maximum allocation size, while the call without a nullptr
// one, which may be smaller. // returns the real one, which may be smaller.
signature->resize(sig_len); signature->resize(sig_len);
return true; return true;
} }

@@ -23,7 +23,8 @@ const EVP_CIPHER* GetCipherForKey(SymmetricKey* key) {
switch (key->key().length()) { switch (key->key().length()) {
case 16: return EVP_aes_128_cbc(); case 16: return EVP_aes_128_cbc();
case 32: return EVP_aes_256_cbc(); case 32: return EVP_aes_256_cbc();
default: return NULL; default:
return nullptr;
} }
} }
@@ -84,10 +85,7 @@ size_t Encryptor::Counter::GetLengthInBytes() const {
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
// Encryptor Implementation. // Encryptor Implementation.
Encryptor::Encryptor() Encryptor::Encryptor() : key_(nullptr), mode_(CBC) {}
: key_(NULL),
mode_(CBC) {
}
Encryptor::~Encryptor() { Encryptor::~Encryptor() {
} }
@@ -102,7 +100,7 @@ bool Encryptor::Init(SymmetricKey* key,
if (mode == CBC && iv.size() != AES_BLOCK_SIZE) if (mode == CBC && iv.size() != AES_BLOCK_SIZE)
return false; return false;
if (GetCipherForKey(key) == NULL) if (GetCipherForKey(key) == nullptr)
return false; return false;
key_ = key; key_ = key;
@@ -191,9 +189,10 @@ bool Encryptor::Crypt(bool do_encrypt,
DCHECK_EQ(EVP_CIPHER_key_length(cipher), key.length()); DCHECK_EQ(EVP_CIPHER_key_length(cipher), key.length());
ScopedCipherCTX ctx; ScopedCipherCTX ctx;
if (!EVP_CipherInit_ex( if (!EVP_CipherInit_ex(ctx.get(), cipher, nullptr,
ctx.get(), cipher, NULL, reinterpret_cast<const uint8_t*>(key.data()), reinterpret_cast<const uint8_t*>(key.data()),
reinterpret_cast<const uint8_t*>(iv_.data()), do_encrypt)) reinterpret_cast<const uint8_t*>(iv_.data()),
do_encrypt))
return false; return false;
// When encrypting, add another block size of space to allow for any padding. // When encrypting, add another block size of space to allow for any padding.

@@ -63,10 +63,10 @@ bool HMAC::Sign(const base::StringPiece& data,
DCHECK(initialized_); DCHECK(initialized_);
ScopedOpenSSLSafeSizeBuffer<EVP_MAX_MD_SIZE> result(digest, digest_length); ScopedOpenSSLSafeSizeBuffer<EVP_MAX_MD_SIZE> result(digest, digest_length);
return !!::HMAC(hash_alg_ == SHA1 ? EVP_sha1() : EVP_sha256(), return !!::HMAC(hash_alg_ == SHA1 ? EVP_sha1() : EVP_sha256(), key_.data(),
key_.data(), key_.size(), key_.size(),
reinterpret_cast<const unsigned char*>(data.data()), reinterpret_cast<const unsigned char*>(data.data()),
data.size(), result.safe_buffer(), NULL); data.size(), result.safe_buffer(), nullptr);
} }
bool HMAC::Verify(const base::StringPiece& data, bool HMAC::Verify(const base::StringPiece& data,

@@ -287,7 +287,7 @@ TEST(HMACTest, EmptyKey) {
base::StringPiece data(""); base::StringPiece data("");
crypto::HMAC hmac(crypto::HMAC::SHA1); crypto::HMAC hmac(crypto::HMAC::SHA1);
ASSERT_TRUE(hmac.Init(NULL, 0)); ASSERT_TRUE(hmac.Init(nullptr, 0));
unsigned char digest[kSHA1DigestSize]; unsigned char digest[kSHA1DigestSize];
EXPECT_TRUE(hmac.Sign(data, digest, kSHA1DigestSize)); EXPECT_TRUE(hmac.Sign(data, digest, kSHA1DigestSize));

@@ -209,7 +209,7 @@ class CRYPTO_EXPORT MockAppleKeychain : public AppleKeychain {
bool locked_; bool locked_;
typedef struct KeychainPasswordData { typedef struct KeychainPasswordData {
KeychainPasswordData() : data(NULL), length(0) {} KeychainPasswordData() : data(nullptr), length(0) {}
void* data; void* data;
UInt32 length; UInt32 length;
} KeychainPasswordData; } KeychainPasswordData;

@@ -126,13 +126,13 @@ char* PKCS11PasswordFunc(PK11SlotInfo* slot, PRBool retry, void* arg) {
retry != PR_FALSE, retry != PR_FALSE,
&cancelled); &cancelled);
if (cancelled) if (cancelled)
return NULL; return nullptr;
char* result = PORT_Strdup(password.c_str()); char* result = PORT_Strdup(password.c_str());
password.replace(0, password.size(), password.size(), 0); password.replace(0, password.size(), password.size(), 0);
return result; return result;
} }
DLOG(ERROR) << "PK11 password requested with NULL arg"; DLOG(ERROR) << "PK11 password requested with nullptr arg";
return NULL; return nullptr;
} }
// NSS creates a local cache of the sqlite database if it detects that the // NSS creates a local cache of the sqlite database if it detects that the
@@ -218,8 +218,8 @@ class ChromeOSUserData {
} }
ScopedPK11Slot GetPublicSlot() { ScopedPK11Slot GetPublicSlot() {
return ScopedPK11Slot( return ScopedPK11Slot(public_slot_ ? PK11_ReferenceSlot(public_slot_.get())
public_slot_ ? PK11_ReferenceSlot(public_slot_.get()) : NULL); : nullptr);
} }
ScopedPK11Slot GetPrivateSlot( ScopedPK11Slot GetPrivateSlot(
@@ -353,7 +353,7 @@ class NSSInitSingleton {
// If everything is already initialized, then return true. // If everything is already initialized, then return true.
// Note that only |tpm_slot_| is checked, since |chaps_module_| could be // Note that only |tpm_slot_| is checked, since |chaps_module_| could be
// NULL in tests while |tpm_slot_| has been set to the test DB. // nullptr in tests while |tpm_slot_| has been set to the test DB.
if (tpm_slot_) { if (tpm_slot_) {
base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE,
base::Bind(callback, true)); base::Bind(callback, true));
@@ -608,7 +608,7 @@ class NSSInitSingleton {
void SetSystemKeySlotForTesting(ScopedPK11Slot slot) { void SetSystemKeySlotForTesting(ScopedPK11Slot slot) {
// Ensure that a previous value of test_system_slot_ is not overwritten. // Ensure that a previous value of test_system_slot_ is not overwritten.
// Unsetting, i.e. setting a NULL, however is allowed. // Unsetting, i.e. setting a nullptr, however is allowed.
DCHECK(!slot || !test_system_slot_); DCHECK(!slot || !test_system_slot_);
test_system_slot_ = std::move(slot); test_system_slot_ = std::move(slot);
if (test_system_slot_) { if (test_system_slot_) {
@@ -644,7 +644,7 @@ class NSSInitSingleton {
// TODO(mattm): chromeos::TPMTokenloader always calls // TODO(mattm): chromeos::TPMTokenloader always calls
// InitializeTPMTokenAndSystemSlot with slot 0. If the system slot is // InitializeTPMTokenAndSystemSlot with slot 0. If the system slot is
// disabled, tpm_slot_ will be the first user's slot instead. Can that be // disabled, tpm_slot_ will be the first user's slot instead. Can that be
// detected and return NULL instead? // detected and return nullptr instead?
base::Closure wrapped_callback; base::Closure wrapped_callback;
if (!callback.is_null()) { if (!callback.is_null()) {
@@ -669,8 +669,8 @@ class NSSInitSingleton {
NSSInitSingleton() NSSInitSingleton()
: tpm_token_enabled_for_nss_(false), : tpm_token_enabled_for_nss_(false),
initializing_tpm_token_(false), initializing_tpm_token_(false),
chaps_module_(NULL), chaps_module_(nullptr),
root_(NULL) { root_(nullptr) {
// It's safe to construct on any thread, since LazyInstance will prevent any // It's safe to construct on any thread, since LazyInstance will prevent any
// other threads from accessing until the constructor is done. // other threads from accessing until the constructor is done.
thread_checker_.DetachFromThread(); thread_checker_.DetachFromThread();
@@ -717,7 +717,7 @@ class NSSInitSingleton {
} }
if (status != SECSuccess) { if (status != SECSuccess) {
VLOG(1) << "Initializing NSS without a persistent database."; VLOG(1) << "Initializing NSS without a persistent database.";
status = NSS_NoDB_Init(NULL); status = NSS_NoDB_Init(nullptr);
if (status != SECSuccess) { if (status != SECSuccess) {
CrashOnNSSInitFailure(); CrashOnNSSInitFailure();
return; return;
@@ -734,7 +734,7 @@ class NSSInitSingleton {
// PK11_InitPin may write to the keyDB, but no other thread can use NSS // PK11_InitPin may write to the keyDB, but no other thread can use NSS
// yet, so we don't need to lock. // yet, so we don't need to lock.
if (PK11_NeedUserInit(slot)) if (PK11_NeedUserInit(slot))
PK11_InitPin(slot, NULL, NULL); PK11_InitPin(slot, nullptr, nullptr);
PK11_FreeSlot(slot); PK11_FreeSlot(slot);
} }
@@ -758,12 +758,12 @@ class NSSInitSingleton {
if (root_) { if (root_) {
SECMOD_UnloadUserModule(root_); SECMOD_UnloadUserModule(root_);
SECMOD_DestroyModule(root_); SECMOD_DestroyModule(root_);
root_ = NULL; root_ = nullptr;
} }
if (chaps_module_) { if (chaps_module_) {
SECMOD_UnloadUserModule(chaps_module_); SECMOD_UnloadUserModule(chaps_module_);
SECMOD_DestroyModule(chaps_module_); SECMOD_DestroyModule(chaps_module_);
chaps_module_ = NULL; chaps_module_ = nullptr;
} }
SECStatus status = NSS_Shutdown(); SECStatus status = NSS_Shutdown();
@@ -776,14 +776,14 @@ class NSSInitSingleton {
// Load nss's built-in root certs. // Load nss's built-in root certs.
SECMODModule* InitDefaultRootCerts() { SECMODModule* InitDefaultRootCerts() {
SECMODModule* root = LoadModule("Root Certs", "libnssckbi.so", NULL); SECMODModule* root = LoadModule("Root Certs", "libnssckbi.so", nullptr);
if (root) if (root)
return root; return root;
// Aw, snap. Can't find/load root cert shared library. // Aw, snap. Can't find/load root cert shared library.
// This will make it hard to talk to anybody via https. // This will make it hard to talk to anybody via https.
// TODO(mattm): Re-add the NOTREACHED here when crbug.com/310972 is fixed. // TODO(mattm): Re-add the NOTREACHED here when crbug.com/310972 is fixed.
return NULL; return nullptr;
} }
// Load the given module for this NSS session. // Load the given module for this NSS session.
@@ -799,17 +799,17 @@ class NSSInitSingleton {
// https://bugzilla.mozilla.org/show_bug.cgi?id=642546 was filed // https://bugzilla.mozilla.org/show_bug.cgi?id=642546 was filed
// on NSS codebase to address this. // on NSS codebase to address this.
SECMODModule* module = SECMOD_LoadUserModule( SECMODModule* module = SECMOD_LoadUserModule(
const_cast<char*>(modparams.c_str()), NULL, PR_FALSE); const_cast<char*>(modparams.c_str()), nullptr, PR_FALSE);
if (!module) { if (!module) {
LOG(ERROR) << "Error loading " << name << " module into NSS: " LOG(ERROR) << "Error loading " << name << " module into NSS: "
<< GetNSSErrorMessage(); << GetNSSErrorMessage();
return NULL; return nullptr;
} }
if (!module->loaded) { if (!module->loaded) {
LOG(ERROR) << "After loading " << name << ", loaded==false: " LOG(ERROR) << "After loading " << name << ", loaded==false: "
<< GetNSSErrorMessage(); << GetNSSErrorMessage();
SECMOD_DestroyModule(module); SECMOD_DestroyModule(module);
return NULL; return nullptr;
} }
return module; return module;
} }
@@ -846,7 +846,7 @@ ScopedPK11Slot OpenSoftwareNSSDB(const base::FilePath& path,
PK11SlotInfo* db_slot = SECMOD_OpenUserDB(modspec.c_str()); PK11SlotInfo* db_slot = SECMOD_OpenUserDB(modspec.c_str());
if (db_slot) { if (db_slot) {
if (PK11_NeedUserInit(db_slot)) if (PK11_NeedUserInit(db_slot))
PK11_InitPin(db_slot, NULL, NULL); PK11_InitPin(db_slot, nullptr, nullptr);
} else { } else {
LOG(ERROR) << "Error opening persistent database (" << modspec LOG(ERROR) << "Error opening persistent database (" << modspec
<< "): " << GetNSSErrorMessage(); << "): " << GetNSSErrorMessage();
@@ -881,7 +881,7 @@ base::Lock* GetNSSWriteLock() {
} }
AutoNSSWriteLock::AutoNSSWriteLock() : lock_(GetNSSWriteLock()) { AutoNSSWriteLock::AutoNSSWriteLock() : lock_(GetNSSWriteLock()) {
// May be NULL if the lock is not needed in our version of NSS. // May be nullptr if the lock is not needed in our version of NSS.
if (lock_) if (lock_)
lock_->Acquire(); lock_->Acquire();
} }

@@ -24,7 +24,7 @@ namespace crypto {
// Opens an NSS software database in folder |path|, with the (potentially) // Opens an NSS software database in folder |path|, with the (potentially)
// user-visible description |description|. Returns the slot for the opened // user-visible description |description|. Returns the slot for the opened
// database, or NULL if the database could not be opened. // database, or nullptr if the database could not be opened.
CRYPTO_EXPORT ScopedPK11Slot OpenSoftwareNSSDB(const base::FilePath& path, CRYPTO_EXPORT ScopedPK11Slot OpenSoftwareNSSDB(const base::FilePath& path,
const std::string& description); const std::string& description);
@@ -57,8 +57,8 @@ CRYPTO_EXPORT ScopedPK11Slot GetSystemNSSKeySlot(
// through |GetSystemNSSKeySlot| and |IsTPMTokenReady| will return true. // through |GetSystemNSSKeySlot| and |IsTPMTokenReady| will return true.
// |InitializeTPMTokenAndSystemSlot|, which triggers the TPM initialization, // |InitializeTPMTokenAndSystemSlot|, which triggers the TPM initialization,
// does not have to be called if the test system slot is set. // does not have to be called if the test system slot is set.
// This must must not be called consecutively with a |slot| != NULL. If |slot| // This must must not be called consecutively with a |slot| != nullptr. If
// is NULL, the test system slot is unset. // |slot| is nullptr, the test system slot is unset.
CRYPTO_EXPORT void SetSystemKeySlotForTesting(ScopedPK11Slot slot); CRYPTO_EXPORT void SetSystemKeySlotForTesting(ScopedPK11Slot slot);
// Prepare per-user NSS slot mapping. It is safe to call this function multiple // Prepare per-user NSS slot mapping. It is safe to call this function multiple

@@ -9,6 +9,7 @@
#include <stddef.h> #include <stddef.h>
#include "base/logging.h" #include "base/logging.h"
#include "base/memory/ptr_util.h"
#include "base/pickle.h" #include "base/pickle.h"
#include "crypto/openssl_util.h" #include "crypto/openssl_util.h"
@@ -40,8 +41,8 @@ class SecureHashSHA256 : public SecureHash {
SHA256_Final(result.safe_buffer(), &ctx_); SHA256_Final(result.safe_buffer(), &ctx_);
} }
SecureHash* Clone() const override { std::unique_ptr<SecureHash> Clone() const override {
return new SecureHashSHA256(*this); return base::MakeUnique<SecureHashSHA256>(*this);
} }
size_t GetHashLength() const override { return SHA256_DIGEST_LENGTH; } size_t GetHashLength() const override { return SHA256_DIGEST_LENGTH; }
@@ -52,13 +53,13 @@ class SecureHashSHA256 : public SecureHash {
} // namespace } // namespace
SecureHash* SecureHash::Create(Algorithm algorithm) { std::unique_ptr<SecureHash> SecureHash::Create(Algorithm algorithm) {
switch (algorithm) { switch (algorithm) {
case SHA256: case SHA256:
return new SecureHashSHA256(); return base::MakeUnique<SecureHashSHA256>();
default: default:
NOTIMPLEMENTED(); NOTIMPLEMENTED();
return NULL; return nullptr;
} }
} }

@@ -7,6 +7,8 @@
#include <stddef.h> #include <stddef.h>
#include <memory>
#include "base/macros.h" #include "base/macros.h"
#include "crypto/crypto_export.h" #include "crypto/crypto_export.h"
@@ -21,7 +23,7 @@ class CRYPTO_EXPORT SecureHash {
}; };
virtual ~SecureHash() {} virtual ~SecureHash() {}
static SecureHash* Create(Algorithm type); static std::unique_ptr<SecureHash> Create(Algorithm type);
virtual void Update(const void* input, size_t len) = 0; virtual void Update(const void* input, size_t len) = 0;
virtual void Finish(void* output, size_t len) = 0; virtual void Finish(void* output, size_t len) = 0;
@@ -30,7 +32,7 @@ class CRYPTO_EXPORT SecureHash {
// Create a clone of this SecureHash. The returned clone and this both // Create a clone of this SecureHash. The returned clone and this both
// represent the same hash state. But from this point on, calling // represent the same hash state. But from this point on, calling
// Update()/Finish() on either doesn't affect the state of the other. // Update()/Finish() on either doesn't affect the state of the other.
virtual SecureHash* Clone() const = 0; virtual std::unique_ptr<SecureHash> Clone() const = 0;
protected: protected:
SecureHash() {} SecureHash() {}

@@ -9,8 +9,6 @@
#include <stddef.h> #include <stddef.h>
#include <stdint.h> #include <stdint.h>
#include <memory>
#include "base/logging.h" #include "base/logging.h"
#include "crypto/openssl_util.h" #include "crypto/openssl_util.h"
#include "crypto/rsa_private_key.h" #include "crypto/rsa_private_key.h"
@@ -27,7 +25,7 @@ const EVP_MD* ToOpenSSLDigest(SignatureCreator::HashAlgorithm hash_alg) {
case SignatureCreator::SHA256: case SignatureCreator::SHA256:
return EVP_sha256(); return EVP_sha256();
} }
return NULL; return nullptr;
} }
int ToOpenSSLDigestType(SignatureCreator::HashAlgorithm hash_alg) { int ToOpenSSLDigestType(SignatureCreator::HashAlgorithm hash_alg) {
@@ -42,21 +40,26 @@ int ToOpenSSLDigestType(SignatureCreator::HashAlgorithm hash_alg) {
} // namespace } // namespace
SignatureCreator::~SignatureCreator() {
EVP_MD_CTX_destroy(sign_context_);
}
// static // static
SignatureCreator* SignatureCreator::Create(RSAPrivateKey* key, std::unique_ptr<SignatureCreator> SignatureCreator::Create(
HashAlgorithm hash_alg) { RSAPrivateKey* key,
HashAlgorithm hash_alg) {
OpenSSLErrStackTracer err_tracer(FROM_HERE); OpenSSLErrStackTracer err_tracer(FROM_HERE);
std::unique_ptr<SignatureCreator> result(new SignatureCreator); std::unique_ptr<SignatureCreator> result(new SignatureCreator);
const EVP_MD* const digest = ToOpenSSLDigest(hash_alg); const EVP_MD* const digest = ToOpenSSLDigest(hash_alg);
DCHECK(digest); DCHECK(digest);
if (!digest) { if (!digest) {
return NULL; return nullptr;
} }
if (!EVP_DigestSignInit(result->sign_context_, NULL, digest, NULL, if (!EVP_DigestSignInit(result->sign_context_, nullptr, digest, nullptr,
key->key())) { key->key())) {
return NULL; return nullptr;
} }
return result.release(); return result;
} }
// static // static
@@ -80,14 +83,6 @@ bool SignatureCreator::Sign(RSAPrivateKey* key,
return true; return true;
} }
SignatureCreator::SignatureCreator()
: sign_context_(EVP_MD_CTX_create()) {
}
SignatureCreator::~SignatureCreator() {
EVP_MD_CTX_destroy(sign_context_);
}
bool SignatureCreator::Update(const uint8_t* data_part, int data_part_len) { bool SignatureCreator::Update(const uint8_t* data_part, int data_part_len) {
OpenSSLErrStackTracer err_tracer(FROM_HERE); OpenSSLErrStackTracer err_tracer(FROM_HERE);
return !!EVP_DigestSignUpdate(sign_context_, data_part, data_part_len); return !!EVP_DigestSignUpdate(sign_context_, data_part, data_part_len);
@@ -98,7 +93,7 @@ bool SignatureCreator::Final(std::vector<uint8_t>* signature) {
// Determine the maximum length of the signature. // Determine the maximum length of the signature.
size_t len = 0; size_t len = 0;
if (!EVP_DigestSignFinal(sign_context_, NULL, &len)) { if (!EVP_DigestSignFinal(sign_context_, nullptr, &len)) {
signature->clear(); signature->clear();
return false; return false;
} }
@@ -113,4 +108,6 @@ bool SignatureCreator::Final(std::vector<uint8_t>* signature) {
return true; return true;
} }
SignatureCreator::SignatureCreator() : sign_context_(EVP_MD_CTX_create()) {}
} // namespace crypto } // namespace crypto

@@ -7,6 +7,7 @@
#include <stdint.h> #include <stdint.h>
#include <memory>
#include <vector> #include <vector>
#include "base/macros.h" #include "base/macros.h"
@@ -35,8 +36,8 @@ class CRYPTO_EXPORT SignatureCreator {
// Create an instance. The caller must ensure that the provided PrivateKey // Create an instance. The caller must ensure that the provided PrivateKey
// instance outlives the created SignatureCreator. Uses the HashAlgorithm // instance outlives the created SignatureCreator. Uses the HashAlgorithm
// specified. // specified.
static SignatureCreator* Create(RSAPrivateKey* key, HashAlgorithm hash_alg); static std::unique_ptr<SignatureCreator> Create(RSAPrivateKey* key,
HashAlgorithm hash_alg);
// Signs the precomputed |hash_alg| digest |data| using private |key| as // Signs the precomputed |hash_alg| digest |data| using private |key| as
// specified in PKCS #1 v1.5. // specified in PKCS #1 v1.5.

@@ -27,7 +27,7 @@ const EVP_MD* ToOpenSSLDigest(SignatureVerifier::HashAlgorithm hash_alg) {
case SignatureVerifier::SHA256: case SignatureVerifier::SHA256:
return EVP_sha256(); return EVP_sha256();
} }
return NULL; return nullptr;
} }
} // namespace } // namespace
@@ -36,9 +36,7 @@ struct SignatureVerifier::VerifyContext {
ScopedEVP_MD_CTX ctx; ScopedEVP_MD_CTX ctx;
}; };
SignatureVerifier::SignatureVerifier() SignatureVerifier::SignatureVerifier() : verify_context_(nullptr) {}
: verify_context_(NULL) {
}
SignatureVerifier::~SignatureVerifier() { SignatureVerifier::~SignatureVerifier() {
Reset(); Reset();
@@ -153,7 +151,7 @@ bool SignatureVerifier::CommonInit(int pkey_type,
void SignatureVerifier::Reset() { void SignatureVerifier::Reset() {
delete verify_context_; delete verify_context_;
verify_context_ = NULL; verify_context_ = nullptr;
signature_.clear(); signature_.clear();
} }

@@ -10,7 +10,7 @@
#include <stdint.h> #include <stdint.h>
#include <algorithm> #include <algorithm>
#include <memory> #include <utility>
#include "base/logging.h" #include "base/logging.h"
#include "base/strings/string_util.h" #include "base/strings/string_util.h"
@@ -23,21 +23,22 @@ SymmetricKey::~SymmetricKey() {
} }
// static // static
SymmetricKey* SymmetricKey::GenerateRandomKey(Algorithm algorithm, std::unique_ptr<SymmetricKey> SymmetricKey::GenerateRandomKey(
size_t key_size_in_bits) { Algorithm algorithm,
size_t key_size_in_bits) {
DCHECK_EQ(AES, algorithm); DCHECK_EQ(AES, algorithm);
// Whitelist supported key sizes to avoid accidentaly relying on // Whitelist supported key sizes to avoid accidentaly relying on
// algorithms available in NSS but not BoringSSL and vice // algorithms available in NSS but not BoringSSL and vice
// versa. Note that BoringSSL does not support AES-192. // versa. Note that BoringSSL does not support AES-192.
if (key_size_in_bits != 128 && key_size_in_bits != 256) if (key_size_in_bits != 128 && key_size_in_bits != 256)
return NULL; return nullptr;
size_t key_size_in_bytes = key_size_in_bits / 8; size_t key_size_in_bytes = key_size_in_bits / 8;
DCHECK_EQ(key_size_in_bits, key_size_in_bytes * 8); DCHECK_EQ(key_size_in_bits, key_size_in_bytes * 8);
if (key_size_in_bytes == 0) if (key_size_in_bytes == 0)
return NULL; return nullptr;
OpenSSLErrStackTracer err_tracer(FROM_HERE); OpenSSLErrStackTracer err_tracer(FROM_HERE);
std::unique_ptr<SymmetricKey> key(new SymmetricKey); std::unique_ptr<SymmetricKey> key(new SymmetricKey);
@@ -45,15 +46,16 @@ SymmetricKey* SymmetricKey::GenerateRandomKey(Algorithm algorithm,
base::WriteInto(&key->key_, key_size_in_bytes + 1)); base::WriteInto(&key->key_, key_size_in_bytes + 1));
int rv = RAND_bytes(key_data, static_cast<int>(key_size_in_bytes)); int rv = RAND_bytes(key_data, static_cast<int>(key_size_in_bytes));
return rv == 1 ? key.release() : NULL; return rv == 1 ? std::move(key) : nullptr;
} }
// static // static
SymmetricKey* SymmetricKey::DeriveKeyFromPassword(Algorithm algorithm, std::unique_ptr<SymmetricKey> SymmetricKey::DeriveKeyFromPassword(
const std::string& password, Algorithm algorithm,
const std::string& salt, const std::string& password,
size_t iterations, const std::string& salt,
size_t key_size_in_bits) { size_t iterations,
size_t key_size_in_bits) {
DCHECK(algorithm == AES || algorithm == HMAC_SHA1); DCHECK(algorithm == AES || algorithm == HMAC_SHA1);
if (algorithm == AES) { if (algorithm == AES) {
@@ -61,14 +63,14 @@ SymmetricKey* SymmetricKey::DeriveKeyFromPassword(Algorithm algorithm,
// algorithms available in NSS but not BoringSSL and vice // algorithms available in NSS but not BoringSSL and vice
// versa. Note that BoringSSL does not support AES-192. // versa. Note that BoringSSL does not support AES-192.
if (key_size_in_bits != 128 && key_size_in_bits != 256) if (key_size_in_bits != 128 && key_size_in_bits != 256)
return NULL; return nullptr;
} }
size_t key_size_in_bytes = key_size_in_bits / 8; size_t key_size_in_bytes = key_size_in_bits / 8;
DCHECK_EQ(key_size_in_bits, key_size_in_bytes * 8); DCHECK_EQ(key_size_in_bits, key_size_in_bytes * 8);
if (key_size_in_bytes == 0) if (key_size_in_bytes == 0)
return NULL; return nullptr;
OpenSSLErrStackTracer err_tracer(FROM_HERE); OpenSSLErrStackTracer err_tracer(FROM_HERE);
std::unique_ptr<SymmetricKey> key(new SymmetricKey); std::unique_ptr<SymmetricKey> key(new SymmetricKey);
@@ -79,23 +81,23 @@ SymmetricKey* SymmetricKey::DeriveKeyFromPassword(Algorithm algorithm,
reinterpret_cast<const uint8_t*>(salt.data()), salt.length(), reinterpret_cast<const uint8_t*>(salt.data()), salt.length(),
static_cast<unsigned>(iterations), static_cast<unsigned>(iterations),
key_size_in_bytes, key_data); key_size_in_bytes, key_data);
return rv == 1 ? key.release() : NULL; return rv == 1 ? std::move(key) : nullptr;
} }
// static // static
SymmetricKey* SymmetricKey::Import(Algorithm algorithm, std::unique_ptr<SymmetricKey> SymmetricKey::Import(Algorithm algorithm,
const std::string& raw_key) { const std::string& raw_key) {
if (algorithm == AES) { if (algorithm == AES) {
// Whitelist supported key sizes to avoid accidentaly relying on // Whitelist supported key sizes to avoid accidentaly relying on
// algorithms available in NSS but not BoringSSL and vice // algorithms available in NSS but not BoringSSL and vice
// versa. Note that BoringSSL does not support AES-192. // versa. Note that BoringSSL does not support AES-192.
if (raw_key.size() != 128/8 && raw_key.size() != 256/8) if (raw_key.size() != 128/8 && raw_key.size() != 256/8)
return NULL; return nullptr;
} }
std::unique_ptr<SymmetricKey> key(new SymmetricKey); std::unique_ptr<SymmetricKey> key(new SymmetricKey);
key->key_ = raw_key; key->key_ = raw_key;
return key.release(); return key;
} }
bool SymmetricKey::GetRawKey(std::string* raw_key) { bool SymmetricKey::GetRawKey(std::string* raw_key) {
@@ -103,4 +105,6 @@ bool SymmetricKey::GetRawKey(std::string* raw_key) {
return true; return true;
} }
SymmetricKey::SymmetricKey() = default;
} // namespace crypto } // namespace crypto

@@ -7,6 +7,7 @@
#include <stddef.h> #include <stddef.h>
#include <memory>
#include <string> #include <string>
#include "base/macros.h" #include "base/macros.h"
@@ -31,25 +32,28 @@ class CRYPTO_EXPORT SymmetricKey {
// Generates a random key suitable to be used with |algorithm| and of // Generates a random key suitable to be used with |algorithm| and of
// |key_size_in_bits| bits. |key_size_in_bits| must be a multiple of 8. // |key_size_in_bits| bits. |key_size_in_bits| must be a multiple of 8.
// The caller is responsible for deleting the returned SymmetricKey. // The caller is responsible for deleting the returned SymmetricKey.
static SymmetricKey* GenerateRandomKey(Algorithm algorithm, static std::unique_ptr<SymmetricKey> GenerateRandomKey(
size_t key_size_in_bits); Algorithm algorithm,
size_t key_size_in_bits);
// Derives a key from the supplied password and salt using PBKDF2, suitable // Derives a key from the supplied password and salt using PBKDF2, suitable
// for use with specified |algorithm|. Note |algorithm| is not the algorithm // for use with specified |algorithm|. Note |algorithm| is not the algorithm
// used to derive the key from the password. |key_size_in_bits| must be a // used to derive the key from the password. |key_size_in_bits| must be a
// multiple of 8. The caller is responsible for deleting the returned // multiple of 8. The caller is responsible for deleting the returned
// SymmetricKey. // SymmetricKey.
static SymmetricKey* DeriveKeyFromPassword(Algorithm algorithm, static std::unique_ptr<SymmetricKey> DeriveKeyFromPassword(
const std::string& password, Algorithm algorithm,
const std::string& salt, const std::string& password,
size_t iterations, const std::string& salt,
size_t key_size_in_bits); size_t iterations,
size_t key_size_in_bits);
// Imports an array of key bytes in |raw_key|. This key may have been // Imports an array of key bytes in |raw_key|. This key may have been
// generated by GenerateRandomKey or DeriveKeyFromPassword and exported with // generated by GenerateRandomKey or DeriveKeyFromPassword and exported with
// GetRawKey, or via another compatible method. The key must be of suitable // GetRawKey, or via another compatible method. The key must be of suitable
// size for use with |algorithm|. The caller owns the returned SymmetricKey. // size for use with |algorithm|. The caller owns the returned SymmetricKey.
static SymmetricKey* Import(Algorithm algorithm, const std::string& raw_key); static std::unique_ptr<SymmetricKey> Import(Algorithm algorithm,
const std::string& raw_key);
const std::string& key() { return key_; } const std::string& key() { return key_; }
@@ -59,7 +63,8 @@ class CRYPTO_EXPORT SymmetricKey {
bool GetRawKey(std::string* raw_key); bool GetRawKey(std::string* raw_key);
private: private:
SymmetricKey() {} SymmetricKey();
std::string key_; std::string key_;
DISALLOW_COPY_AND_ASSIGN(SymmetricKey); DISALLOW_COPY_AND_ASSIGN(SymmetricKey);

@@ -14,7 +14,7 @@
TEST(SymmetricKeyTest, GenerateRandomKey) { TEST(SymmetricKeyTest, GenerateRandomKey) {
std::unique_ptr<crypto::SymmetricKey> key( std::unique_ptr<crypto::SymmetricKey> key(
crypto::SymmetricKey::GenerateRandomKey(crypto::SymmetricKey::AES, 256)); crypto::SymmetricKey::GenerateRandomKey(crypto::SymmetricKey::AES, 256));
ASSERT_TRUE(NULL != key.get()); ASSERT_TRUE(key);
std::string raw_key; std::string raw_key;
EXPECT_TRUE(key->GetRawKey(&raw_key)); EXPECT_TRUE(key->GetRawKey(&raw_key));
EXPECT_EQ(32U, raw_key.size()); EXPECT_EQ(32U, raw_key.size());
@@ -23,7 +23,7 @@ TEST(SymmetricKeyTest, GenerateRandomKey) {
// (Note: this has a one-in-10^77 chance of failure!) // (Note: this has a one-in-10^77 chance of failure!)
std::unique_ptr<crypto::SymmetricKey> key2( std::unique_ptr<crypto::SymmetricKey> key2(
crypto::SymmetricKey::GenerateRandomKey(crypto::SymmetricKey::AES, 256)); crypto::SymmetricKey::GenerateRandomKey(crypto::SymmetricKey::AES, 256));
ASSERT_TRUE(NULL != key2.get()); ASSERT_TRUE(key2);
std::string raw_key2; std::string raw_key2;
EXPECT_TRUE(key2->GetRawKey(&raw_key2)); EXPECT_TRUE(key2->GetRawKey(&raw_key2));
EXPECT_EQ(32U, raw_key2.size()); EXPECT_EQ(32U, raw_key2.size());
@@ -33,13 +33,13 @@ TEST(SymmetricKeyTest, GenerateRandomKey) {
TEST(SymmetricKeyTest, ImportGeneratedKey) { TEST(SymmetricKeyTest, ImportGeneratedKey) {
std::unique_ptr<crypto::SymmetricKey> key1( std::unique_ptr<crypto::SymmetricKey> key1(
crypto::SymmetricKey::GenerateRandomKey(crypto::SymmetricKey::AES, 256)); crypto::SymmetricKey::GenerateRandomKey(crypto::SymmetricKey::AES, 256));
ASSERT_TRUE(NULL != key1.get()); ASSERT_TRUE(key1);
std::string raw_key1; std::string raw_key1;
EXPECT_TRUE(key1->GetRawKey(&raw_key1)); EXPECT_TRUE(key1->GetRawKey(&raw_key1));
std::unique_ptr<crypto::SymmetricKey> key2( std::unique_ptr<crypto::SymmetricKey> key2(
crypto::SymmetricKey::Import(crypto::SymmetricKey::AES, raw_key1)); crypto::SymmetricKey::Import(crypto::SymmetricKey::AES, raw_key1));
ASSERT_TRUE(NULL != key2.get()); ASSERT_TRUE(key2);
std::string raw_key2; std::string raw_key2;
EXPECT_TRUE(key2->GetRawKey(&raw_key2)); EXPECT_TRUE(key2->GetRawKey(&raw_key2));
@@ -51,13 +51,13 @@ TEST(SymmetricKeyTest, ImportDerivedKey) {
std::unique_ptr<crypto::SymmetricKey> key1( std::unique_ptr<crypto::SymmetricKey> key1(
crypto::SymmetricKey::DeriveKeyFromPassword( crypto::SymmetricKey::DeriveKeyFromPassword(
crypto::SymmetricKey::HMAC_SHA1, "password", "somesalt", 1024, 160)); crypto::SymmetricKey::HMAC_SHA1, "password", "somesalt", 1024, 160));
ASSERT_TRUE(NULL != key1.get()); ASSERT_TRUE(key1);
std::string raw_key1; std::string raw_key1;
EXPECT_TRUE(key1->GetRawKey(&raw_key1)); EXPECT_TRUE(key1->GetRawKey(&raw_key1));
std::unique_ptr<crypto::SymmetricKey> key2( std::unique_ptr<crypto::SymmetricKey> key2(
crypto::SymmetricKey::Import(crypto::SymmetricKey::HMAC_SHA1, raw_key1)); crypto::SymmetricKey::Import(crypto::SymmetricKey::HMAC_SHA1, raw_key1));
ASSERT_TRUE(NULL != key2.get()); ASSERT_TRUE(key2);
std::string raw_key2; std::string raw_key2;
EXPECT_TRUE(key2->GetRawKey(&raw_key2)); EXPECT_TRUE(key2->GetRawKey(&raw_key2));
@@ -84,7 +84,7 @@ TEST_P(SymmetricKeyDeriveKeyFromPasswordTest, DeriveKeyFromPassword) {
crypto::SymmetricKey::DeriveKeyFromPassword( crypto::SymmetricKey::DeriveKeyFromPassword(
test_data.algorithm, test_data.password, test_data.salt, test_data.algorithm, test_data.password, test_data.salt,
test_data.rounds, test_data.key_size_in_bits)); test_data.rounds, test_data.key_size_in_bits));
ASSERT_TRUE(NULL != key.get()); ASSERT_TRUE(key);
std::string raw_key; std::string raw_key;
key->GetRawKey(&raw_key); key->GetRawKey(&raw_key);

@@ -22,4 +22,4 @@
#define WINCRYPT_X509_EXTENSIONS ((LPCSTR) 5) #define WINCRYPT_X509_EXTENSIONS ((LPCSTR) 5)
#define WINCRYPT_X509_NAME ((LPCSTR) 7) #define WINCRYPT_X509_NAME ((LPCSTR) 7)
#endif // NET_CRYPTO_WINCRYPT_SHIM_H_ #endif // NET_CRYPTO_WINCRYPT_SHIM_H_

@@ -96,10 +96,9 @@ void ContentVerifyJob::BytesRead(int count, const char* data) {
if (current_block_ >= hash_reader_->block_count()) if (current_block_ >= hash_reader_->block_count())
return DispatchFailureCallback(HASH_MISMATCH); return DispatchFailureCallback(HASH_MISMATCH);
if (!current_hash_.get()) { if (!current_hash_) {
current_hash_byte_count_ = 0; current_hash_byte_count_ = 0;
current_hash_.reset( current_hash_ = crypto::SecureHash::Create(crypto::SecureHash::SHA256);
crypto::SecureHash::Create(crypto::SecureHash::SHA256));
} }
// Compute how many bytes we should hash, and add them to the current hash. // Compute how many bytes we should hash, and add them to the current hash.
int bytes_to_hash = int bytes_to_hash =

@@ -51,8 +51,7 @@ bool TransportEncryptionHandler::Initialize(const std::string& aes_key,
is_activated_ = false; is_activated_ = false;
if (aes_iv_mask.size() == kAesKeySize && aes_key.size() == kAesKeySize) { if (aes_iv_mask.size() == kAesKeySize && aes_key.size() == kAesKeySize) {
iv_mask_ = aes_iv_mask; iv_mask_ = aes_iv_mask;
key_.reset( key_ = crypto::SymmetricKey::Import(crypto::SymmetricKey::AES, aes_key);
crypto::SymmetricKey::Import(crypto::SymmetricKey::AES, aes_key));
encryptor_.reset(new crypto::Encryptor()); encryptor_.reset(new crypto::Encryptor());
encryptor_->Init(key_.get(), crypto::Encryptor::CTR, std::string()); encryptor_->Init(key_.get(), crypto::Encryptor::CTR, std::string());
is_activated_ = true; is_activated_ = true;

@@ -481,9 +481,8 @@ void AesDecryptor::Decrypt(StreamType stream_type,
return; return;
} }
crypto::SymmetricKey* decryption_key = key->decryption_key(); decrypted = DecryptData(*encrypted.get(), key->decryption_key());
decrypted = DecryptData(*encrypted.get(), decryption_key); if (!decrypted) {
if (!decrypted.get()) {
DVLOG(1) << "Decryption failed."; DVLOG(1) << "Decryption failed.";
decrypt_cb.Run(kError, NULL); decrypt_cb.Run(kError, NULL);
return; return;
@@ -607,8 +606,8 @@ AesDecryptor::DecryptionKey::~DecryptionKey() {}
bool AesDecryptor::DecryptionKey::Init() { bool AesDecryptor::DecryptionKey::Init() {
CHECK(!secret_.empty()); CHECK(!secret_.empty());
decryption_key_.reset(crypto::SymmetricKey::Import( decryption_key_ =
crypto::SymmetricKey::AES, secret_)); crypto::SymmetricKey::Import(crypto::SymmetricKey::AES, secret_);
if (!decryption_key_) if (!decryption_key_)
return false; return false;
return true; return true;

@@ -10,7 +10,6 @@
#include "base/bind.h" #include "base/bind.h"
#include "base/files/file_util.h" #include "base/files/file_util.h"
#include "base/files/scoped_temp_dir.h" #include "base/files/scoped_temp_dir.h"
#include "base/memory/ptr_util.h"
#include "base/memory/ref_counted.h" #include "base/memory/ref_counted.h"
#include "base/run_loop.h" #include "base/run_loop.h"
#include "base/threading/thread_task_runner_handle.h" #include "base/threading/thread_task_runner_handle.h"
@@ -66,8 +65,8 @@ class SQLiteChannelIDStoreTest : public testing::Test {
ASSERT_TRUE(asn1::ExtractSPKIFromDERCert(*cert_data, &spki)); ASSERT_TRUE(asn1::ExtractSPKIFromDERCert(*cert_data, &spki));
std::vector<uint8_t> public_key(spki.size()); std::vector<uint8_t> public_key(spki.size());
memcpy(public_key.data(), spki.data(), spki.size()); memcpy(public_key.data(), spki.data(), spki.size());
key->reset(crypto::ECPrivateKey::CreateFromEncryptedPrivateKeyInfo( *key = crypto::ECPrivateKey::CreateFromEncryptedPrivateKeyInfo(
ChannelIDService::kEPKIPassword, private_key, public_key)); ChannelIDService::kEPKIPassword, private_key, public_key);
} }
static base::Time GetTestCertExpirationTime() { static base::Time GetTestCertExpirationTime() {
@@ -111,10 +110,9 @@ class SQLiteChannelIDStoreTest : public testing::Test {
Load(&channel_ids); Load(&channel_ids);
ASSERT_EQ(0u, channel_ids.size()); ASSERT_EQ(0u, channel_ids.size());
// Make sure the store gets written at least once. // Make sure the store gets written at least once.
google_key_.reset(crypto::ECPrivateKey::Create()); google_key_ = crypto::ECPrivateKey::Create();
store_->AddChannelID(DefaultChannelIDStore::ChannelID( store_->AddChannelID(DefaultChannelIDStore::ChannelID(
"google.com", base::Time::FromInternalValue(1), "google.com", base::Time::FromInternalValue(1), google_key_->Copy()));
base::WrapUnique(google_key_->Copy())));
} }
base::ScopedTempDir temp_dir_; base::ScopedTempDir temp_dir_;
@@ -127,8 +125,7 @@ class SQLiteChannelIDStoreTest : public testing::Test {
TEST_F(SQLiteChannelIDStoreTest, TestPersistence) { TEST_F(SQLiteChannelIDStoreTest, TestPersistence) {
std::unique_ptr<crypto::ECPrivateKey> foo_key(crypto::ECPrivateKey::Create()); std::unique_ptr<crypto::ECPrivateKey> foo_key(crypto::ECPrivateKey::Create());
store_->AddChannelID(DefaultChannelIDStore::ChannelID( store_->AddChannelID(DefaultChannelIDStore::ChannelID(
"foo.com", base::Time::FromInternalValue(3), "foo.com", base::Time::FromInternalValue(3), foo_key->Copy()));
base::WrapUnique(foo_key->Copy())));
std::vector<std::unique_ptr<DefaultChannelIDStore::ChannelID>> channel_ids; std::vector<std::unique_ptr<DefaultChannelIDStore::ChannelID>> channel_ids;
// Replace the store effectively destroying the current one and forcing it // Replace the store effectively destroying the current one and forcing it
@@ -184,7 +181,7 @@ TEST_F(SQLiteChannelIDStoreTest, TestPersistence) {
TEST_F(SQLiteChannelIDStoreTest, TestDeleteAll) { TEST_F(SQLiteChannelIDStoreTest, TestDeleteAll) {
store_->AddChannelID(DefaultChannelIDStore::ChannelID( store_->AddChannelID(DefaultChannelIDStore::ChannelID(
"foo.com", base::Time::FromInternalValue(3), "foo.com", base::Time::FromInternalValue(3),
base::WrapUnique(crypto::ECPrivateKey::Create()))); crypto::ECPrivateKey::Create()));
std::vector<std::unique_ptr<DefaultChannelIDStore::ChannelID>> channel_ids; std::vector<std::unique_ptr<DefaultChannelIDStore::ChannelID>> channel_ids;
// Replace the store effectively destroying the current one and forcing it // Replace the store effectively destroying the current one and forcing it

@@ -7,7 +7,6 @@
#include <stdint.h> #include <stdint.h>
#include <cstddef> #include <cstddef>
#include <memory>
#include <utility> #include <utility>
#include "base/compiler_specific.h" #include "base/compiler_specific.h"
@@ -324,12 +323,12 @@ MockECSignatureCreatorFactory::MockECSignatureCreatorFactory() {
} }
MockECSignatureCreatorFactory::~MockECSignatureCreatorFactory() { MockECSignatureCreatorFactory::~MockECSignatureCreatorFactory() {
crypto::ECSignatureCreator::SetFactoryForTesting(NULL); crypto::ECSignatureCreator::SetFactoryForTesting(nullptr);
} }
crypto::ECSignatureCreator* MockECSignatureCreatorFactory::Create( std::unique_ptr<crypto::ECSignatureCreator>
crypto::ECPrivateKey* key) { MockECSignatureCreatorFactory::Create(crypto::ECPrivateKey* key) {
return new MockECSignatureCreator(key); return base::MakeUnique<MockECSignatureCreator>(key);
} }
SpdySessionDependencies::SpdySessionDependencies(NextProto protocol) SpdySessionDependencies::SpdySessionDependencies(NextProto protocol)

@@ -164,7 +164,8 @@ class MockECSignatureCreatorFactory : public crypto::ECSignatureCreatorFactory {
~MockECSignatureCreatorFactory() override; ~MockECSignatureCreatorFactory() override;
// crypto::ECSignatureCreatorFactory // crypto::ECSignatureCreatorFactory
crypto::ECSignatureCreator* Create(crypto::ECPrivateKey* key) override; std::unique_ptr<crypto::ECSignatureCreator> Create(
crypto::ECPrivateKey* key) override;
private: private:
DISALLOW_COPY_AND_ASSIGN(MockECSignatureCreatorFactory); DISALLOW_COPY_AND_ASSIGN(MockECSignatureCreatorFactory);

@@ -192,7 +192,7 @@ class ChannelIDServiceJob {
i != requests.end(); i++) { i != requests.end(); i++) {
std::unique_ptr<crypto::ECPrivateKey> key_copy; std::unique_ptr<crypto::ECPrivateKey> key_copy;
if (key) if (key)
key_copy.reset(key->Copy()); key_copy = key->Copy();
(*i)->Post(error, std::move(key_copy)); (*i)->Post(error, std::move(key_copy));
} }
} }
@@ -439,7 +439,7 @@ void ChannelIDService::GeneratedChannelID(
std::unique_ptr<crypto::ECPrivateKey> key; std::unique_ptr<crypto::ECPrivateKey> key;
if (error == OK) { if (error == OK) {
key.reset(channel_id->key()->Copy()); key = channel_id->key()->Copy();
channel_id_store_->SetChannelID(std::move(channel_id)); channel_id_store_->SetChannelID(std::move(channel_id));
} }
HandleResult(error, server_identifier, std::move(key)); HandleResult(error, server_identifier, std::move(key));

@@ -11,7 +11,6 @@
#include "base/bind.h" #include "base/bind.h"
#include "base/location.h" #include "base/location.h"
#include "base/macros.h" #include "base/macros.h"
#include "base/memory/ptr_util.h"
#include "base/run_loop.h" #include "base/run_loop.h"
#include "base/single_thread_task_runner.h" #include "base/single_thread_task_runner.h"
#include "base/strings/string_number_conversions.h" #include "base/strings/string_number_conversions.h"
@@ -100,9 +99,8 @@ void MockChannelIDStoreWithAsyncGet::CallGetChannelIDCallbackWithResult(
if (err == OK) if (err == OK)
channel_id_count_ = 1; channel_id_count_ = 1;
base::ThreadTaskRunnerHandle::Get()->PostTask( base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, FROM_HERE, base::Bind(callback_, err, server_identifier_,
base::Bind(callback_, err, server_identifier_, base::Passed(key ? key->Copy() : nullptr)));
base::Passed(base::WrapUnique(key ? key->Copy() : nullptr))));
} }
class ChannelIDServiceTest : public testing::Test { class ChannelIDServiceTest : public testing::Test {

@@ -33,7 +33,7 @@ ChannelIDStore::ChannelID& ChannelIDStore::ChannelID::operator=(
server_identifier_ = other.server_identifier_; server_identifier_ = other.server_identifier_;
creation_time_ = other.creation_time_; creation_time_ = other.creation_time_;
if (other.key_) if (other.key_)
key_.reset(other.key_->Copy()); key_ = other.key_->Copy();
return *this; return *this;
} }

@@ -242,7 +242,7 @@ int DefaultChannelIDStore::GetChannelID(
return ERR_FILE_NOT_FOUND; return ERR_FILE_NOT_FOUND;
ChannelID* channel_id = it->second; ChannelID* channel_id = it->second;
key_result->reset(channel_id->key()->Copy()); *key_result = channel_id->key()->Copy();
return OK; return OK;
} }
@@ -290,7 +290,7 @@ void DefaultChannelIDStore::SetForceKeepSessionState() {
DCHECK(CalledOnValidThread()); DCHECK(CalledOnValidThread());
InitIfNecessary(); InitIfNecessary();
if (store_.get()) if (store_)
store_->SetForceKeepSessionState(); store_->SetForceKeepSessionState();
} }
@@ -310,7 +310,7 @@ void DefaultChannelIDStore::DeleteAllInMemory() {
void DefaultChannelIDStore::InitStore() { void DefaultChannelIDStore::InitStore() {
DCHECK(CalledOnValidThread()); DCHECK(CalledOnValidThread());
DCHECK(store_.get()) << "Store must exist to initialize"; DCHECK(store_) << "Store must exist to initialize";
DCHECK(!loaded_); DCHECK(!loaded_);
store_->Load(base::Bind(&DefaultChannelIDStore::OnLoaded, store_->Load(base::Bind(&DefaultChannelIDStore::OnLoaded,
@@ -381,7 +381,7 @@ void DefaultChannelIDStore::SyncDeleteForDomainsCreatedBetween(
channel_id->creation_time() >= delete_begin) && channel_id->creation_time() >= delete_begin) &&
(delete_end.is_null() || channel_id->creation_time() < delete_end) && (delete_end.is_null() || channel_id->creation_time() < delete_end) &&
domain_predicate.Run(channel_id->server_identifier())) { domain_predicate.Run(channel_id->server_identifier())) {
if (store_.get()) if (store_)
store_->DeleteChannelID(*channel_id); store_->DeleteChannelID(*channel_id);
delete channel_id; delete channel_id;
channel_ids_.erase(cur); channel_ids_.erase(cur);
@@ -428,7 +428,7 @@ void DefaultChannelIDStore::InternalDeleteChannelID(
return; // There is nothing to delete. return; // There is nothing to delete.
ChannelID* channel_id = it->second; ChannelID* channel_id = it->second;
if (store_.get()) if (store_)
store_->DeleteChannelID(*channel_id); store_->DeleteChannelID(*channel_id);
channel_ids_.erase(it); channel_ids_.erase(it);
delete channel_id; delete channel_id;
@@ -439,14 +439,14 @@ void DefaultChannelIDStore::InternalInsertChannelID(
DCHECK(CalledOnValidThread()); DCHECK(CalledOnValidThread());
DCHECK(loaded_); DCHECK(loaded_);
if (store_.get()) if (store_)
store_->AddChannelID(*(channel_id.get())); store_->AddChannelID(*channel_id);
const std::string& server_identifier = channel_id->server_identifier(); const std::string& server_identifier = channel_id->server_identifier();
channel_ids_[server_identifier] = channel_id.release(); channel_ids_[server_identifier] = channel_id.release();
} }
bool DefaultChannelIDStore::IsEphemeral() { bool DefaultChannelIDStore::IsEphemeral() {
return store_.get() == nullptr; return !store_;
} }
DefaultChannelIDStore::PersistentStore::PersistentStore() {} DefaultChannelIDStore::PersistentStore::PersistentStore() {}

@@ -132,25 +132,21 @@ TEST(DefaultChannelIDStoreTest, TestLoading) {
scoped_refptr<MockPersistentStore> persistent_store(new MockPersistentStore); scoped_refptr<MockPersistentStore> persistent_store(new MockPersistentStore);
persistent_store->AddChannelID(DefaultChannelIDStore::ChannelID( persistent_store->AddChannelID(DefaultChannelIDStore::ChannelID(
"google.com", base::Time(), "google.com", base::Time(), crypto::ECPrivateKey::Create()));
base::WrapUnique(crypto::ECPrivateKey::Create())));
persistent_store->AddChannelID(DefaultChannelIDStore::ChannelID( persistent_store->AddChannelID(DefaultChannelIDStore::ChannelID(
"verisign.com", base::Time(), "verisign.com", base::Time(), crypto::ECPrivateKey::Create()));
base::WrapUnique(crypto::ECPrivateKey::Create())));
// Make sure channel_ids load properly. // Make sure channel_ids load properly.
DefaultChannelIDStore store(persistent_store.get()); DefaultChannelIDStore store(persistent_store.get());
// Load has not occurred yet. // Load has not occurred yet.
EXPECT_EQ(0, store.GetChannelIDCount()); EXPECT_EQ(0, store.GetChannelIDCount());
store.SetChannelID(base::WrapUnique(new ChannelIDStore::ChannelID( store.SetChannelID(base::WrapUnique(new ChannelIDStore::ChannelID(
"verisign.com", base::Time(), "verisign.com", base::Time(), crypto::ECPrivateKey::Create())));
base::WrapUnique(crypto::ECPrivateKey::Create()))));
// Wait for load & queued set task. // Wait for load & queued set task.
base::RunLoop().RunUntilIdle(); base::RunLoop().RunUntilIdle();
EXPECT_EQ(2, store.GetChannelIDCount()); EXPECT_EQ(2, store.GetChannelIDCount());
store.SetChannelID(base::WrapUnique(new ChannelIDStore::ChannelID( store.SetChannelID(base::WrapUnique(new ChannelIDStore::ChannelID(
"twitter.com", base::Time(), "twitter.com", base::Time(), crypto::ECPrivateKey::Create())));
base::WrapUnique(crypto::ECPrivateKey::Create()))));
// Set should be synchronous now that load is done. // Set should be synchronous now that load is done.
EXPECT_EQ(3, store.GetChannelIDCount()); EXPECT_EQ(3, store.GetChannelIDCount());
} }
@@ -170,7 +166,7 @@ TEST(DefaultChannelIDStoreTest, TestSettingAndGetting) {
EXPECT_FALSE(key); EXPECT_FALSE(key);
store.SetChannelID(base::WrapUnique(new ChannelIDStore::ChannelID( store.SetChannelID(base::WrapUnique(new ChannelIDStore::ChannelID(
"verisign.com", base::Time::FromInternalValue(123), "verisign.com", base::Time::FromInternalValue(123),
base::WrapUnique(expected_key->Copy())))); expected_key->Copy())));
EXPECT_EQ(OK, store.GetChannelID("verisign.com", &key, EXPECT_EQ(OK, store.GetChannelID("verisign.com", &key,
base::Bind(&GetChannelIDCallbackNotCalled))); base::Bind(&GetChannelIDCallbackNotCalled)));
EXPECT_TRUE(KeysEqual(expected_key.get(), key.get())); EXPECT_TRUE(KeysEqual(expected_key.get(), key.get()));
@@ -186,10 +182,10 @@ TEST(DefaultChannelIDStoreTest, TestDuplicateChannelIds) {
EXPECT_EQ(0, store.GetChannelIDCount()); EXPECT_EQ(0, store.GetChannelIDCount());
store.SetChannelID(base::WrapUnique(new ChannelIDStore::ChannelID( store.SetChannelID(base::WrapUnique(new ChannelIDStore::ChannelID(
"verisign.com", base::Time::FromInternalValue(123), "verisign.com", base::Time::FromInternalValue(123),
base::WrapUnique(crypto::ECPrivateKey::Create())))); crypto::ECPrivateKey::Create())));
store.SetChannelID(base::WrapUnique(new ChannelIDStore::ChannelID( store.SetChannelID(base::WrapUnique(new ChannelIDStore::ChannelID(
"verisign.com", base::Time::FromInternalValue(456), "verisign.com", base::Time::FromInternalValue(456),
base::WrapUnique(expected_key->Copy())))); expected_key->Copy())));
// Wait for load & queued set tasks. // Wait for load & queued set tasks.
base::RunLoop().RunUntilIdle(); base::RunLoop().RunUntilIdle();
@@ -205,7 +201,7 @@ TEST(DefaultChannelIDStoreTest, TestAsyncGet) {
crypto::ECPrivateKey::Create()); crypto::ECPrivateKey::Create());
persistent_store->AddChannelID(ChannelIDStore::ChannelID( persistent_store->AddChannelID(ChannelIDStore::ChannelID(
"verisign.com", base::Time::FromInternalValue(123), "verisign.com", base::Time::FromInternalValue(123),
base::WrapUnique(expected_key->Copy()))); expected_key->Copy()));
DefaultChannelIDStore store(persistent_store.get()); DefaultChannelIDStore store(persistent_store.get());
AsyncGetChannelIDHelper helper; AsyncGetChannelIDHelper helper;
@@ -231,14 +227,11 @@ TEST(DefaultChannelIDStoreTest, TestDeleteAll) {
DefaultChannelIDStore store(persistent_store.get()); DefaultChannelIDStore store(persistent_store.get());
store.SetChannelID(base::WrapUnique(new ChannelIDStore::ChannelID( store.SetChannelID(base::WrapUnique(new ChannelIDStore::ChannelID(
"verisign.com", base::Time(), "verisign.com", base::Time(), crypto::ECPrivateKey::Create())));
base::WrapUnique(crypto::ECPrivateKey::Create()))));
store.SetChannelID(base::WrapUnique(new ChannelIDStore::ChannelID( store.SetChannelID(base::WrapUnique(new ChannelIDStore::ChannelID(
"google.com", base::Time(), "google.com", base::Time(), crypto::ECPrivateKey::Create())));
base::WrapUnique(crypto::ECPrivateKey::Create()))));
store.SetChannelID(base::WrapUnique(new ChannelIDStore::ChannelID( store.SetChannelID(base::WrapUnique(new ChannelIDStore::ChannelID(
"harvard.com", base::Time(), "harvard.com", base::Time(), crypto::ECPrivateKey::Create())));
base::WrapUnique(crypto::ECPrivateKey::Create()))));
// Wait for load & queued set tasks. // Wait for load & queued set tasks.
base::RunLoop().RunUntilIdle(); base::RunLoop().RunUntilIdle();
@@ -254,14 +247,11 @@ TEST(DefaultChannelIDStoreTest, TestDeleteForDomains) {
DefaultChannelIDStore store(persistent_store.get()); DefaultChannelIDStore store(persistent_store.get());
store.SetChannelID(base::WrapUnique(new ChannelIDStore::ChannelID( store.SetChannelID(base::WrapUnique(new ChannelIDStore::ChannelID(
"verisign.com", base::Time(), "verisign.com", base::Time(), crypto::ECPrivateKey::Create())));
base::WrapUnique(crypto::ECPrivateKey::Create()))));
store.SetChannelID(base::WrapUnique(new ChannelIDStore::ChannelID( store.SetChannelID(base::WrapUnique(new ChannelIDStore::ChannelID(
"google.com", base::Time(), "google.com", base::Time(), crypto::ECPrivateKey::Create())));
base::WrapUnique(crypto::ECPrivateKey::Create()))));
store.SetChannelID(base::WrapUnique(new ChannelIDStore::ChannelID( store.SetChannelID(base::WrapUnique(new ChannelIDStore::ChannelID(
"harvard.com", base::Time(), "harvard.com", base::Time(), crypto::ECPrivateKey::Create())));
base::WrapUnique(crypto::ECPrivateKey::Create()))));
// Wait for load & queued set tasks. // Wait for load & queued set tasks.
base::RunLoop().RunUntilIdle(); base::RunLoop().RunUntilIdle();
EXPECT_EQ(3, store.GetChannelIDCount()); EXPECT_EQ(3, store.GetChannelIDCount());
@@ -293,11 +283,9 @@ TEST(DefaultChannelIDStoreTest, TestDeleteForDomains) {
TEST(DefaultChannelIDStoreTest, TestAsyncGetAndDeleteAll) { TEST(DefaultChannelIDStoreTest, TestAsyncGetAndDeleteAll) {
scoped_refptr<MockPersistentStore> persistent_store(new MockPersistentStore); scoped_refptr<MockPersistentStore> persistent_store(new MockPersistentStore);
persistent_store->AddChannelID(ChannelIDStore::ChannelID( persistent_store->AddChannelID(ChannelIDStore::ChannelID(
"verisign.com", base::Time(), "verisign.com", base::Time(), crypto::ECPrivateKey::Create()));
base::WrapUnique(crypto::ECPrivateKey::Create())));
persistent_store->AddChannelID(ChannelIDStore::ChannelID( persistent_store->AddChannelID(ChannelIDStore::ChannelID(
"google.com", base::Time(), "google.com", base::Time(), crypto::ECPrivateKey::Create()));
base::WrapUnique(crypto::ECPrivateKey::Create())));
ChannelIDStore::ChannelIDList pre_channel_ids; ChannelIDStore::ChannelIDList pre_channel_ids;
ChannelIDStore::ChannelIDList post_channel_ids; ChannelIDStore::ChannelIDList post_channel_ids;
@@ -323,14 +311,12 @@ TEST(DefaultChannelIDStoreTest, TestDelete) {
std::unique_ptr<crypto::ECPrivateKey> key; std::unique_ptr<crypto::ECPrivateKey> key;
EXPECT_EQ(0, store.GetChannelIDCount()); EXPECT_EQ(0, store.GetChannelIDCount());
store.SetChannelID(base::WrapUnique(new ChannelIDStore::ChannelID( store.SetChannelID(base::WrapUnique(new ChannelIDStore::ChannelID(
"verisign.com", base::Time(), "verisign.com", base::Time(), crypto::ECPrivateKey::Create())));
base::WrapUnique(crypto::ECPrivateKey::Create()))));
// Wait for load & queued set task. // Wait for load & queued set task.
base::RunLoop().RunUntilIdle(); base::RunLoop().RunUntilIdle();
store.SetChannelID(base::WrapUnique(new ChannelIDStore::ChannelID( store.SetChannelID(base::WrapUnique(new ChannelIDStore::ChannelID(
"google.com", base::Time(), "google.com", base::Time(), crypto::ECPrivateKey::Create())));
base::WrapUnique(crypto::ECPrivateKey::Create()))));
EXPECT_EQ(2, store.GetChannelIDCount()); EXPECT_EQ(2, store.GetChannelIDCount());
int delete_finished = 0; int delete_finished = 0;
@@ -357,12 +343,11 @@ TEST(DefaultChannelIDStoreTest, TestAsyncDelete) {
scoped_refptr<MockPersistentStore> persistent_store(new MockPersistentStore); scoped_refptr<MockPersistentStore> persistent_store(new MockPersistentStore);
std::unique_ptr<crypto::ECPrivateKey> expected_key( std::unique_ptr<crypto::ECPrivateKey> expected_key(
crypto::ECPrivateKey::Create()); crypto::ECPrivateKey::Create());
persistent_store->AddChannelID(ChannelIDStore::ChannelID(
"a.com", base::Time::FromInternalValue(1),
base::WrapUnique(crypto::ECPrivateKey::Create())));
persistent_store->AddChannelID( persistent_store->AddChannelID(
ChannelIDStore::ChannelID("b.com", base::Time::FromInternalValue(3), ChannelIDStore::ChannelID("a.com", base::Time::FromInternalValue(1),
base::WrapUnique(expected_key->Copy()))); crypto::ECPrivateKey::Create()));
persistent_store->AddChannelID(ChannelIDStore::ChannelID(
"b.com", base::Time::FromInternalValue(3), expected_key->Copy()));
DefaultChannelIDStore store(persistent_store.get()); DefaultChannelIDStore store(persistent_store.get());
int delete_finished = 0; int delete_finished = 0;
store.DeleteChannelID("a.com", store.DeleteChannelID("a.com",
@@ -405,17 +390,13 @@ TEST(DefaultChannelIDStoreTest, TestGetAll) {
EXPECT_EQ(0, store.GetChannelIDCount()); EXPECT_EQ(0, store.GetChannelIDCount());
store.SetChannelID(base::WrapUnique(new ChannelIDStore::ChannelID( store.SetChannelID(base::WrapUnique(new ChannelIDStore::ChannelID(
"verisign.com", base::Time(), "verisign.com", base::Time(), crypto::ECPrivateKey::Create())));
base::WrapUnique(crypto::ECPrivateKey::Create()))));
store.SetChannelID(base::WrapUnique(new ChannelIDStore::ChannelID( store.SetChannelID(base::WrapUnique(new ChannelIDStore::ChannelID(
"google.com", base::Time(), "google.com", base::Time(), crypto::ECPrivateKey::Create())));
base::WrapUnique(crypto::ECPrivateKey::Create()))));
store.SetChannelID(base::WrapUnique(new ChannelIDStore::ChannelID( store.SetChannelID(base::WrapUnique(new ChannelIDStore::ChannelID(
"harvard.com", base::Time(), "harvard.com", base::Time(), crypto::ECPrivateKey::Create())));
base::WrapUnique(crypto::ECPrivateKey::Create()))));
store.SetChannelID(base::WrapUnique(new ChannelIDStore::ChannelID( store.SetChannelID(base::WrapUnique(new ChannelIDStore::ChannelID(
"mit.com", base::Time(), "mit.com", base::Time(), crypto::ECPrivateKey::Create())));
base::WrapUnique(crypto::ECPrivateKey::Create()))));
// Wait for load & queued set tasks. // Wait for load & queued set tasks.
base::RunLoop().RunUntilIdle(); base::RunLoop().RunUntilIdle();
@@ -436,11 +417,9 @@ TEST(DefaultChannelIDStoreTest, TestInitializeFrom) {
crypto::ECPrivateKey::Create()); crypto::ECPrivateKey::Create());
store.SetChannelID(base::WrapUnique(new ChannelIDStore::ChannelID( store.SetChannelID(base::WrapUnique(new ChannelIDStore::ChannelID(
"preexisting.com", base::Time(), "preexisting.com", base::Time(), preexisting_key->Copy())));
base::WrapUnique(preexisting_key->Copy()))));
store.SetChannelID(base::WrapUnique(new ChannelIDStore::ChannelID( store.SetChannelID(base::WrapUnique(new ChannelIDStore::ChannelID(
"both.com", base::Time(), "both.com", base::Time(), crypto::ECPrivateKey::Create())));
base::WrapUnique(crypto::ECPrivateKey::Create()))));
// Wait for load & queued set tasks. // Wait for load & queued set tasks.
base::RunLoop().RunUntilIdle(); base::RunLoop().RunUntilIdle();
EXPECT_EQ(2, store.GetChannelIDCount()); EXPECT_EQ(2, store.GetChannelIDCount());
@@ -449,9 +428,9 @@ TEST(DefaultChannelIDStoreTest, TestInitializeFrom) {
source_channel_ids.push_back(ChannelIDStore::ChannelID( source_channel_ids.push_back(ChannelIDStore::ChannelID(
"both.com", base::Time(), "both.com", base::Time(),
// Key differs from above to test that existing entries are overwritten. // Key differs from above to test that existing entries are overwritten.
base::WrapUnique(both_key->Copy()))); both_key->Copy()));
source_channel_ids.push_back(ChannelIDStore::ChannelID( source_channel_ids.push_back(ChannelIDStore::ChannelID(
"copied.com", base::Time(), base::WrapUnique(copied_key->Copy()))); "copied.com", base::Time(), copied_key->Copy()));
store.InitializeFrom(source_channel_ids); store.InitializeFrom(source_channel_ids);
EXPECT_EQ(3, store.GetChannelIDCount()); EXPECT_EQ(3, store.GetChannelIDCount());
@@ -481,21 +460,19 @@ TEST(DefaultChannelIDStoreTest, TestAsyncInitializeFrom) {
std::unique_ptr<crypto::ECPrivateKey> copied_key( std::unique_ptr<crypto::ECPrivateKey> copied_key(
crypto::ECPrivateKey::Create()); crypto::ECPrivateKey::Create());
persistent_store->AddChannelID(
ChannelIDStore::ChannelID("preexisting.com", base::Time(),
base::WrapUnique(preexisting_key->Copy())));
persistent_store->AddChannelID(ChannelIDStore::ChannelID( persistent_store->AddChannelID(ChannelIDStore::ChannelID(
"both.com", base::Time(), "preexisting.com", base::Time(), preexisting_key->Copy()));
base::WrapUnique(crypto::ECPrivateKey::Create()))); persistent_store->AddChannelID(ChannelIDStore::ChannelID(
"both.com", base::Time(), crypto::ECPrivateKey::Create()));
DefaultChannelIDStore store(persistent_store.get()); DefaultChannelIDStore store(persistent_store.get());
ChannelIDStore::ChannelIDList source_channel_ids; ChannelIDStore::ChannelIDList source_channel_ids;
source_channel_ids.push_back(ChannelIDStore::ChannelID( source_channel_ids.push_back(ChannelIDStore::ChannelID(
"both.com", base::Time(), "both.com", base::Time(),
// Key differs from above to test that existing entries are overwritten. // Key differs from above to test that existing entries are overwritten.
base::WrapUnique(both_key->Copy()))); both_key->Copy()));
source_channel_ids.push_back(ChannelIDStore::ChannelID( source_channel_ids.push_back(ChannelIDStore::ChannelID(
"copied.com", base::Time(), base::WrapUnique(copied_key->Copy()))); "copied.com", base::Time(), copied_key->Copy()));
store.InitializeFrom(source_channel_ids); store.InitializeFrom(source_channel_ids);
EXPECT_EQ(0, store.GetChannelIDCount()); EXPECT_EQ(0, store.GetChannelIDCount());
// Wait for load & queued tasks. // Wait for load & queued tasks.

@@ -77,45 +77,46 @@ bool Nigori::InitByDerivation(const std::string& hostname,
std::unique_ptr<SymmetricKey> user_salt(SymmetricKey::DeriveKeyFromPassword( std::unique_ptr<SymmetricKey> user_salt(SymmetricKey::DeriveKeyFromPassword(
SymmetricKey::HMAC_SHA1, salt_password.str(), kSaltSalt, kSaltIterations, SymmetricKey::HMAC_SHA1, salt_password.str(), kSaltSalt, kSaltIterations,
kSaltKeySizeInBits)); kSaltKeySizeInBits));
DCHECK(user_salt.get()); DCHECK(user_salt);
std::string raw_user_salt; std::string raw_user_salt;
if (!user_salt->GetRawKey(&raw_user_salt)) if (!user_salt->GetRawKey(&raw_user_salt))
return false; return false;
// Kuser = PBKDF2(P, Suser, Nuser, 16) // Kuser = PBKDF2(P, Suser, Nuser, 16)
user_key_.reset(SymmetricKey::DeriveKeyFromPassword(SymmetricKey::AES, user_key_ = SymmetricKey::DeriveKeyFromPassword(
password, raw_user_salt, kUserIterations, kDerivedKeySizeInBits)); SymmetricKey::AES, password, raw_user_salt, kUserIterations,
DCHECK(user_key_.get()); kDerivedKeySizeInBits);
DCHECK(user_key_);
// Kenc = PBKDF2(P, Suser, Nenc, 16) // Kenc = PBKDF2(P, Suser, Nenc, 16)
encryption_key_.reset(SymmetricKey::DeriveKeyFromPassword(SymmetricKey::AES, encryption_key_ = SymmetricKey::DeriveKeyFromPassword(
password, raw_user_salt, kEncryptionIterations, kDerivedKeySizeInBits)); SymmetricKey::AES, password, raw_user_salt, kEncryptionIterations,
DCHECK(encryption_key_.get()); kDerivedKeySizeInBits);
DCHECK(encryption_key_);
// Kmac = PBKDF2(P, Suser, Nmac, 16) // Kmac = PBKDF2(P, Suser, Nmac, 16)
mac_key_.reset(SymmetricKey::DeriveKeyFromPassword( mac_key_ = SymmetricKey::DeriveKeyFromPassword(
SymmetricKey::HMAC_SHA1, password, raw_user_salt, kSigningIterations, SymmetricKey::HMAC_SHA1, password, raw_user_salt, kSigningIterations,
kDerivedKeySizeInBits)); kDerivedKeySizeInBits);
DCHECK(mac_key_.get()); DCHECK(mac_key_);
return user_key_.get() && encryption_key_.get() && mac_key_.get(); return user_key_ && encryption_key_ && mac_key_;
} }
bool Nigori::InitByImport(const std::string& user_key, bool Nigori::InitByImport(const std::string& user_key,
const std::string& encryption_key, const std::string& encryption_key,
const std::string& mac_key) { const std::string& mac_key) {
user_key_.reset(SymmetricKey::Import(SymmetricKey::AES, user_key)); user_key_ = SymmetricKey::Import(SymmetricKey::AES, user_key);
DCHECK(user_key_.get()); DCHECK(user_key_);
encryption_key_.reset(SymmetricKey::Import(SymmetricKey::AES, encryption_key_ = SymmetricKey::Import(SymmetricKey::AES, encryption_key);
encryption_key)); DCHECK(encryption_key_);
DCHECK(encryption_key_.get());
mac_key_.reset(SymmetricKey::Import(SymmetricKey::HMAC_SHA1, mac_key)); mac_key_ = SymmetricKey::Import(SymmetricKey::HMAC_SHA1, mac_key);
DCHECK(mac_key_.get()); DCHECK(mac_key_);
return user_key_.get() && encryption_key_.get() && mac_key_.get(); return user_key_ && encryption_key_ && mac_key_;
} }
// Permute[Kenc,Kmac](type || name) // Permute[Kenc,Kmac](type || name)