Snap for 5450365 from 2901ff5e4e69a0581fa3c11adee192fce658b8f0 to pi-platform-release

Change-Id: I67bd0e7bc849fcaca90e952547ad9d4d54e05ea6
diff --git a/keystore/Android.bp b/keystore/Android.bp
index 8af8717..8d095e1 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",
@@ -77,6 +76,13 @@
         pdk: {
             enabled: false,
         },
+        debuggable: {
+            cflags: [
+                // Allow VTS tests running as root to have
+                // additional permissions.
+                "-DGRANT_ROOT_ALL_PERMISSIONS",
+            ],
+        },
     },
 
     required: ["keystore_cli_v2"],
diff --git a/keystore/KeyStore.cpp b/keystore/KeyStore.cpp
index f197d91..428b51e 100644
--- a/keystore/KeyStore.cpp
+++ b/keystore/KeyStore.cpp
@@ -63,9 +63,9 @@
     return (*const_cast<KeymasterDevices*>(this))[secLevel];
 }
 
-KeyStore::KeyStore(Entropy* entropy, const KeymasterDevices& kmDevices,
+KeyStore::KeyStore(const KeymasterDevices& kmDevices,
                    SecurityLevel minimalAllowedSecurityLevelForNewKeys)
-    : mEntropy(entropy), mKmDevices(kmDevices),
+    : mKmDevices(kmDevices),
       mAllowNewFallback(minimalAllowedSecurityLevelForNewKeys == SecurityLevel::SOFTWARE) {
     memset(&mMetaData, '\0', sizeof(mMetaData));
 }
@@ -89,7 +89,7 @@
 
 ResponseCode KeyStore::initializeUser(const android::String8& pw, uid_t userId) {
     UserState* userState = getUserState(userId);
-    return userState->initialize(pw, mEntropy);
+    return userState->initialize(pw);
 }
 
 ResponseCode KeyStore::copyMasterKey(uid_t srcUser, uid_t dstUser) {
@@ -100,12 +100,12 @@
 
 ResponseCode KeyStore::writeMasterKey(const android::String8& pw, uid_t userId) {
     UserState* userState = getUserState(userId);
-    return userState->writeMasterKey(pw, mEntropy);
+    return userState->writeMasterKey(pw);
 }
 
 ResponseCode KeyStore::readMasterKey(const android::String8& pw, uid_t userId) {
     UserState* userState = getUserState(userId);
-    return userState->readMasterKey(pw, mEntropy);
+    return userState->readMasterKey(pw);
 }
 
 /* Here is the encoding of keys. This is necessary in order to allow arbitrary
@@ -360,8 +360,7 @@
 
 ResponseCode KeyStore::put(const char* filename, Blob* keyBlob, uid_t userId) {
     UserState* userState = getUserState(userId);
-    return keyBlob->writeBlob(filename, userState->getEncryptionKey(), userState->getState(),
-                              mEntropy);
+    return keyBlob->writeBlob(filename, userState->getEncryptionKey(), userState->getState());
 }
 
 static NullOr<std::tuple<uid_t, std::string>> filename2UidAlias(const std::string& filename);
diff --git a/keystore/KeyStore.h b/keystore/KeyStore.h
index 23476d2..f0fe9d3 100644
--- a/keystore/KeyStore.h
+++ b/keystore/KeyStore.h
@@ -40,7 +40,7 @@
 
 class KeyStore {
   public:
-    KeyStore(Entropy* entropy, const KeymasterDevices& kmDevices,
+    KeyStore(const KeymasterDevices& kmDevices,
              SecurityLevel minimalAllowedSecurityLevelForNewKeys);
     ~KeyStore();
 
@@ -140,7 +140,6 @@
     static const char* kMetaDataFile;
     static const android::String16 kRsaKeyType;
     static const android::String16 kEcKeyType;
-    Entropy* mEntropy;
 
     KeymasterDevices mKmDevices;
     bool mAllowNewFallback;
diff --git a/keystore/blob.cpp b/keystore/blob.cpp
index d21c691..c3956f0 100644
--- a/keystore/blob.cpp
+++ b/keystore/blob.cpp
@@ -19,12 +19,12 @@
 #include <arpa/inet.h>
 #include <errno.h>
 #include <fcntl.h>
+#include <openssl/rand.h>
 #include <string.h>
 
 #include <cutils/log.h>
 
 #include "blob.h"
-#include "entropy.h"
 
 #include "keystore_utils.h"
 
@@ -60,16 +60,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]);
@@ -93,15 +108,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));
 
@@ -205,8 +225,8 @@
     }
 }
 
-ResponseCode Blob::writeBlob(const std::string& filename, const uint8_t* aes_key, State state,
-                             Entropy* entropy) {
+ResponseCode Blob::writeBlob(const std::string& filename, const std::vector<uint8_t>& aes_key,
+                             State state) {
     ALOGV("writing blob %s", filename.c_str());
 
     const size_t dataLength = mBlob.length;
@@ -219,7 +239,7 @@
         }
 
         memset(mBlob.initialization_vector, 0, AES_BLOCK_SIZE);
-        if (!entropy->generate_random_data(mBlob.initialization_vector, kGcmIvSizeBytes)) {
+        if (!RAND_bytes(mBlob.initialization_vector, kGcmIvSizeBytes)) {
             ALOGW("Could not read random data for: %s", filename.c_str());
             return ResponseCode::SYSTEM_ERROR;
         }
@@ -255,7 +275,8 @@
     return ResponseCode::NO_ERROR;
 }
 
-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) {
     ALOGV("reading blob %s", filename.c_str());
     const int in = TEMP_FAILURE_RETRY(open(filename.c_str(), O_RDONLY));
     if (in < 0) {
@@ -299,7 +320,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(blob.encrypted, blob.encrypted, encryptedLength, &key, blob.vector,
                             AES_DECRYPT);
             key = {};  // clear key
diff --git a/keystore/blob.h b/keystore/blob.h
index 665e07a..dc70709 100644
--- a/keystore/blob.h
+++ b/keystore/blob.h
@@ -24,11 +24,13 @@
 
 #include <keystore/keymaster_types.h>
 #include <keystore/keystore.h>
+#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
@@ -80,10 +82,9 @@
     TYPE_KEY_PAIR = 3,
     TYPE_KEYMASTER_10 = 4,
     TYPE_KEY_CHARACTERISTICS = 5,
+    TYPE_MASTER_KEY_AES256 = 7,
 } BlobType;
 
-class Entropy;
-
 class Blob {
   public:
     Blob(const uint8_t* value, size_t valueLength, const uint8_t* info, uint8_t infoLength,
@@ -121,9 +122,10 @@
     keystore::SecurityLevel getSecurityLevel() const;
     void setSecurityLevel(keystore::SecurityLevel);
 
-    ResponseCode writeBlob(const std::string& filename, const uint8_t* aes_key, State state,
-                           Entropy* entropy);
-    ResponseCode readBlob(const std::string& filename, const uint8_t* aes_key, State state);
+    ResponseCode writeBlob(const std::string& filename, const std::vector<uint8_t>& aes_key,
+                           State state);
+    ResponseCode readBlob(const std::string& filename, const std::vector<uint8_t>& aes_key,
+                          State state);
 
   private:
     blobv3 mBlob;
diff --git a/keystore/entropy.cpp b/keystore/entropy.cpp
deleted file mode 100644
index 1bfe9a1..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 <cutils/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_client_impl.cpp b/keystore/keystore_client_impl.cpp
index 6d998ad..994e3f2 100644
--- a/keystore/keystore_client_impl.cpp
+++ b/keystore/keystore_client_impl.cpp
@@ -366,7 +366,7 @@
     int32_t result;
     auto binder_result = keystore_->exist(key_name16, kDefaultUID, &result);
     if (!binder_result.isOk()) return false;  // binder error
-    return result;
+    return result == static_cast<int32_t>(ResponseCode::NO_ERROR);
 }
 
 bool KeystoreClientImpl::listKeys(const std::string& prefix,
diff --git a/keystore/keystore_main.cpp b/keystore/keystore_main.cpp
index 82d4e69..52e83c8 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";
@@ -155,7 +151,7 @@
     SecurityLevel minimalAllowedSecurityLevelForNewKeys =
         halVersion.majorVersion >= 2 ? SecurityLevel::TRUSTED_ENVIRONMENT : SecurityLevel::SOFTWARE;
 
-    keystore::KeyStore keyStore(&entropy, kmDevices, minimalAllowedSecurityLevelForNewKeys);
+    keystore::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/permissions.cpp b/keystore/permissions.cpp
index 1ba91d9..b297c59 100644
--- a/keystore/permissions.cpp
+++ b/keystore/permissions.cpp
@@ -68,7 +68,14 @@
     {AID_SYSTEM, static_cast<perm_t>((uint32_t)(~0))},
     {AID_VPN, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY)},
     {AID_WIFI, static_cast<perm_t>(P_GET | P_SIGN | P_VERIFY)},
+    {AID_BLUETOOTH, static_cast<perm_t>(P_GET | P_INSERT | P_DELETE | P_EXIST | P_SIGN | P_VERIFY)},
+
+#ifdef GRANT_ROOT_ALL_PERMISSIONS
+    // Allow VTS tests running as root to perform all operations
+    {AID_ROOT, static_cast<perm_t>((uint32_t)(~0))},
+#else
     {AID_ROOT, static_cast<perm_t>(P_GET)},
+#endif
 };
 
 static const perm_t DEFAULT_PERMS = static_cast<perm_t>(
diff --git a/keystore/user_state.cpp b/keystore/user_state.cpp
index 5f9cd5f..aab6175 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 <cutils/log.h>
 
@@ -66,7 +68,7 @@
 }
 
 void UserState::zeroizeMasterKeysInMemory() {
-    memset(mMasterKey, 0, sizeof(mMasterKey));
+    memset(mMasterKey.data(), 0, mMasterKey.size());
     memset(mSalt, 0, sizeof(mSalt));
 }
 
@@ -76,11 +78,11 @@
     return unlink(mMasterKeyFile) == 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;
     }
@@ -95,7 +97,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);
 }
@@ -130,14 +132,15 @@
     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);
-    return masterKeyBlob.writeBlob(mMasterKeyFile, passwordKey, STATE_NO_ERROR, entropy);
+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);
+    return masterKeyBlob.writeBlob(mMasterKeyFile, passwordKey, STATE_NO_ERROR);
 }
 
-ResponseCode UserState::readMasterKey(const android::String8& pw, Entropy* entropy) {
+ResponseCode UserState::readMasterKey(const android::String8& pw) {
     int in = TEMP_FAILURE_RETRY(open(mMasterKeyFile, O_RDONLY));
     if (in < 0) {
         return ResponseCode::SYSTEM_ERROR;
@@ -157,23 +160,33 @@
     } else {
         salt = NULL;
     }
-    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(rawBlob);
     ResponseCode response = masterKeyBlob.readBlob(mMasterKeyFile, passwordKey, STATE_NO_ERROR);
     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 == NULL) {
-            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;
@@ -221,7 +234,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 != NULL) {
@@ -233,19 +246,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 c28f7b8..c4f3cd4 100644
--- a/keystore/user_state.h
+++ b/keystore/user_state.h
@@ -24,8 +24,7 @@
 #include <utils/String8.h>
 
 #include <keystore/keystore.h>
-
-#include "entropy.h"
+#include <vector>
 
 class UserState {
   public:
@@ -47,28 +46,31 @@
     void zeroizeMasterKeysInMemory();
     bool deleteMasterKey();
 
-    ResponseCode initialize(const android::String8& pw, Entropy* entropy);
+    ResponseCode initialize(const android::String8& pw);
 
     ResponseCode copyMasterKey(UserState* src);
     ResponseCode copyMasterKeyFile(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);
 
-    auto& getEncryptionKey() const { return mMasterKey; }
+    const std::vector<uint8_t>& getEncryptionKey() const { return mMasterKey; }
 
     bool reset();
 
   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();
 
     uid_t mUserId;
@@ -79,7 +81,7 @@
     State mState;
     int8_t mRetry;
 
-    uint8_t mMasterKey[MASTER_KEY_SIZE_BYTES];
+    std::vector<uint8_t> mMasterKey;
     uint8_t mSalt[SALT_SIZE];
 };