Refactor key generation to handle both normal and metadata encryption.

Bug: 147733587
Test: Treehugger
Change-Id: Iee176037dec2621c84da325c2627f988fcebbc8d
Merged-In: Iee176037dec2621c84da325c2627f988fcebbc8d
diff --git a/KeyUtil.h b/KeyUtil.h
index 878b4ab..16aaf99 100644
--- a/KeyUtil.h
+++ b/KeyUtil.h
@@ -17,6 +17,7 @@
 #ifndef ANDROID_VOLD_KEYUTIL_H
 #define ANDROID_VOLD_KEYUTIL_H
 
+#include "CryptoType.h"
 #include "KeyBuffer.h"
 #include "KeyStorage.h"
 
@@ -30,9 +31,26 @@
 
 using namespace android::fscrypt;
 
-bool randomKey(KeyBuffer* key);
+// Description of how to generate a key when needed.
+struct KeyGeneration {
+    size_t keysize;
+    bool allow_gen;
+    bool use_hw_wrapped_key;
+};
 
-bool generateStorageKey(const EncryptionOptions& options, KeyBuffer* key);
+// Generate a key as specified in KeyGeneration
+bool generateStorageKey(const KeyGeneration& gen, KeyBuffer* key);
+
+// Returns KeyGeneration suitable for key as described in EncryptionOptions
+const KeyGeneration makeGen(const EncryptionOptions& options);
+
+// Returns KeyGeneration suitable for key as described in CryptoType
+const KeyGeneration makeGen(const CryptoType& crypto);
+
+// Returns a key with allow_gen false so generateStorageKey returns false;
+// this is used to indicate to retrieveOrGenerateKey that a key should not
+// be generated.
+const KeyGeneration neverGen();
 
 bool isFsKeyringSupported(void);
 
@@ -58,9 +76,9 @@
 // In the latter case, the caller is responsible for dropping caches.
 bool evictKey(const std::string& mountpoint, const EncryptionPolicy& policy);
 
-bool retrieveKey(bool create_if_absent, const KeyAuthentication& key_authentication,
-                 const std::string& key_path, const std::string& tmp_path,
-                 const EncryptionOptions& options, KeyBuffer* key, bool keepOld = true);
+bool retrieveOrGenerateKey(const std::string& key_path, const std::string& tmp_path,
+                           const KeyAuthentication& key_authentication, const KeyGeneration& gen,
+                           KeyBuffer* key, bool keepOld = true);
 
 }  // namespace vold
 }  // namespace android