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
[email protected]
Review-Url: https://codereview.chromium.org/2095523002
Cr-Commit-Position: refs/heads/master@{#402368}
diff --git a/crypto/ec_private_key.cc b/crypto/ec_private_key.cc
index 176c9796..8f3c411 100644
--- a/crypto/ec_private_key.cc
+++ b/crypto/ec_private_key.cc
@@ -13,8 +13,6 @@
#include <stddef.h>
#include <stdint.h>
-#include <memory>
-
#include "base/logging.h"
#include "crypto/auto_cbb.h"
#include "crypto/openssl_util.h"
@@ -43,13 +41,13 @@
return false;
ScopedBIO bio(BIO_new(BIO_s_mem()));
- if (!bio.get())
+ if (!bio)
return false;
if (!export_fn(bio.get(), key))
return false;
- char* data = NULL;
+ char* data = nullptr;
long len = BIO_get_mem_data(bio.get(), &data);
if (!data || len < 0)
return false;
@@ -65,28 +63,21 @@
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
-ECPrivateKey* ECPrivateKey::Create() {
+std::unique_ptr<ECPrivateKey> ECPrivateKey::Create() {
OpenSSLErrStackTracer err_tracer(FROM_HERE);
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()))
- return NULL;
+ if (!ec_key || !EC_KEY_generate_key(ec_key.get()))
+ return nullptr;
std::unique_ptr<ECPrivateKey> result(new ECPrivateKey());
result->key_ = EVP_PKEY_new();
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_));
- return result.release();
+ return result;
}
// static
@@ -100,13 +91,13 @@
if (!pkey || CBS_len(&cbs) != 0 || EVP_PKEY_id(pkey.get()) != EVP_PKEY_EC)
return nullptr;
- std::unique_ptr<ECPrivateKey> result(new ECPrivateKey);
+ std::unique_ptr<ECPrivateKey> result(new ECPrivateKey());
result->key_ = pkey.release();
return result;
}
// static
-ECPrivateKey* ECPrivateKey::CreateFromEncryptedPrivateKeyInfo(
+std::unique_ptr<ECPrivateKey> ECPrivateKey::CreateFromEncryptedPrivateKeyInfo(
const std::string& password,
const std::vector<uint8_t>& encrypted_private_key_info,
const std::vector<uint8_t>& subject_public_key_info) {
@@ -114,16 +105,16 @@
// useful for the NSS implementation (which uses the public key's SHA1
// as a lookup key when storing the private one in its store).
if (encrypted_private_key_info.empty())
- return NULL;
+ return nullptr;
OpenSSLErrStackTracer err_tracer(FROM_HERE);
const uint8_t* data = &encrypted_private_key_info[0];
const uint8_t* ptr = data;
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())
- return NULL;
+ return nullptr;
ScopedPKCS8_PRIV_KEY_INFO p8_decrypted;
if (password.empty()) {
@@ -142,15 +133,22 @@
}
if (!p8_decrypted)
- return NULL;
+ return nullptr;
// 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());
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 {
@@ -174,7 +172,7 @@
OpenSSLErrStackTracer err_tracer(FROM_HERE);
// Convert into a PKCS#8 object.
ScopedPKCS8_PRIV_KEY_INFO pkcs8(EVP_PKEY2PKCS8(key_));
- if (!pkcs8.get())
+ if (!pkcs8)
return false;
// Encrypt the object.
@@ -190,7 +188,7 @@
0,
iterations,
pkcs8.get()));
- if (!encrypted.get())
+ if (!encrypted)
return false;
// Write it into |*output|
@@ -236,6 +234,6 @@
return true;
}
-ECPrivateKey::ECPrivateKey() : key_(NULL) {}
+ECPrivateKey::ECPrivateKey() : key_(nullptr) {}
} // namespace crypto
diff --git a/crypto/ec_private_key.h b/crypto/ec_private_key.h
index 3e543d3d..9cdb453 100644
--- a/crypto/ec_private_key.h
+++ b/crypto/ec_private_key.h
@@ -30,10 +30,10 @@
public:
~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.
// 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
// an ASN.1-encoded PrivateKeyInfo block from PKCS #8. This can return
@@ -44,17 +44,17 @@
// Creates a new instance by importing an existing key pair.
// The key pair is given as an ASN.1-encoded PKCS #8 EncryptedPrivateKeyInfo
// 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.
// See https://crbug.com/603319.
- static ECPrivateKey* CreateFromEncryptedPrivateKeyInfo(
+ static std::unique_ptr<ECPrivateKey> CreateFromEncryptedPrivateKeyInfo(
const std::string& password,
const std::vector<uint8_t>& encrypted_private_key_info,
const std::vector<uint8_t>& subject_public_key_info);
// Returns a copy of the object.
- ECPrivateKey* Copy() const;
+ std::unique_ptr<ECPrivateKey> Copy() const;
EVP_PKEY* key() { return key_; }
diff --git a/crypto/ec_private_key_unittest.cc b/crypto/ec_private_key_unittest.cc
index 450ed15..386844c 100644
--- a/crypto/ec_private_key_unittest.cc
+++ b/crypto/ec_private_key_unittest.cc
@@ -45,7 +45,7 @@
static const char kPassword2[] = "test";
std::unique_ptr<crypto::ECPrivateKey> keypair(crypto::ECPrivateKey::Create());
- ASSERT_TRUE(keypair.get());
+ ASSERT_TRUE(keypair);
// Re-import as a PrivateKeyInfo.
std::vector<uint8_t> privkey;
@@ -61,16 +61,16 @@
EXPECT_TRUE(
keypair->ExportEncryptedPrivateKey(kPassword1, 1, &encrypted_privkey));
EXPECT_TRUE(keypair->ExportPublicKey(&pubkey));
- keypair_copy.reset(crypto::ECPrivateKey::CreateFromEncryptedPrivateKeyInfo(
- kPassword1, encrypted_privkey, pubkey));
+ keypair_copy = crypto::ECPrivateKey::CreateFromEncryptedPrivateKeyInfo(
+ kPassword1, encrypted_privkey, pubkey);
ASSERT_TRUE(keypair_copy);
ExpectKeysEqual(keypair.get(), keypair_copy.get());
// Re-import as an EncryptedPrivateKeyInfo with kPassword2.
EXPECT_TRUE(
keypair->ExportEncryptedPrivateKey(kPassword2, 1, &encrypted_privkey));
- keypair_copy.reset(crypto::ECPrivateKey::CreateFromEncryptedPrivateKeyInfo(
- kPassword2, encrypted_privkey, pubkey));
+ keypair_copy = crypto::ECPrivateKey::CreateFromEncryptedPrivateKeyInfo(
+ kPassword2, encrypted_privkey, pubkey);
ASSERT_TRUE(keypair_copy);
ExpectKeysEqual(keypair.get(), keypair_copy.get());
}
@@ -79,8 +79,8 @@
std::unique_ptr<crypto::ECPrivateKey> keypair1(
crypto::ECPrivateKey::Create());
std::unique_ptr<crypto::ECPrivateKey> keypair2(keypair1->Copy());
- ASSERT_TRUE(keypair1.get());
- ASSERT_TRUE(keypair2.get());
+ ASSERT_TRUE(keypair1);
+ ASSERT_TRUE(keypair2);
ExpectKeysEqual(keypair1.get(), keypair2.get());
}
@@ -206,7 +206,7 @@
std::unique_ptr<crypto::ECPrivateKey> keypair1(
crypto::ECPrivateKey::Create());
- ASSERT_TRUE(keypair1.get());
+ ASSERT_TRUE(keypair1);
std::vector<uint8_t> privkey1;
std::vector<uint8_t> pubkey1;
@@ -217,7 +217,7 @@
std::unique_ptr<crypto::ECPrivateKey> keypair2(
crypto::ECPrivateKey::CreateFromEncryptedPrivateKeyInfo(
password2, privkey1, pubkey1));
- ASSERT_FALSE(keypair2.get());
+ ASSERT_FALSE(keypair2);
}
TEST(ECPrivateKeyUnitTest, LoadNSSKeyTest) {
@@ -256,7 +256,7 @@
std::vector<uint8_t>(std::begin(kNSSPublicKey),
std::end(kNSSPublicKey))));
- EXPECT_TRUE(keypair_nss.get());
+ EXPECT_TRUE(keypair_nss);
}
TEST(ECPrivateKeyUnitTest, LoadOpenSSLKeyTest) {
@@ -303,7 +303,7 @@
std::vector<uint8_t>(std::begin(kOpenSSLPublicKey),
std::end(kOpenSSLPublicKey))));
- EXPECT_TRUE(keypair_openssl.get());
+ EXPECT_TRUE(keypair_openssl);
std::vector<uint8_t> public_key;
EXPECT_TRUE(keypair_openssl->ExportPublicKey(&public_key));
@@ -398,5 +398,5 @@
std::vector<uint8_t>(std::begin(kOpenSSLPublicKey),
std::end(kOpenSSLPublicKey))));
- EXPECT_TRUE(keypair_openssl.get());
+ EXPECT_TRUE(keypair_openssl);
}
diff --git a/crypto/ec_signature_creator.cc b/crypto/ec_signature_creator.cc
index a6887bc..34e5181d 100644
--- a/crypto/ec_signature_creator.cc
+++ b/crypto/ec_signature_creator.cc
@@ -5,21 +5,23 @@
#include "crypto/ec_signature_creator.h"
#include "base/logging.h"
+#include "base/memory/ptr_util.h"
#include "crypto/ec_signature_creator_impl.h"
namespace crypto {
namespace {
-ECSignatureCreatorFactory* g_factory_ = NULL;
+ECSignatureCreatorFactory* g_factory_ = nullptr;
} // namespace
// static
-ECSignatureCreator* ECSignatureCreator::Create(ECPrivateKey* key) {
+std::unique_ptr<ECSignatureCreator> ECSignatureCreator::Create(
+ ECPrivateKey* key) {
if (g_factory_)
return g_factory_->Create(key);
- return new ECSignatureCreatorImpl(key);
+ return base::MakeUnique<ECSignatureCreatorImpl>(key);
}
// static
diff --git a/crypto/ec_signature_creator.h b/crypto/ec_signature_creator.h
index 47128fed..72e09df 100644
--- a/crypto/ec_signature_creator.h
+++ b/crypto/ec_signature_creator.h
@@ -7,6 +7,7 @@
#include <stdint.h>
+#include <memory>
#include <string>
#include <vector>
@@ -21,7 +22,7 @@
public:
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).
@@ -35,7 +36,7 @@
// instance outlives the created ECSignatureCreator.
// TODO(rch): This is currently hard coded to use SHA256. Ideally, we should
// 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
// ECSignatureCreator objects. Because the ECDSA algorithm involves
diff --git a/crypto/ec_signature_creator_impl.cc b/crypto/ec_signature_creator_impl.cc
index e80a7fb..c22efda 100644
--- a/crypto/ec_signature_creator_impl.cc
+++ b/crypto/ec_signature_creator_impl.cc
@@ -33,9 +33,10 @@
ScopedEVP_MD_CTX ctx(EVP_MD_CTX_create());
size_t sig_len = 0;
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_DigestSignFinal(ctx.get(), NULL, &sig_len)) {
+ !EVP_DigestSignFinal(ctx.get(), nullptr, &sig_len)) {
return false;
}
@@ -43,9 +44,9 @@
if (!EVP_DigestSignFinal(ctx.get(), &signature->front(), &sig_len))
return false;
- // NOTE: A call to EVP_DigestSignFinal() with a NULL second parameter returns
- // a maximum allocation size, while the call without a NULL returns the real
- // one, which may be smaller.
+ // NOTE: A call to EVP_DigestSignFinal() with a nullptr second parameter
+ // returns a maximum allocation size, while the call without a nullptr
+ // returns the real one, which may be smaller.
signature->resize(sig_len);
return true;
}
diff --git a/crypto/encryptor.cc b/crypto/encryptor.cc
index a9f9a9d5d..06bf00cc 100644
--- a/crypto/encryptor.cc
+++ b/crypto/encryptor.cc
@@ -23,7 +23,8 @@
switch (key->key().length()) {
case 16: return EVP_aes_128_cbc();
case 32: return EVP_aes_256_cbc();
- default: return NULL;
+ default:
+ return nullptr;
}
}
@@ -84,10 +85,7 @@
/////////////////////////////////////////////////////////////////////////////
// Encryptor Implementation.
-Encryptor::Encryptor()
- : key_(NULL),
- mode_(CBC) {
-}
+Encryptor::Encryptor() : key_(nullptr), mode_(CBC) {}
Encryptor::~Encryptor() {
}
@@ -102,7 +100,7 @@
if (mode == CBC && iv.size() != AES_BLOCK_SIZE)
return false;
- if (GetCipherForKey(key) == NULL)
+ if (GetCipherForKey(key) == nullptr)
return false;
key_ = key;
@@ -191,9 +189,10 @@
DCHECK_EQ(EVP_CIPHER_key_length(cipher), key.length());
ScopedCipherCTX ctx;
- if (!EVP_CipherInit_ex(
- ctx.get(), cipher, NULL, reinterpret_cast<const uint8_t*>(key.data()),
- reinterpret_cast<const uint8_t*>(iv_.data()), do_encrypt))
+ if (!EVP_CipherInit_ex(ctx.get(), cipher, nullptr,
+ reinterpret_cast<const uint8_t*>(key.data()),
+ reinterpret_cast<const uint8_t*>(iv_.data()),
+ do_encrypt))
return false;
// When encrypting, add another block size of space to allow for any padding.
diff --git a/crypto/hmac.cc b/crypto/hmac.cc
index c3c43da..fa91628 100644
--- a/crypto/hmac.cc
+++ b/crypto/hmac.cc
@@ -63,10 +63,10 @@
DCHECK(initialized_);
ScopedOpenSSLSafeSizeBuffer<EVP_MAX_MD_SIZE> result(digest, digest_length);
- return !!::HMAC(hash_alg_ == SHA1 ? EVP_sha1() : EVP_sha256(),
- key_.data(), key_.size(),
+ return !!::HMAC(hash_alg_ == SHA1 ? EVP_sha1() : EVP_sha256(), key_.data(),
+ key_.size(),
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,
diff --git a/crypto/hmac_unittest.cc b/crypto/hmac_unittest.cc
index f8dbd5a6..9c42dad 100644
--- a/crypto/hmac_unittest.cc
+++ b/crypto/hmac_unittest.cc
@@ -287,7 +287,7 @@
base::StringPiece data("");
crypto::HMAC hmac(crypto::HMAC::SHA1);
- ASSERT_TRUE(hmac.Init(NULL, 0));
+ ASSERT_TRUE(hmac.Init(nullptr, 0));
unsigned char digest[kSHA1DigestSize];
EXPECT_TRUE(hmac.Sign(data, digest, kSHA1DigestSize));
diff --git a/crypto/mock_apple_keychain.h b/crypto/mock_apple_keychain.h
index f36e982d..db4fcd8 100644
--- a/crypto/mock_apple_keychain.h
+++ b/crypto/mock_apple_keychain.h
@@ -209,7 +209,7 @@
bool locked_;
typedef struct KeychainPasswordData {
- KeychainPasswordData() : data(NULL), length(0) {}
+ KeychainPasswordData() : data(nullptr), length(0) {}
void* data;
UInt32 length;
} KeychainPasswordData;
diff --git a/crypto/nss_util.cc b/crypto/nss_util.cc
index afca2ec..66114cd 100644
--- a/crypto/nss_util.cc
+++ b/crypto/nss_util.cc
@@ -126,13 +126,13 @@
retry != PR_FALSE,
&cancelled);
if (cancelled)
- return NULL;
+ return nullptr;
char* result = PORT_Strdup(password.c_str());
password.replace(0, password.size(), password.size(), 0);
return result;
}
- DLOG(ERROR) << "PK11 password requested with NULL arg";
- return NULL;
+ DLOG(ERROR) << "PK11 password requested with nullptr arg";
+ return nullptr;
}
// NSS creates a local cache of the sqlite database if it detects that the
@@ -218,8 +218,8 @@
}
ScopedPK11Slot GetPublicSlot() {
- return ScopedPK11Slot(
- public_slot_ ? PK11_ReferenceSlot(public_slot_.get()) : NULL);
+ return ScopedPK11Slot(public_slot_ ? PK11_ReferenceSlot(public_slot_.get())
+ : nullptr);
}
ScopedPK11Slot GetPrivateSlot(
@@ -353,7 +353,7 @@
// If everything is already initialized, then return true.
// 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_) {
base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE,
base::Bind(callback, true));
@@ -608,7 +608,7 @@
void SetSystemKeySlotForTesting(ScopedPK11Slot slot) {
// 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_);
test_system_slot_ = std::move(slot);
if (test_system_slot_) {
@@ -644,7 +644,7 @@
// TODO(mattm): chromeos::TPMTokenloader always calls
// InitializeTPMTokenAndSystemSlot with slot 0. If the system slot is
// 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;
if (!callback.is_null()) {
@@ -669,8 +669,8 @@
NSSInitSingleton()
: tpm_token_enabled_for_nss_(false),
initializing_tpm_token_(false),
- chaps_module_(NULL),
- root_(NULL) {
+ chaps_module_(nullptr),
+ root_(nullptr) {
// It's safe to construct on any thread, since LazyInstance will prevent any
// other threads from accessing until the constructor is done.
thread_checker_.DetachFromThread();
@@ -717,7 +717,7 @@
}
if (status != SECSuccess) {
VLOG(1) << "Initializing NSS without a persistent database.";
- status = NSS_NoDB_Init(NULL);
+ status = NSS_NoDB_Init(nullptr);
if (status != SECSuccess) {
CrashOnNSSInitFailure();
return;
@@ -734,7 +734,7 @@
// PK11_InitPin may write to the keyDB, but no other thread can use NSS
// yet, so we don't need to lock.
if (PK11_NeedUserInit(slot))
- PK11_InitPin(slot, NULL, NULL);
+ PK11_InitPin(slot, nullptr, nullptr);
PK11_FreeSlot(slot);
}
@@ -758,12 +758,12 @@
if (root_) {
SECMOD_UnloadUserModule(root_);
SECMOD_DestroyModule(root_);
- root_ = NULL;
+ root_ = nullptr;
}
if (chaps_module_) {
SECMOD_UnloadUserModule(chaps_module_);
SECMOD_DestroyModule(chaps_module_);
- chaps_module_ = NULL;
+ chaps_module_ = nullptr;
}
SECStatus status = NSS_Shutdown();
@@ -776,14 +776,14 @@
// Load nss's built-in root certs.
SECMODModule* InitDefaultRootCerts() {
- SECMODModule* root = LoadModule("Root Certs", "libnssckbi.so", NULL);
+ SECMODModule* root = LoadModule("Root Certs", "libnssckbi.so", nullptr);
if (root)
return root;
// Aw, snap. Can't find/load root cert shared library.
// This will make it hard to talk to anybody via https.
// 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.
@@ -799,17 +799,17 @@
// https://bugzilla.mozilla.org/show_bug.cgi?id=642546 was filed
// on NSS codebase to address this.
SECMODModule* module = SECMOD_LoadUserModule(
- const_cast<char*>(modparams.c_str()), NULL, PR_FALSE);
+ const_cast<char*>(modparams.c_str()), nullptr, PR_FALSE);
if (!module) {
LOG(ERROR) << "Error loading " << name << " module into NSS: "
<< GetNSSErrorMessage();
- return NULL;
+ return nullptr;
}
if (!module->loaded) {
LOG(ERROR) << "After loading " << name << ", loaded==false: "
<< GetNSSErrorMessage();
SECMOD_DestroyModule(module);
- return NULL;
+ return nullptr;
}
return module;
}
@@ -846,7 +846,7 @@
PK11SlotInfo* db_slot = SECMOD_OpenUserDB(modspec.c_str());
if (db_slot) {
if (PK11_NeedUserInit(db_slot))
- PK11_InitPin(db_slot, NULL, NULL);
+ PK11_InitPin(db_slot, nullptr, nullptr);
} else {
LOG(ERROR) << "Error opening persistent database (" << modspec
<< "): " << GetNSSErrorMessage();
@@ -881,7 +881,7 @@
}
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_)
lock_->Acquire();
}
diff --git a/crypto/nss_util_internal.h b/crypto/nss_util_internal.h
index 0982a6e8..697e376 100644
--- a/crypto/nss_util_internal.h
+++ b/crypto/nss_util_internal.h
@@ -24,7 +24,7 @@
// Opens an NSS software database in folder |path|, with the (potentially)
// 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,
const std::string& description);
@@ -57,8 +57,8 @@
// through |GetSystemNSSKeySlot| and |IsTPMTokenReady| will return true.
// |InitializeTPMTokenAndSystemSlot|, which triggers the TPM initialization,
// 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|
-// is NULL, the test system slot is unset.
+// This must must not be called consecutively with a |slot| != nullptr. If
+// |slot| is nullptr, the test system slot is unset.
CRYPTO_EXPORT void SetSystemKeySlotForTesting(ScopedPK11Slot slot);
// Prepare per-user NSS slot mapping. It is safe to call this function multiple
diff --git a/crypto/secure_hash.cc b/crypto/secure_hash.cc
index 2a5a1f0..76d42d3 100644
--- a/crypto/secure_hash.cc
+++ b/crypto/secure_hash.cc
@@ -9,6 +9,7 @@
#include <stddef.h>
#include "base/logging.h"
+#include "base/memory/ptr_util.h"
#include "base/pickle.h"
#include "crypto/openssl_util.h"
@@ -40,8 +41,8 @@
SHA256_Final(result.safe_buffer(), &ctx_);
}
- SecureHash* Clone() const override {
- return new SecureHashSHA256(*this);
+ std::unique_ptr<SecureHash> Clone() const override {
+ return base::MakeUnique<SecureHashSHA256>(*this);
}
size_t GetHashLength() const override { return SHA256_DIGEST_LENGTH; }
@@ -52,13 +53,13 @@
} // namespace
-SecureHash* SecureHash::Create(Algorithm algorithm) {
+std::unique_ptr<SecureHash> SecureHash::Create(Algorithm algorithm) {
switch (algorithm) {
case SHA256:
- return new SecureHashSHA256();
+ return base::MakeUnique<SecureHashSHA256>();
default:
NOTIMPLEMENTED();
- return NULL;
+ return nullptr;
}
}
diff --git a/crypto/secure_hash.h b/crypto/secure_hash.h
index a5590e5..30b9fdc 100644
--- a/crypto/secure_hash.h
+++ b/crypto/secure_hash.h
@@ -7,6 +7,8 @@
#include <stddef.h>
+#include <memory>
+
#include "base/macros.h"
#include "crypto/crypto_export.h"
@@ -21,7 +23,7 @@
};
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 Finish(void* output, size_t len) = 0;
@@ -30,7 +32,7 @@
// Create a clone of this SecureHash. The returned clone and this both
// represent the same hash state. But from this point on, calling
// 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:
SecureHash() {}
diff --git a/crypto/signature_creator.cc b/crypto/signature_creator.cc
index 6543e63..bb4019e 100644
--- a/crypto/signature_creator.cc
+++ b/crypto/signature_creator.cc
@@ -9,8 +9,6 @@
#include <stddef.h>
#include <stdint.h>
-#include <memory>
-
#include "base/logging.h"
#include "crypto/openssl_util.h"
#include "crypto/rsa_private_key.h"
@@ -27,7 +25,7 @@
case SignatureCreator::SHA256:
return EVP_sha256();
}
- return NULL;
+ return nullptr;
}
int ToOpenSSLDigestType(SignatureCreator::HashAlgorithm hash_alg) {
@@ -42,21 +40,26 @@
} // namespace
+SignatureCreator::~SignatureCreator() {
+ EVP_MD_CTX_destroy(sign_context_);
+}
+
// static
-SignatureCreator* SignatureCreator::Create(RSAPrivateKey* key,
- HashAlgorithm hash_alg) {
+std::unique_ptr<SignatureCreator> SignatureCreator::Create(
+ RSAPrivateKey* key,
+ HashAlgorithm hash_alg) {
OpenSSLErrStackTracer err_tracer(FROM_HERE);
std::unique_ptr<SignatureCreator> result(new SignatureCreator);
const EVP_MD* const digest = ToOpenSSLDigest(hash_alg);
DCHECK(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())) {
- return NULL;
+ return nullptr;
}
- return result.release();
+ return result;
}
// static
@@ -80,14 +83,6 @@
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) {
OpenSSLErrStackTracer err_tracer(FROM_HERE);
return !!EVP_DigestSignUpdate(sign_context_, data_part, data_part_len);
@@ -98,7 +93,7 @@
// Determine the maximum length of the signature.
size_t len = 0;
- if (!EVP_DigestSignFinal(sign_context_, NULL, &len)) {
+ if (!EVP_DigestSignFinal(sign_context_, nullptr, &len)) {
signature->clear();
return false;
}
@@ -113,4 +108,6 @@
return true;
}
+SignatureCreator::SignatureCreator() : sign_context_(EVP_MD_CTX_create()) {}
+
} // namespace crypto
diff --git a/crypto/signature_creator.h b/crypto/signature_creator.h
index 98329b8..674bd4cc 100644
--- a/crypto/signature_creator.h
+++ b/crypto/signature_creator.h
@@ -7,6 +7,7 @@
#include <stdint.h>
+#include <memory>
#include <vector>
#include "base/macros.h"
@@ -35,8 +36,8 @@
// Create an instance. The caller must ensure that the provided PrivateKey
// instance outlives the created SignatureCreator. Uses the HashAlgorithm
// 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
// specified in PKCS #1 v1.5.
diff --git a/crypto/signature_verifier.cc b/crypto/signature_verifier.cc
index f4a3d4f0..236b64c 100644
--- a/crypto/signature_verifier.cc
+++ b/crypto/signature_verifier.cc
@@ -27,7 +27,7 @@
case SignatureVerifier::SHA256:
return EVP_sha256();
}
- return NULL;
+ return nullptr;
}
} // namespace
@@ -36,9 +36,7 @@
ScopedEVP_MD_CTX ctx;
};
-SignatureVerifier::SignatureVerifier()
- : verify_context_(NULL) {
-}
+SignatureVerifier::SignatureVerifier() : verify_context_(nullptr) {}
SignatureVerifier::~SignatureVerifier() {
Reset();
@@ -153,7 +151,7 @@
void SignatureVerifier::Reset() {
delete verify_context_;
- verify_context_ = NULL;
+ verify_context_ = nullptr;
signature_.clear();
}
diff --git a/crypto/symmetric_key.cc b/crypto/symmetric_key.cc
index 4da8bd8..e3ecf62 100644
--- a/crypto/symmetric_key.cc
+++ b/crypto/symmetric_key.cc
@@ -10,7 +10,7 @@
#include <stdint.h>
#include <algorithm>
-#include <memory>
+#include <utility>
#include "base/logging.h"
#include "base/strings/string_util.h"
@@ -23,21 +23,22 @@
}
// static
-SymmetricKey* SymmetricKey::GenerateRandomKey(Algorithm algorithm,
- size_t key_size_in_bits) {
+std::unique_ptr<SymmetricKey> SymmetricKey::GenerateRandomKey(
+ Algorithm algorithm,
+ size_t key_size_in_bits) {
DCHECK_EQ(AES, algorithm);
// Whitelist supported key sizes to avoid accidentaly relying on
// algorithms available in NSS but not BoringSSL and vice
// versa. Note that BoringSSL does not support AES-192.
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;
DCHECK_EQ(key_size_in_bits, key_size_in_bytes * 8);
if (key_size_in_bytes == 0)
- return NULL;
+ return nullptr;
OpenSSLErrStackTracer err_tracer(FROM_HERE);
std::unique_ptr<SymmetricKey> key(new SymmetricKey);
@@ -45,15 +46,16 @@
base::WriteInto(&key->key_, key_size_in_bytes + 1));
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
-SymmetricKey* SymmetricKey::DeriveKeyFromPassword(Algorithm algorithm,
- const std::string& password,
- const std::string& salt,
- size_t iterations,
- size_t key_size_in_bits) {
+std::unique_ptr<SymmetricKey> SymmetricKey::DeriveKeyFromPassword(
+ Algorithm algorithm,
+ const std::string& password,
+ const std::string& salt,
+ size_t iterations,
+ size_t key_size_in_bits) {
DCHECK(algorithm == AES || algorithm == HMAC_SHA1);
if (algorithm == AES) {
@@ -61,14 +63,14 @@
// algorithms available in NSS but not BoringSSL and vice
// versa. Note that BoringSSL does not support AES-192.
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;
DCHECK_EQ(key_size_in_bits, key_size_in_bytes * 8);
if (key_size_in_bytes == 0)
- return NULL;
+ return nullptr;
OpenSSLErrStackTracer err_tracer(FROM_HERE);
std::unique_ptr<SymmetricKey> key(new SymmetricKey);
@@ -79,23 +81,23 @@
reinterpret_cast<const uint8_t*>(salt.data()), salt.length(),
static_cast<unsigned>(iterations),
key_size_in_bytes, key_data);
- return rv == 1 ? key.release() : NULL;
+ return rv == 1 ? std::move(key) : nullptr;
}
// static
-SymmetricKey* SymmetricKey::Import(Algorithm algorithm,
- const std::string& raw_key) {
+std::unique_ptr<SymmetricKey> SymmetricKey::Import(Algorithm algorithm,
+ const std::string& raw_key) {
if (algorithm == AES) {
// Whitelist supported key sizes to avoid accidentaly relying on
// algorithms available in NSS but not BoringSSL and vice
// versa. Note that BoringSSL does not support AES-192.
if (raw_key.size() != 128/8 && raw_key.size() != 256/8)
- return NULL;
+ return nullptr;
}
std::unique_ptr<SymmetricKey> key(new SymmetricKey);
key->key_ = raw_key;
- return key.release();
+ return key;
}
bool SymmetricKey::GetRawKey(std::string* raw_key) {
@@ -103,4 +105,6 @@
return true;
}
+SymmetricKey::SymmetricKey() = default;
+
} // namespace crypto
diff --git a/crypto/symmetric_key.h b/crypto/symmetric_key.h
index 2b2e2ce..7494634b 100644
--- a/crypto/symmetric_key.h
+++ b/crypto/symmetric_key.h
@@ -7,6 +7,7 @@
#include <stddef.h>
+#include <memory>
#include <string>
#include "base/macros.h"
@@ -31,25 +32,28 @@
// 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.
// The caller is responsible for deleting the returned SymmetricKey.
- static SymmetricKey* GenerateRandomKey(Algorithm algorithm,
- size_t key_size_in_bits);
+ static std::unique_ptr<SymmetricKey> GenerateRandomKey(
+ Algorithm algorithm,
+ size_t key_size_in_bits);
// Derives a key from the supplied password and salt using PBKDF2, suitable
// 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
// multiple of 8. The caller is responsible for deleting the returned
// SymmetricKey.
- static SymmetricKey* DeriveKeyFromPassword(Algorithm algorithm,
- const std::string& password,
- const std::string& salt,
- size_t iterations,
- size_t key_size_in_bits);
+ static std::unique_ptr<SymmetricKey> DeriveKeyFromPassword(
+ Algorithm algorithm,
+ const std::string& password,
+ const std::string& salt,
+ size_t iterations,
+ size_t key_size_in_bits);
// Imports an array of key bytes in |raw_key|. This key may have been
// generated by GenerateRandomKey or DeriveKeyFromPassword and exported with
// GetRawKey, or via another compatible method. The key must be of suitable
// 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_; }
@@ -59,7 +63,8 @@
bool GetRawKey(std::string* raw_key);
private:
- SymmetricKey() {}
+ SymmetricKey();
+
std::string key_;
DISALLOW_COPY_AND_ASSIGN(SymmetricKey);
diff --git a/crypto/symmetric_key_unittest.cc b/crypto/symmetric_key_unittest.cc
index 468759b04..d954761 100644
--- a/crypto/symmetric_key_unittest.cc
+++ b/crypto/symmetric_key_unittest.cc
@@ -14,7 +14,7 @@
TEST(SymmetricKeyTest, GenerateRandomKey) {
std::unique_ptr<crypto::SymmetricKey> key(
crypto::SymmetricKey::GenerateRandomKey(crypto::SymmetricKey::AES, 256));
- ASSERT_TRUE(NULL != key.get());
+ ASSERT_TRUE(key);
std::string raw_key;
EXPECT_TRUE(key->GetRawKey(&raw_key));
EXPECT_EQ(32U, raw_key.size());
@@ -23,7 +23,7 @@
// (Note: this has a one-in-10^77 chance of failure!)
std::unique_ptr<crypto::SymmetricKey> key2(
crypto::SymmetricKey::GenerateRandomKey(crypto::SymmetricKey::AES, 256));
- ASSERT_TRUE(NULL != key2.get());
+ ASSERT_TRUE(key2);
std::string raw_key2;
EXPECT_TRUE(key2->GetRawKey(&raw_key2));
EXPECT_EQ(32U, raw_key2.size());
@@ -33,13 +33,13 @@
TEST(SymmetricKeyTest, ImportGeneratedKey) {
std::unique_ptr<crypto::SymmetricKey> key1(
crypto::SymmetricKey::GenerateRandomKey(crypto::SymmetricKey::AES, 256));
- ASSERT_TRUE(NULL != key1.get());
+ ASSERT_TRUE(key1);
std::string raw_key1;
EXPECT_TRUE(key1->GetRawKey(&raw_key1));
std::unique_ptr<crypto::SymmetricKey> key2(
crypto::SymmetricKey::Import(crypto::SymmetricKey::AES, raw_key1));
- ASSERT_TRUE(NULL != key2.get());
+ ASSERT_TRUE(key2);
std::string raw_key2;
EXPECT_TRUE(key2->GetRawKey(&raw_key2));
@@ -51,13 +51,13 @@
std::unique_ptr<crypto::SymmetricKey> key1(
crypto::SymmetricKey::DeriveKeyFromPassword(
crypto::SymmetricKey::HMAC_SHA1, "password", "somesalt", 1024, 160));
- ASSERT_TRUE(NULL != key1.get());
+ ASSERT_TRUE(key1);
std::string raw_key1;
EXPECT_TRUE(key1->GetRawKey(&raw_key1));
std::unique_ptr<crypto::SymmetricKey> key2(
crypto::SymmetricKey::Import(crypto::SymmetricKey::HMAC_SHA1, raw_key1));
- ASSERT_TRUE(NULL != key2.get());
+ ASSERT_TRUE(key2);
std::string raw_key2;
EXPECT_TRUE(key2->GetRawKey(&raw_key2));
@@ -84,7 +84,7 @@
crypto::SymmetricKey::DeriveKeyFromPassword(
test_data.algorithm, test_data.password, test_data.salt,
test_data.rounds, test_data.key_size_in_bits));
- ASSERT_TRUE(NULL != key.get());
+ ASSERT_TRUE(key);
std::string raw_key;
key->GetRawKey(&raw_key);
diff --git a/crypto/wincrypt_shim.h b/crypto/wincrypt_shim.h
index 799ac49f..48d4b5c 100644
--- a/crypto/wincrypt_shim.h
+++ b/crypto/wincrypt_shim.h
@@ -22,4 +22,4 @@
#define WINCRYPT_X509_EXTENSIONS ((LPCSTR) 5)
#define WINCRYPT_X509_NAME ((LPCSTR) 7)
-#endif // NET_CRYPTO_WINCRYPT_SHIM_H_
\ No newline at end of file
+#endif // NET_CRYPTO_WINCRYPT_SHIM_H_