Merge "Reducing amount of files created in dropbox for keystore"
diff --git a/keystore/Android.bp b/keystore/Android.bp
index 366f591..a12183f 100644
--- a/keystore/Android.bp
+++ b/keystore/Android.bp
@@ -13,7 +13,6 @@
     },
 
     clang: true,
-    cpp_std: "c++17",
 }
 
 cc_binary {
@@ -26,7 +25,6 @@
         "auth_token_table.cpp",
         "blob.cpp",
         "confirmation_manager.cpp",
-        "entropy.cpp",
         "grant_store.cpp",
         "key_config.proto",
         "key_proto_handler.cpp",
diff --git a/keystore/KeyStore.cpp b/keystore/KeyStore.cpp
index ac3ab5f..6e8a4b2 100644
--- a/keystore/KeyStore.cpp
+++ b/keystore/KeyStore.cpp
@@ -49,10 +49,9 @@
 
 using android::String8;
 
-KeyStore::KeyStore(Entropy* entropy, const KeymasterDevices& kmDevices,
+KeyStore::KeyStore(const KeymasterDevices& kmDevices,
                    SecurityLevel minimalAllowedSecurityLevelForNewKeys)
-    : mEntropy(entropy),
-      mAllowNewFallback(minimalAllowedSecurityLevelForNewKeys == SecurityLevel::SOFTWARE),
+    : mAllowNewFallback(minimalAllowedSecurityLevelForNewKeys == SecurityLevel::SOFTWARE),
       mConfirmationManager(new ConfirmationManager(this)) {
     memset(&mMetaData, '\0', sizeof(mMetaData));
 
@@ -81,7 +80,7 @@
 
 ResponseCode KeyStore::initializeUser(const android::String8& pw, uid_t userId) {
     auto userState = mUserStateDB.getUserState(userId);
-    return userState->initialize(pw, mEntropy);
+    return userState->initialize(pw);
 }
 
 ResponseCode KeyStore::copyMasterKey(uid_t srcUser, uid_t dstUser) {
@@ -92,12 +91,12 @@
 
 ResponseCode KeyStore::writeMasterKey(const android::String8& pw, uid_t userId) {
     auto userState = mUserStateDB.getUserState(userId);
-    return userState->writeMasterKey(pw, mEntropy);
+    return userState->writeMasterKey(pw);
 }
 
 ResponseCode KeyStore::readMasterKey(const android::String8& pw, uid_t userId) {
     auto userState = mUserStateDB.getUserState(userId);
-    return userState->readMasterKey(pw, mEntropy);
+    return userState->readMasterKey(pw);
 }
 
 LockedKeyBlobEntry KeyStore::getLockedBlobEntryIfNotExists(const std::string& alias, uid_t uid) {
@@ -285,7 +284,7 @@
                            Blob characteristicsBlob) {
     auto userState = mUserStateDB.getUserStateByUid(blobfile->uid());
     return blobfile.writeBlobs(std::move(keyBlob), std::move(characteristicsBlob),
-                               userState->getEncryptionKey(), userState->getState(), mEntropy);
+                               userState->getEncryptionKey(), userState->getState());
 }
 
 ResponseCode KeyStore::del(const LockedKeyBlobEntry& blobfile) {
diff --git a/keystore/KeyStore.h b/keystore/KeyStore.h
index d2049a4..69a02ae 100644
--- a/keystore/KeyStore.h
+++ b/keystore/KeyStore.h
@@ -62,7 +62,7 @@
 }  // namespace keystore
 
 namespace std {
-template <typename T, size_t count> class tuple_size<keystore::Devices<T, count>> {
+template <typename T, size_t count> struct tuple_size<keystore::Devices<T, count>> {
   public:
     static constexpr size_t value = std::tuple_size<std::array<T, count>>::value;
 };
@@ -75,7 +75,7 @@
 
 class KeyStore : public ::android::IBinder::DeathRecipient {
   public:
-    KeyStore(Entropy* entropy, const KeymasterDevices& kmDevices,
+    KeyStore(const KeymasterDevices& kmDevices,
              SecurityLevel minimalAllowedSecurityLevelForNewKeys);
     ~KeyStore();
 
@@ -148,7 +148,6 @@
     static const char* kMetaDataFile;
     static const android::String16 kRsaKeyType;
     static const android::String16 kEcKeyType;
-    Entropy* mEntropy;
 
     KeymasterWorkers mKmDevices;
 
diff --git a/keystore/binder/android/security/keystore/IKeystoreService.aidl b/keystore/binder/android/security/keystore/IKeystoreService.aidl
index ea1e0f4..348964f 100644
--- a/keystore/binder/android/security/keystore/IKeystoreService.aidl
+++ b/keystore/binder/android/security/keystore/IKeystoreService.aidl
@@ -75,5 +75,5 @@
     int cancelConfirmationPrompt(IBinder listener);
     boolean isConfirmationPromptSupported();
     int onKeyguardVisibilityChanged(in boolean isShowing, in int userId);
-    int listUidsOfAuthBoundKeys(out int[] uids);
+    int listUidsOfAuthBoundKeys(out @utf8InCpp List<String> uids);
 }
diff --git a/keystore/blob.cpp b/keystore/blob.cpp
index f887e80..f9485a4 100644
--- a/keystore/blob.cpp
+++ b/keystore/blob.cpp
@@ -24,11 +24,11 @@
 #include <log/log.h>
 
 #include "blob.h"
-#include "entropy.h"
 
 #include "keystore_utils.h"
 
 #include <openssl/evp.h>
+#include <openssl/rand.h>
 
 #include <istream>
 #include <ostream>
@@ -69,16 +69,31 @@
     size_t mSize;
 };
 
-/*
- * Encrypt 'len' data at 'in' with AES-GCM, using 128-bit key at 'key', 96-bit IV at 'iv' and write
- * output to 'out' (which may be the same location as 'in') and 128-bit tag to 'tag'.
+/**
+ * Returns a EVP_CIPHER appropriate for the given key, based on the key's size.
  */
-ResponseCode AES_gcm_encrypt(const uint8_t* in, uint8_t* out, size_t len, const uint8_t* key,
-                             const uint8_t* iv, uint8_t* tag) {
-    const EVP_CIPHER* cipher = EVP_aes_128_gcm();
+const EVP_CIPHER* getAesCipherForKey(const std::vector<uint8_t>& key) {
+    const EVP_CIPHER* cipher = EVP_aes_256_gcm();
+    if (key.size() == kAes128KeySizeBytes) {
+        cipher = EVP_aes_128_gcm();
+    }
+    return cipher;
+}
+
+/*
+ * Encrypt 'len' data at 'in' with AES-GCM, using 128-bit or 256-bit key at 'key', 96-bit IV at
+ * 'iv' and write output to 'out' (which may be the same location as 'in') and 128-bit tag to
+ * 'tag'.
+ */
+ResponseCode AES_gcm_encrypt(const uint8_t* in, uint8_t* out, size_t len,
+                             const std::vector<uint8_t>& key, const uint8_t* iv, uint8_t* tag) {
+
+    // There can be 128-bit and 256-bit keys
+    const EVP_CIPHER* cipher = getAesCipherForKey(key);
+
     EVP_CIPHER_CTX_Ptr ctx(EVP_CIPHER_CTX_new());
 
-    EVP_EncryptInit_ex(ctx.get(), cipher, nullptr /* engine */, key, iv);
+    EVP_EncryptInit_ex(ctx.get(), cipher, nullptr /* engine */, key.data(), iv);
     EVP_CIPHER_CTX_set_padding(ctx.get(), 0 /* no padding needed with GCM */);
 
     std::unique_ptr<uint8_t[]> out_tmp(new uint8_t[len]);
@@ -102,15 +117,20 @@
 }
 
 /*
- * Decrypt 'len' data at 'in' with AES-GCM, using 128-bit key at 'key', 96-bit IV at 'iv', checking
- * 128-bit tag at 'tag' and writing plaintext to 'out' (which may be the same location as 'in').
+ * Decrypt 'len' data at 'in' with AES-GCM, using 128-bit or 256-bit key at 'key', 96-bit IV at
+ * 'iv', checking 128-bit tag at 'tag' and writing plaintext to 'out'(which may be the same
+ * location as 'in').
  */
-ResponseCode AES_gcm_decrypt(const uint8_t* in, uint8_t* out, size_t len, const uint8_t* key,
-                             const uint8_t* iv, const uint8_t* tag) {
-    const EVP_CIPHER* cipher = EVP_aes_128_gcm();
+ResponseCode AES_gcm_decrypt(const uint8_t* in, uint8_t* out, size_t len,
+                             const std::vector<uint8_t> key, const uint8_t* iv,
+                             const uint8_t* tag) {
+
+    // There can be 128-bit and 256-bit keys
+    const EVP_CIPHER* cipher = getAesCipherForKey(key);
+
     EVP_CIPHER_CTX_Ptr ctx(EVP_CIPHER_CTX_new());
 
-    EVP_DecryptInit_ex(ctx.get(), cipher, nullptr /* engine */, key, iv);
+    EVP_DecryptInit_ex(ctx.get(), cipher, nullptr /* engine */, key.data(), iv);
     EVP_CIPHER_CTX_set_padding(ctx.get(), 0 /* no padding needed with GCM */);
     EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_SET_TAG, kGcmTagLength, const_cast<uint8_t*>(tag));
 
@@ -139,7 +159,7 @@
 
 class ArrayStreamBuffer : public std::streambuf {
   public:
-    template <typename T, size_t size> ArrayStreamBuffer(const T (&data)[size]) {
+    template <typename T, size_t size> explicit ArrayStreamBuffer(const T (&data)[size]) {
         static_assert(sizeof(T) == 1, "Array element size too large");
         std::streambuf::char_type* d = const_cast<std::streambuf::char_type*>(
             reinterpret_cast<const std::streambuf::char_type*>(&data[0]));
@@ -296,7 +316,7 @@
 }
 
 static ResponseCode writeBlob(const std::string& filename, Blob blob, blobv3* rawBlob,
-                              const uint8_t* aes_key, State state, Entropy* entropy) {
+                              const std::vector<uint8_t>& aes_key, State state) {
     ALOGV("writing blob %s", filename.c_str());
 
     const size_t dataLength = rawBlob->length;
@@ -309,7 +329,7 @@
         }
 
         memset(rawBlob->initialization_vector, 0, AES_BLOCK_SIZE);
-        if (!entropy->generate_random_data(rawBlob->initialization_vector, kGcmIvSizeBytes)) {
+        if (!RAND_bytes(rawBlob->initialization_vector, kGcmIvSizeBytes)) {
             ALOGW("Could not read random data for: %s", filename.c_str());
             return ResponseCode::SYSTEM_ERROR;
         }
@@ -341,16 +361,15 @@
 }
 
 ResponseCode LockedKeyBlobEntry::writeBlobs(Blob keyBlob, Blob characteristicsBlob,
-                                            const uint8_t* aes_key, State state,
-                                            Entropy* entropy) const {
+                                            const std::vector<uint8_t>& aes_key,
+                                            State state) const {
     if (entry_ == nullptr) {
         return ResponseCode::SYSTEM_ERROR;
     }
     ResponseCode rc;
     if (keyBlob) {
         blobv3* rawBlob = keyBlob.mBlob.get();
-        rc = writeBlob(entry_->getKeyBlobPath(), std::move(keyBlob), rawBlob, aes_key, state,
-                       entropy);
+        rc = writeBlob(entry_->getKeyBlobPath(), std::move(keyBlob), rawBlob, aes_key, state);
         if (rc != ResponseCode::NO_ERROR) {
             return rc;
         }
@@ -359,12 +378,13 @@
     if (characteristicsBlob) {
         blobv3* rawBlob = characteristicsBlob.mBlob.get();
         rc = writeBlob(entry_->getCharacteristicsBlobPath(), std::move(characteristicsBlob),
-                       rawBlob, aes_key, state, entropy);
+                       rawBlob, aes_key, state);
     }
     return rc;
 }
 
-ResponseCode Blob::readBlob(const std::string& filename, const uint8_t* aes_key, State state) {
+ResponseCode Blob::readBlob(const std::string& filename, const std::vector<uint8_t>& aes_key,
+                            State state) {
     ResponseCode rc;
     ALOGV("reading blob %s", filename.c_str());
     std::unique_ptr<blobv3> rawBlob = std::make_unique<blobv3>();
@@ -414,7 +434,7 @@
             }
 
             AES_KEY key;
-            AES_set_decrypt_key(aes_key, kAesKeySize * 8, &key);
+            AES_set_decrypt_key(aes_key.data(), kAesKeySize * 8, &key);
             AES_cbc_encrypt(v2blob.encrypted, v2blob.encrypted, encryptedLength, &key,
                             v2blob.vector, AES_DECRYPT);
             key = {};  // clear key
@@ -445,8 +465,8 @@
     return ResponseCode::NO_ERROR;
 }
 
-std::tuple<ResponseCode, Blob, Blob> LockedKeyBlobEntry::readBlobs(const uint8_t* aes_key,
-                                                                   State state) const {
+std::tuple<ResponseCode, Blob, Blob>
+LockedKeyBlobEntry::readBlobs(const std::vector<uint8_t>& aes_key, State state) const {
     std::tuple<ResponseCode, Blob, Blob> result;
     auto& [rc, keyBlob, characteristicsBlob] = result;
     if (entry_ == nullptr) return rc = ResponseCode::SYSTEM_ERROR, result;
diff --git a/keystore/blob.h b/keystore/blob.h
index 92e4514..ce488ec 100644
--- a/keystore/blob.h
+++ b/keystore/blob.h
@@ -30,11 +30,13 @@
 #include <mutex>
 #include <set>
 #include <sstream>
+#include <vector>
 
 constexpr size_t kValueSize = 32768;
 constexpr size_t kAesKeySize = 128 / 8;
 constexpr size_t kGcmTagLength = 128 / 8;
 constexpr size_t kGcmIvLength = 96 / 8;
+constexpr size_t kAes128KeySizeBytes = 128 / 8;
 
 /* Here is the file format. There are two parts in blob.value, the secret and
  * the description. The secret is stored in ciphertext, and its original size
@@ -87,9 +89,9 @@
     TYPE_KEYMASTER_10 = 4,
     TYPE_KEY_CHARACTERISTICS = 5,
     TYPE_KEY_CHARACTERISTICS_CACHE = 6,
+    TYPE_MASTER_KEY_AES256 = 7,
 } BlobType;
 
-class Entropy;
 class LockedKeyBlobEntry;
 
 /**
@@ -115,7 +117,7 @@
 
     Blob& operator=(const Blob& rhs);
     Blob& operator=(Blob&& rhs);
-    operator bool() const { return bool(mBlob); }
+    explicit operator bool() const { return bool(mBlob); }
 
     const uint8_t* getValue() const { return mBlob->value; }
 
@@ -154,7 +156,8 @@
   private:
     std::unique_ptr<blobv3> mBlob;
 
-    ResponseCode readBlob(const std::string& filename, const uint8_t* aes_key, State state);
+    ResponseCode readBlob(const std::string& filename, const std::vector<uint8_t>& aes_key,
+                          State state);
 };
 
 /**
@@ -239,6 +242,7 @@
     static std::condition_variable locked_blobs_mutex_cond_var_;
 
     const KeyBlobEntry* entry_;
+    // NOLINTNEXTLINE(google-explicit-constructor)
     LockedKeyBlobEntry(const KeyBlobEntry& entry) : entry_(&entry) {}
 
     static void put(const KeyBlobEntry& entry);
@@ -262,12 +266,13 @@
          std::function<bool(uid_t, const std::string&)> filter =
              [](uid_t, const std::string&) -> bool { return true; });
 
-    ResponseCode writeBlobs(Blob keyBlob, Blob characteristicsBlob, const uint8_t* aes_key,
-                            State state, Entropy* entorpy) const;
-    std::tuple<ResponseCode, Blob, Blob> readBlobs(const uint8_t* aes_key, State state) const;
+    ResponseCode writeBlobs(Blob keyBlob, Blob characteristicsBlob,
+                            const std::vector<uint8_t>& aes_key, State state) const;
+    std::tuple<ResponseCode, Blob, Blob> readBlobs(const std::vector<uint8_t>& aes_key,
+                                                   State state) const;
     ResponseCode deleteBlobs() const;
 
-    inline operator bool() const { return entry_ != nullptr; }
+    inline explicit operator bool() const { return entry_ != nullptr; }
     inline const KeyBlobEntry& operator*() const { return *entry_; }
     inline const KeyBlobEntry* operator->() const { return entry_; }
 };
diff --git a/keystore/entropy.cpp b/keystore/entropy.cpp
deleted file mode 100644
index 8d4d305..0000000
--- a/keystore/entropy.cpp
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * Copyright (C) 2016 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#define LOG_TAG "keystore"
-
-#include "entropy.h"
-
-#include <errno.h>
-#include <fcntl.h>
-#include <stdio.h>
-#include <string.h>
-#include <unistd.h>
-
-#include <log/log.h>
-
-#include "keystore_utils.h"
-
-Entropy::~Entropy() {
-    if (mRandom >= 0) {
-        close(mRandom);
-    }
-}
-
-bool Entropy::open() {
-    const char* randomDevice = "/dev/urandom";
-    mRandom = TEMP_FAILURE_RETRY(::open(randomDevice, O_RDONLY));
-    if (mRandom < 0) {
-        ALOGE("open: %s: %s", randomDevice, strerror(errno));
-        return false;
-    }
-    return true;
-}
-
-bool Entropy::generate_random_data(uint8_t* data, size_t size) const {
-    return (readFully(mRandom, data, size) == size);
-}
diff --git a/keystore/entropy.h b/keystore/entropy.h
deleted file mode 100644
index 0e4d1b2..0000000
--- a/keystore/entropy.h
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * Copyright (C) 2016 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef KEYSTORE_ENTROPY_H_
-#define KEYSTORE_ENTROPY_H_
-
-#include <stdint.h>
-
-class Entropy {
-  public:
-    Entropy() : mRandom(-1) {}
-    ~Entropy();
-
-    bool open();
-    bool generate_random_data(uint8_t* data, size_t size) const;
-
-  private:
-    int mRandom;
-};
-
-#endif  // KEYSTORE_ENTROPY_H_
diff --git a/keystore/grant_store.h b/keystore/grant_store.h
index f8e4f91..1baf32c 100644
--- a/keystore/grant_store.h
+++ b/keystore/grant_store.h
@@ -48,6 +48,7 @@
 
   uint64_t grant_no_;  ///< numeric grant identifier - randomly assigned
 
+  // NOLINTNEXTLINE(google-explicit-constructor)
   operator const uint64_t&() const { return grant_no_; }
 };
 
diff --git a/keystore/include/keystore/KeyAttestationApplicationId.h b/keystore/include/keystore/KeyAttestationApplicationId.h
index dc914c1..861c2e1 100644
--- a/keystore/include/keystore/KeyAttestationApplicationId.h
+++ b/keystore/include/keystore/KeyAttestationApplicationId.h
@@ -33,8 +33,8 @@
     typedef std::vector<std::unique_ptr<KeyAttestationPackageInfo>> PackageInfoVector;
     KeyAttestationApplicationId();
     // Following c'tors are for initializing instances containing test data.
-    KeyAttestationApplicationId(std::unique_ptr<KeyAttestationPackageInfo> package);
-    KeyAttestationApplicationId(PackageInfoVector packages);
+    explicit KeyAttestationApplicationId(std::unique_ptr<KeyAttestationPackageInfo> package);
+    explicit KeyAttestationApplicationId(PackageInfoVector packages);
 
     status_t writeToParcel(Parcel*) const override;
     status_t readFromParcel(const Parcel* parcel) override;
diff --git a/keystore/include/keystore/KeyCharacteristics.h b/keystore/include/keystore/KeyCharacteristics.h
index 40d495c..9c90b8a 100644
--- a/keystore/include/keystore/KeyCharacteristics.h
+++ b/keystore/include/keystore/KeyCharacteristics.h
@@ -27,7 +27,7 @@
 // Parcelable version of keystore::KeyCharacteristics
 struct KeyCharacteristics : public ::android::Parcelable {
     KeyCharacteristics(){};
-    KeyCharacteristics(::keystore::KeyCharacteristics&& other) {
+    explicit KeyCharacteristics(::keystore::KeyCharacteristics&& other) {
         softwareEnforced = std::move(other.softwareEnforced);
         hardwareEnforced = std::move(other.hardwareEnforced);
     }
diff --git a/keystore/include/keystore/KeymasterArguments.h b/keystore/include/keystore/KeymasterArguments.h
index b453b11..3d22f5f 100644
--- a/keystore/include/keystore/KeymasterArguments.h
+++ b/keystore/include/keystore/KeymasterArguments.h
@@ -26,6 +26,7 @@
 // struct for serializing/deserializing a list of KeyParameters
 struct KeymasterArguments : public Parcelable {
     KeymasterArguments(){};
+    // NOLINTNEXTLINE(google-explicit-constructor)
     KeymasterArguments(hardware::hidl_vec<::keystore::KeyParameter>&& other);
     explicit KeymasterArguments(const hardware::hidl_vec<::keystore::KeyParameter>& other);
 
diff --git a/keystore/include/keystore/KeystoreResponse.h b/keystore/include/keystore/KeystoreResponse.h
index 5ad260d..20f7274 100644
--- a/keystore/include/keystore/KeystoreResponse.h
+++ b/keystore/include/keystore/KeystoreResponse.h
@@ -34,6 +34,7 @@
         : response_code_(response_code), error_msg_(std::make_unique<String16>(error_msg)) {}
     explicit KeystoreResponse(const int response_code)
         : response_code_(response_code), error_msg_() {}
+    // NOLINTNEXTLINE(google-explicit-constructor)
     KeystoreResponse(const ::keystore::KeyStoreServiceReturnCode& rc)
         : response_code_(rc.getErrorCode()), error_msg_() {}
     KeystoreResponse(const KeystoreResponse& other)
diff --git a/keystore/include/keystore/Signature.h b/keystore/include/keystore/Signature.h
index 31ecdef..f39acec 100644
--- a/keystore/include/keystore/Signature.h
+++ b/keystore/include/keystore/Signature.h
@@ -27,7 +27,7 @@
   public:
     Signature() = default;
     // Intended for initializing instances containing test data.
-    Signature(std::vector<uint8_t> signature_data);
+    explicit Signature(std::vector<uint8_t> signature_data);
 
     status_t writeToParcel(Parcel*) const override;
     status_t readFromParcel(const Parcel* parcel) override;
diff --git a/keystore/include/keystore/keystore_concurrency.h b/keystore/include/keystore/keystore_concurrency.h
index b60b7a6..039ca31 100644
--- a/keystore/include/keystore/keystore_concurrency.h
+++ b/keystore/include/keystore/keystore_concurrency.h
@@ -85,9 +85,10 @@
 
   public:
     ProxyLock() : impl_() {}
+    // NOLINTNEXTLINE(google-explicit-constructor)
     template <typename... Args> ProxyLock(Args&&... args) : impl_{std::forward<Args>(args)...} {}
-    ProxyLock(Implementation&& impl) : impl_(std::move(impl)) {}
-    operator bool() const { return impl_.value() != nullptr; }
+    explicit ProxyLock(Implementation&& impl) : impl_(std::move(impl)) {}
+    explicit operator bool() const { return impl_.value() != nullptr; }
 
     template <typename T = typename Implementation::lockedType>
     std::enable_if_t<!std::is_const<typename Implementation::lockedType>::value, T*> operator->() {
diff --git a/keystore/include/keystore/keystore_return_types.h b/keystore/include/keystore/keystore_return_types.h
index e091447..f8cf1cc 100644
--- a/keystore/include/keystore/keystore_return_types.h
+++ b/keystore/include/keystore/keystore_return_types.h
@@ -41,10 +41,13 @@
 class KeyStoreServiceReturnCode {
   public:
     KeyStoreServiceReturnCode() : errorCode_(0) {}
+    // NOLINTNEXTLINE(google-explicit-constructor)
     KeyStoreServiceReturnCode(const ErrorCode& errorCode) : errorCode_(int32_t(errorCode)) {}
+    // NOLINTNEXTLINE(google-explicit-constructor)
     KeyStoreServiceReturnCode(const ResponseCode& errorCode) : errorCode_(int32_t(errorCode)) {}
     KeyStoreServiceReturnCode(const KeyStoreServiceReturnCode& errorCode)
         : errorCode_(errorCode.errorCode_) {}
+    // NOLINTNEXTLINE(google-explicit-constructor)
     KeyStoreServiceReturnCode(const KeyStoreNativeReturnCode& errorCode);
     explicit inline KeyStoreServiceReturnCode(const int32_t& errorCode) : errorCode_(errorCode) {}
     inline KeyStoreServiceReturnCode& operator=(const ErrorCode& errorCode) {
@@ -115,11 +118,14 @@
 class KeyStoreNativeReturnCode {
   public:
     KeyStoreNativeReturnCode() : errorCode_(0) {}
+    // NOLINTNEXTLINE(google-explicit-constructor)
     KeyStoreNativeReturnCode(const ErrorCode& errorCode) : errorCode_(int32_t(errorCode)) {}
+    // NOLINTNEXTLINE(google-explicit-constructor)
     KeyStoreNativeReturnCode(const ResponseCode& errorCode) : errorCode_(int32_t(errorCode)) {}
     KeyStoreNativeReturnCode(const KeyStoreNativeReturnCode& errorCode)
         : errorCode_(errorCode.errorCode_) {}
     explicit inline KeyStoreNativeReturnCode(const int32_t& errorCode) : errorCode_(errorCode) {}
+    // NOLINTNEXTLINE(google-explicit-constructor)
     KeyStoreNativeReturnCode(const KeyStoreServiceReturnCode& errorcode);
     inline KeyStoreNativeReturnCode& operator=(const ErrorCode& errorCode) {
         errorCode_ = int32_t(errorCode);
diff --git a/keystore/include/keystore/utils.h b/keystore/include/keystore/utils.h
index 1d8208a..544dd21 100644
--- a/keystore/include/keystore/utils.h
+++ b/keystore/include/keystore/utils.h
@@ -29,8 +29,12 @@
     typedef std::shared_ptr<CollectionType> CollectionPtr;
 
     SharedNullableIterator() {}
-    SharedNullableIterator(const std::shared_ptr<CollectionType>& coll) : coll_(coll) { init(); }
-    SharedNullableIterator(std::shared_ptr<CollectionType>&& coll) : coll_(coll) { init(); }
+    explicit SharedNullableIterator(const std::shared_ptr<CollectionType>& coll) : coll_(coll) {
+        init();
+    }
+    explicit SharedNullableIterator(std::shared_ptr<CollectionType>&& coll) : coll_(coll) {
+        init();
+    }
 
     SharedNullableIterator(const SharedNullableIterator& other)
         : coll_(other.coll_), cur_(other.cur_) {}
diff --git a/keystore/key_store_service.cpp b/keystore/key_store_service.cpp
index 2f17848..a7fcd38 100644
--- a/keystore/key_store_service.cpp
+++ b/keystore/key_store_service.cpp
@@ -281,7 +281,7 @@
  * if the password/pin is removed. Only allowed to be called by system.
  * The output is bound by the initial size of uidsOut to be compatible with Java.
  */
-Status KeyStoreService::listUidsOfAuthBoundKeys(::std::vector<int32_t>* uidsOut,
+Status KeyStoreService::listUidsOfAuthBoundKeys(std::vector<std::string>* uidsOut,
                                                 int32_t* aidl_return) {
     const int32_t callingUid = IPCThreadState::self()->getCallingUid();
     const int32_t userId = get_user_id(callingUid);
@@ -312,14 +312,11 @@
         return Status::fromServiceSpecificError(static_cast<int32_t>(rc));
     }
 
-    auto it = uidsOut->begin();
     for (LockedKeyBlobEntry& entry : internal_matches) {
-        if (it == uidsOut->end()) {
-            ALOGW("Maximum number (%d) of auth bound uids found, truncating remainder",
-                  static_cast<int32_t>(uidsOut->capacity()));
-            break;
-        }
-        if (std::find(uidsOut->begin(), it, entry->uid()) != it) {
+        // Need to store uids as a list of strings because integer list output
+        // parameters is not supported in aidl-cpp.
+        std::string entryUid = std::to_string(entry->uid());
+        if (std::find(uidsOut->begin(), uidsOut->end(), entryUid) != uidsOut->end()) {
             // uid already in list, skip
             continue;
         }
@@ -331,7 +328,7 @@
         }
 
         if (blob && blob.isEncrypted()) {
-            *it++ = entry->uid();
+            uidsOut->push_back(entryUid);
         } else if (charBlob) {
             auto [success, hwEnforced, swEnforced] = charBlob.getKeyCharacteristics();
             if (!success) {
@@ -340,7 +337,7 @@
             }
             if (hwEnforced.Contains(TAG_USER_SECURE_ID) ||
                 swEnforced.Contains(TAG_USER_SECURE_ID)) {
-                *it++ = entry->uid();
+                uidsOut->push_back(entryUid);
             }
         }
     }
diff --git a/keystore/key_store_service.h b/keystore/key_store_service.h
index 5a3586f..2171213 100644
--- a/keystore/key_store_service.h
+++ b/keystore/key_store_service.h
@@ -61,7 +61,7 @@
                                     int32_t* _aidl_return) override;
     ::android::binder::Status list(const ::android::String16& namePrefix, int32_t uid,
                                    ::std::vector<::android::String16>* _aidl_return) override;
-    ::android::binder::Status listUidsOfAuthBoundKeys(::std::vector<int32_t>* uids,
+    ::android::binder::Status listUidsOfAuthBoundKeys(std::vector<::std::string>* uids,
                                                       int32_t* _aidl_return) override;
 
     ::android::binder::Status reset(int32_t* _aidl_return) override;
diff --git a/keystore/keymaster_worker.cpp b/keystore/keymaster_worker.cpp
index c7d2671..d2175b8 100644
--- a/keystore/keymaster_worker.cpp
+++ b/keystore/keymaster_worker.cpp
@@ -346,7 +346,7 @@
         {
             hidl_vec<uint8_t> clientId;
             hidl_vec<uint8_t> appData;
-            for (auto param : opParams) {
+            for (const auto& param : opParams) {
                 if (param.tag == Tag::APPLICATION_ID) {
                     clientId = authorizationValue(TAG_APPLICATION_ID, param).value();
                 } else if (param.tag == Tag::APPLICATION_DATA) {
@@ -535,7 +535,7 @@
     std::function<void()> f_;
 
   public:
-    Finalize(std::function<void()> f) : f_(f) {}
+    explicit Finalize(std::function<void()> f) : f_(f) {}
     ~Finalize() {
         if (f_) f_();
     }
diff --git a/keystore/keymaster_worker.h b/keystore/keymaster_worker.h
index 2a35977..c02d389 100644
--- a/keystore/keymaster_worker.h
+++ b/keystore/keymaster_worker.h
@@ -95,6 +95,7 @@
 
       public:
         NonCopyableFunction() = default;
+        // NOLINTNEXTLINE(google-explicit-constructor)
         template <typename F> NonCopyableFunction(F f) {
             f_ = std::make_unique<NonCopyableFunctionTypeEraser<F>>(std::move(f));
         }
diff --git a/keystore/keystore_attestation_id.h b/keystore/keystore_attestation_id.h
index f45d5be..63015ee 100644
--- a/keystore/keystore_attestation_id.h
+++ b/keystore/keystore_attestation_id.h
@@ -33,12 +33,18 @@
 
 template <typename T> class StatusOr {
   public:
+    // NOLINTNEXTLINE(google-explicit-constructor)
     StatusOr(const status_t error) : _status(error), _value() {}
+    // NOLINTNEXTLINE(google-explicit-constructor)
     StatusOr(const T& value) : _status(NO_ERROR), _value(value) {}
+    // NOLINTNEXTLINE(google-explicit-constructor)
     StatusOr(T&& value) : _status(NO_ERROR), _value(value) {}
 
+    // NOLINTNEXTLINE(google-explicit-constructor)
     operator const T&() const { return _value; }
+    // NOLINTNEXTLINE(google-explicit-constructor)
     operator T&() { return _value; }
+    // NOLINTNEXTLINE(google-explicit-constructor)
     operator T &&() && { return std::move(_value); }
 
     bool isOk() const { return NO_ERROR == _status; }
diff --git a/keystore/keystore_cli_v2.cpp b/keystore/keystore_cli_v2.cpp
index 0500da2..b46b221 100644
--- a/keystore/keystore_cli_v2.cpp
+++ b/keystore/keystore_cli_v2.cpp
@@ -384,7 +384,7 @@
         return 1;
     }
     int32_t aidl_return;
-    ::std::vector<int32_t> uids(100);
+    ::std::vector<::std::string> uids;
     android::binder::Status status = service->listUidsOfAuthBoundKeys(&uids, &aidl_return);
     if (!status.isOk()) {
         fprintf(stderr, "Requesting uids of auth bound keys failed with error %s.\n",
@@ -397,8 +397,7 @@
     }
     printf("Apps with auth bound keys:\n");
     for (auto i = uids.begin(); i != uids.end(); ++i) {
-        if (*i == 0) break;
-        printf("%d\n", *i);
+        printf("%s\n", i->c_str());
     }
     return 0;
 }
diff --git a/keystore/keystore_main.cpp b/keystore/keystore_main.cpp
index 409ac83..70f38cc 100644
--- a/keystore/keystore_main.cpp
+++ b/keystore/keystore_main.cpp
@@ -32,7 +32,6 @@
 #include <keystore/keystore_return_types.h>
 
 #include "KeyStore.h"
-#include "entropy.h"
 #include "key_store_service.h"
 #include "legacy_keymaster_device_wrapper.h"
 #include "permissions.h"
@@ -136,9 +135,6 @@
     CHECK(argc >= 2) << "A directory must be specified!";
     CHECK(chdir(argv[1]) != -1) << "chdir: " << argv[1] << ": " << strerror(errno);
 
-    Entropy entropy;
-    CHECK(entropy.open()) << "Failed to open entropy source.";
-
     auto kmDevices = initializeKeymasters();
 
     CHECK(kmDevices[SecurityLevel::SOFTWARE]) << "Missing software Keymaster device";
@@ -156,7 +152,7 @@
         halVersion.majorVersion >= 2 ? SecurityLevel::TRUSTED_ENVIRONMENT : SecurityLevel::SOFTWARE;
 
     android::sp<keystore::KeyStore> keyStore(
-        new keystore::KeyStore(&entropy, kmDevices, minimalAllowedSecurityLevelForNewKeys));
+        new keystore::KeyStore(kmDevices, minimalAllowedSecurityLevelForNewKeys));
     keyStore->initialize();
     android::sp<android::IServiceManager> sm = android::defaultServiceManager();
     android::sp<keystore::KeyStoreService> service = new keystore::KeyStoreService(keyStore);
diff --git a/keystore/legacy_keymaster_device_wrapper.cpp b/keystore/legacy_keymaster_device_wrapper.cpp
index 4073b42..86d286e 100644
--- a/keystore/legacy_keymaster_device_wrapper.cpp
+++ b/keystore/legacy_keymaster_device_wrapper.cpp
@@ -66,7 +66,7 @@
 
 class KmParamSet : public keymaster_key_param_set_t {
   public:
-    KmParamSet(const hidl_vec<KeyParameter>& keyParams) {
+    explicit KmParamSet(const hidl_vec<KeyParameter>& keyParams) {
         params = new keymaster_key_param_t[keyParams.size()];
         length = keyParams.size();
         for (size_t i = 0; i < keyParams.size(); ++i) {
diff --git a/keystore/legacy_keymaster_device_wrapper.h b/keystore/legacy_keymaster_device_wrapper.h
index ad26221..cd2e5a7 100644
--- a/keystore/legacy_keymaster_device_wrapper.h
+++ b/keystore/legacy_keymaster_device_wrapper.h
@@ -43,7 +43,7 @@
 
 class LegacyKeymasterDeviceWrapper : public IKeymasterDevice {
   public:
-    LegacyKeymasterDeviceWrapper(keymaster2_device_t* dev);
+    explicit LegacyKeymasterDeviceWrapper(keymaster2_device_t* dev);
     virtual ~LegacyKeymasterDeviceWrapper();
 
     // Methods from ::android::hardware::keymaster::V3_0::IKeymasterDevice follow.
diff --git a/keystore/user_state.cpp b/keystore/user_state.cpp
index c9a2d72..bc3f6d9 100644
--- a/keystore/user_state.cpp
+++ b/keystore/user_state.cpp
@@ -24,7 +24,9 @@
 #include <stdlib.h>
 #include <sys/stat.h>
 
+#include <openssl/digest.h>
 #include <openssl/evp.h>
+#include <openssl/rand.h>
 
 #include <log/log.h>
 
@@ -73,7 +75,7 @@
 }
 
 void UserState::zeroizeMasterKeysInMemory() {
-    memset(mMasterKey, 0, sizeof(mMasterKey));
+    memset(mMasterKey.data(), 0, mMasterKey.size());
     memset(mSalt, 0, sizeof(mSalt));
 }
 
@@ -83,11 +85,11 @@
     return unlink(mMasterKeyEntry.getKeyBlobPath().c_str()) == 0 || errno == ENOENT;
 }
 
-ResponseCode UserState::initialize(const android::String8& pw, Entropy* entropy) {
-    if (!generateMasterKey(entropy)) {
+ResponseCode UserState::initialize(const android::String8& pw) {
+    if (!generateMasterKey()) {
         return ResponseCode::SYSTEM_ERROR;
     }
-    ResponseCode response = writeMasterKey(pw, entropy);
+    ResponseCode response = writeMasterKey(pw);
     if (response != ResponseCode::NO_ERROR) {
         return response;
     }
@@ -102,7 +104,7 @@
     if ((*src)->getState() != STATE_NO_ERROR) {
         return ResponseCode::SYSTEM_ERROR;
     }
-    memcpy(mMasterKey, (*src)->mMasterKey, MASTER_KEY_SIZE_BYTES);
+    mMasterKey = (*src)->mMasterKey;
     setupMasterKeys();
     return copyMasterKeyFile(src);
 }
@@ -137,15 +139,16 @@
     return ResponseCode::NO_ERROR;
 }
 
-ResponseCode UserState::writeMasterKey(const android::String8& pw, Entropy* entropy) {
-    uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
-    generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, mSalt);
-    Blob masterKeyBlob(mMasterKey, sizeof(mMasterKey), mSalt, sizeof(mSalt), TYPE_MASTER_KEY);
+ResponseCode UserState::writeMasterKey(const android::String8& pw) {
+    std::vector<uint8_t> passwordKey(MASTER_KEY_SIZE_BYTES);
+    generateKeyFromPassword(passwordKey, pw, mSalt);
+    Blob masterKeyBlob(mMasterKey.data(), mMasterKey.size(), mSalt, sizeof(mSalt),
+                       TYPE_MASTER_KEY_AES256);
     auto lockedEntry = LockedKeyBlobEntry::get(mMasterKeyEntry);
-    return lockedEntry.writeBlobs(masterKeyBlob, {}, passwordKey, STATE_NO_ERROR, entropy);
+    return lockedEntry.writeBlobs(masterKeyBlob, {}, passwordKey, STATE_NO_ERROR);
 }
 
-ResponseCode UserState::readMasterKey(const android::String8& pw, Entropy* entropy) {
+ResponseCode UserState::readMasterKey(const android::String8& pw) {
 
     auto lockedEntry = LockedKeyBlobEntry::get(mMasterKeyEntry);
 
@@ -168,8 +171,14 @@
     } else {
         salt = nullptr;
     }
-    uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
-    generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, salt);
+
+    size_t masterKeySize = MASTER_KEY_SIZE_BYTES;
+    if (rawBlob.type == TYPE_MASTER_KEY) {
+        masterKeySize = SHA1_DIGEST_SIZE_BYTES;
+    }
+
+    std::vector<uint8_t> passwordKey(masterKeySize);
+    generateKeyFromPassword(passwordKey, pw, salt);
     Blob masterKeyBlob, dummyBlob;
     ResponseCode response;
     std::tie(response, masterKeyBlob, dummyBlob) =
@@ -177,16 +186,21 @@
     if (response == ResponseCode::SYSTEM_ERROR) {
         return response;
     }
-    if (response == ResponseCode::NO_ERROR && masterKeyBlob.getLength() == MASTER_KEY_SIZE_BYTES) {
+
+    size_t masterKeyBlobLength = static_cast<size_t>(masterKeyBlob.getLength());
+
+    if (response == ResponseCode::NO_ERROR && masterKeyBlobLength == masterKeySize) {
         // If salt was missing, generate one and write a new master key file with the salt.
         if (salt == nullptr) {
-            if (!generateSalt(entropy)) {
+            if (!generateSalt()) {
                 return ResponseCode::SYSTEM_ERROR;
             }
-            response = writeMasterKey(pw, entropy);
+            response = writeMasterKey(pw);
         }
         if (response == ResponseCode::NO_ERROR) {
-            memcpy(mMasterKey, masterKeyBlob.getValue(), MASTER_KEY_SIZE_BYTES);
+            mMasterKey = std::vector<uint8_t>(masterKeyBlob.getValue(),
+                                              masterKeyBlob.getValue() + masterKeyBlob.getLength());
+
             setupMasterKeys();
         }
         return response;
@@ -234,7 +248,7 @@
     return true;
 }
 
-void UserState::generateKeyFromPassword(uint8_t* key, ssize_t keySize, const android::String8& pw,
+void UserState::generateKeyFromPassword(std::vector<uint8_t>& key, const android::String8& pw,
                                         uint8_t* salt) {
     size_t saltSize;
     if (salt != nullptr) {
@@ -246,19 +260,27 @@
         saltSize = sizeof("keystore");
     }
 
-    PKCS5_PBKDF2_HMAC_SHA1(reinterpret_cast<const char*>(pw.string()), pw.length(), salt, saltSize,
-                           8192, keySize, key);
+    const EVP_MD* digest = EVP_sha256();
+
+    // SHA1 was used prior to increasing the key size
+    if (key.size() == SHA1_DIGEST_SIZE_BYTES) {
+        digest = EVP_sha1();
+    }
+
+    PKCS5_PBKDF2_HMAC(reinterpret_cast<const char*>(pw.string()), pw.length(), salt, saltSize, 8192,
+                      digest, key.size(), key.data());
 }
 
-bool UserState::generateSalt(Entropy* entropy) {
-    return entropy->generate_random_data(mSalt, sizeof(mSalt));
+bool UserState::generateSalt() {
+    return RAND_bytes(mSalt, sizeof(mSalt));
 }
 
-bool UserState::generateMasterKey(Entropy* entropy) {
-    if (!entropy->generate_random_data(mMasterKey, sizeof(mMasterKey))) {
+bool UserState::generateMasterKey() {
+    mMasterKey.resize(MASTER_KEY_SIZE_BYTES);
+    if (!RAND_bytes(mMasterKey.data(), mMasterKey.size())) {
         return false;
     }
-    if (!generateSalt(entropy)) {
+    if (!generateSalt()) {
         return false;
     }
     return true;
diff --git a/keystore/user_state.h b/keystore/user_state.h
index 365941e..b0671e3 100644
--- a/keystore/user_state.h
+++ b/keystore/user_state.h
@@ -26,7 +26,6 @@
 #include <keystore/keystore.h>
 
 #include "blob.h"
-#include "entropy.h"
 #include "keystore_utils.h"
 
 #include <android-base/logging.h>
@@ -34,6 +33,7 @@
 #include <keystore/keystore_concurrency.h>
 #include <mutex>
 #include <set>
+#include <vector>
 
 namespace keystore {
 
@@ -60,14 +60,14 @@
     void zeroizeMasterKeysInMemory();
     bool deleteMasterKey();
 
-    ResponseCode initialize(const android::String8& pw, Entropy* entropy);
+    ResponseCode initialize(const android::String8& pw);
 
     ResponseCode copyMasterKey(LockedUserState<UserState>* src);
     ResponseCode copyMasterKeyFile(LockedUserState<UserState>* src);
-    ResponseCode writeMasterKey(const android::String8& pw, Entropy* entropy);
-    ResponseCode readMasterKey(const android::String8& pw, Entropy* entropy);
+    ResponseCode writeMasterKey(const android::String8& pw);
+    ResponseCode readMasterKey(const android::String8& pw);
 
-    const uint8_t* getEncryptionKey() const { return &mMasterKey[0]; }
+    const std::vector<uint8_t>& getEncryptionKey() const { return mMasterKey; }
 
     bool reset();
 
@@ -75,16 +75,19 @@
     bool operator<(uid_t userId) const;
 
   private:
-    static const int MASTER_KEY_SIZE_BYTES = 16;
+    static const int SHA1_DIGEST_SIZE_BYTES = 16;
+    static const int SHA256_DIGEST_SIZE_BYTES = 32;
+
+    static const int MASTER_KEY_SIZE_BYTES = SHA256_DIGEST_SIZE_BYTES;
     static const int MASTER_KEY_SIZE_BITS = MASTER_KEY_SIZE_BYTES * 8;
 
     static const int MAX_RETRY = 4;
     static const size_t SALT_SIZE = 16;
 
-    void generateKeyFromPassword(uint8_t* key, ssize_t keySize, const android::String8& pw,
+    void generateKeyFromPassword(std::vector<uint8_t>& key, const android::String8& pw,
                                  uint8_t* salt);
-    bool generateSalt(Entropy* entropy);
-    bool generateMasterKey(Entropy* entropy);
+    bool generateSalt();
+    bool generateMasterKey();
     void setupMasterKeys();
 
     KeyBlobEntry mMasterKeyEntry;
@@ -93,7 +96,7 @@
     State mState;
     int8_t mRetry;
 
-    uint8_t mMasterKey[MASTER_KEY_SIZE_BYTES];
+    std::vector<uint8_t> mMasterKey;
     uint8_t mSalt[SALT_SIZE];
 };