Use SHA256 for 32 byte keys

For NIAP certification keys need to be generated using SHA256 or
higher. Presently SHA1 is used. To satisfy this requirement,
SHA256 will be used for new keys. As the master key has recently
increased in size, the key size is used to determine if SHA1 is used
(for older keys) or SHA256.

Bug: 121272336
Test: Ran Keystore CTS tests against Walleye,
      no new test failures observed
Change-Id: Ic5f7840e60817d02b62dca7221f5cc703558db44
Merged-In: I6099156173e04b22c6edafd9fb0e072f7201c5ee
diff --git a/keystore/user_state.cpp b/keystore/user_state.cpp
index b62598d..ff0ea10 100644
--- a/keystore/user_state.cpp
+++ b/keystore/user_state.cpp
@@ -24,6 +24,7 @@
 #include <stdlib.h>
 #include <sys/stat.h>
 
+#include <openssl/digest.h>
 #include <openssl/evp.h>
 #include <openssl/rand.h>
 
@@ -234,8 +235,15 @@
         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 (keySize == SHA1_DIGEST_SIZE_BYTES) {
+        digest = EVP_sha1();
+    }
+
+    PKCS5_PBKDF2_HMAC(reinterpret_cast<const char*>(pw.string()), pw.length(), salt, saltSize, 8192,
+                      digest, keySize, key);
 }
 
 bool UserState::generateSalt() {
diff --git a/keystore/user_state.h b/keystore/user_state.h
index e1d48bd..fcfc895 100644
--- a/keystore/user_state.h
+++ b/keystore/user_state.h
@@ -58,7 +58,10 @@
     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 = SHA1_DIGEST_SIZE_BYTES;
     static const int MASTER_KEY_SIZE_BITS = MASTER_KEY_SIZE_BYTES * 8;
 
     static const int MAX_RETRY = 4;