Add support for metadata encryption

Support encrypting metadata in /userdata using the dm-default-key
driver with a key in the /metadata partition.

Bug: 29189559
Test: Angler & Marlin build and boot
Change-Id: I716b117508d4bb4f6a4039293acb848cbc60f67b
diff --git a/KeyUtil.cpp b/KeyUtil.cpp
index 37398e6..4d507a1 100644
--- a/KeyUtil.cpp
+++ b/KeyUtil.cpp
@@ -74,7 +74,7 @@
     return true;
 }
 
-static std::string keyname(const std::string& raw_ref) {
+std::string keyname(const std::string& raw_ref) {
     std::ostringstream o;
     o << "ext4:";
     for (auto i : raw_ref) {
@@ -163,5 +163,23 @@
     return true;
 }
 
+bool retrieveKey(bool create_if_absent, const std::string& key_path,
+                 const std::string& tmp_path, std::string* key) {
+    if (pathExists(key_path)) {
+        LOG(DEBUG) << "Key exists, using: " << key_path;
+        if (!retrieveKey(key_path, kEmptyAuthentication, key)) return false;
+    } else {
+        if (!create_if_absent) {
+           LOG(ERROR) << "No key found in " << key_path;
+           return false;
+        }
+        LOG(INFO) << "Creating new key in " << key_path;
+        if (!randomKey(key)) return false;
+        if (!storeKeyAtomically(key_path, tmp_path,
+                kEmptyAuthentication, *key)) return false;
+    }
+    return true;
+}
+
 }  // namespace vold
 }  // namespace android