Move key name creation to common path

Bug: 10676015
Change-Id: I781e142217959a8a068844b9cb041282b8ae2a74
diff --git a/keystore/keystore.cpp b/keystore/keystore.cpp
index c890537..336a15b 100644
--- a/keystore/keystore.cpp
+++ b/keystore/keystore.cpp
@@ -272,13 +272,6 @@
     return length;
 }
 
-static int encode_key_for_uid(char* out, uid_t uid, const android::String8& keyName) {
-    int n = snprintf(out, NAME_MAX, "%u_", uid);
-    out += n;
-
-    return n + encode_key(out, keyName);
-}
-
 /*
  * Converts from the "escaped" format on disk to actual name.
  * This will be smaller than the input string.
@@ -1128,17 +1121,7 @@
 
     ResponseCode getKeyForName(Blob* keyBlob, const android::String8& keyName, const uid_t uid,
             const BlobType type) {
-        char filename[NAME_MAX];
-        encode_key_for_uid(filename, uid, keyName);
-
-        UserState* userState = getUserState(uid);
-        android::String8 filepath8;
-
-        filepath8 = android::String8::format("%s/%s", userState->getUserDirName(), filename);
-        if (filepath8.string() == NULL) {
-            ALOGW("can't create filepath for key %s", filename);
-            return SYSTEM_ERROR;
-        }
+        android::String8 filepath8(getKeyNameForUidWithDir(keyName, uid));
 
         ResponseCode responseCode = get(filepath8.string(), keyBlob, type, uid);
         if (responseCode == NO_ERROR) {
@@ -1148,8 +1131,7 @@
         // If this is one of the legacy UID->UID mappings, use it.
         uid_t euid = get_keystore_euid(uid);
         if (euid != uid) {
-            encode_key_for_uid(filename, euid, keyName);
-            filepath8 = android::String8::format("%s/%s", userState->getUserDirName(), filename);
+            filepath8 = getKeyNameForUidWithDir(keyName, euid);
             responseCode = get(filepath8.string(), keyBlob, type, uid);
             if (responseCode == NO_ERROR) {
                 return responseCode;
@@ -1157,13 +1139,14 @@
         }
 
         // They might be using a granted key.
-        encode_key(filename, keyName);
+        android::String8 filename8 = getKeyName(keyName);
         char* end;
-        strtoul(filename, &end, 10);
+        strtoul(filename8.string(), &end, 10);
         if (end[0] != '_' || end[1] == 0) {
             return KEY_NOT_FOUND;
         }
-        filepath8 = android::String8::format("%s/%s", userState->getUserDirName(), filename);
+        filepath8 = android::String8::format("%s/%s", getUserState(uid)->getUserDirName(),
+                filename8.string());
         if (!hasGrant(filepath8.string(), uid)) {
             return responseCode;
         }