Merge "Fix/suppress system/security google-explicit-constructor warnings"
diff --git a/keystore/Android.bp b/keystore/Android.bp
index c1d81b3..a12183f 100644
--- a/keystore/Android.bp
+++ b/keystore/Android.bp
@@ -25,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..25ff3a5 100644
--- a/keystore/KeyStore.h
+++ b/keystore/KeyStore.h
@@ -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/blob.cpp b/keystore/blob.cpp
index a636065..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));
 
@@ -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 ff9195d..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;
 
 /**
@@ -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);
 };
 
 /**
@@ -263,9 +266,10 @@
          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 explicit operator bool() const { return entry_ != nullptr; }
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/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/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];
 };