Add support for multi-user decryption

* Add CLI support using the command "twrp decrypt <PASSWORD> [USER ID]"
* Add GUI support using the menu Advanced --> Decrypt User

Change-Id: Id2681bc2b1012a0571417f7a6e0b980b1b25c61c
(cherry picked from commit 5a79f67a1b1bd1bcadeca0a4896a871646652534)
diff --git a/crypto/ext4crypt/Decrypt.cpp b/crypto/ext4crypt/Decrypt.cpp
index dcd390f..fe27017 100755
--- a/crypto/ext4crypt/Decrypt.cpp
+++ b/crypto/ext4crypt/Decrypt.cpp
@@ -549,13 +549,16 @@
 	std::string disk_decryption_secret_key = "";
 
 	std::string keystore_alias_subid;
-	if (!Find_Keystore_Alias_SubID_And_Prep_Files(user_id, keystore_alias_subid, handle_str)) {
-		printf("failed to scan keystore alias subid and prep keystore files\n");
-		return disk_decryption_secret_key;
-	}
+	// Can be stored in user 0, so check for both.
+	if (!Find_Keystore_Alias_SubID_And_Prep_Files(user_id, keystore_alias_subid, handle_str) &&
+		!Find_Keystore_Alias_SubID_And_Prep_Files(0, keystore_alias_subid, handle_str)) 
+	{
+    	printf("failed to scan keystore alias subid and prep keystore files\n");
+    	return disk_decryption_secret_key;
+  	}
 
 	// First get the keystore service
-    sp<IBinder> binder = getKeystoreBinderRetry();
+	sp<IBinder> binder = getKeystoreBinderRetry();
 #ifdef USE_KEYSTORAGE_4
 	sp<IKeystoreService> service = interface_cast<IKeystoreService>(binder);
 #else
@@ -1165,15 +1168,15 @@
 		printf("e4crypt_unlock_user_key returned fail\n");
 		return Free_Return(retval, weaver_key, &pwd);
 	}
-#ifdef USE_KEYSTORAGE_4
+/*#ifdef USE_KEYSTORAGE_4
 	if (!e4crypt_prepare_user_storage("", user_id, 0, flags)) {
 #else
 	if (!e4crypt_prepare_user_storage(nullptr, user_id, 0, flags)) {
 #endif
 		printf("failed to e4crypt_prepare_user_storage\n");
 		return Free_Return(retval, weaver_key, &pwd);
-	}
-	printf("Decrypted Successfully!\n");
+	}*/
+	printf("User %i Decrypted Successfully!\n", user_id);
 	retval = true;
 	return Free_Return(retval, weaver_key, &pwd);
 }
@@ -1255,15 +1258,15 @@
 			printf("e4crypt_unlock_user_key returned fail\n");
 			return false;
 		}
-#ifdef USE_KEYSTORAGE_4
+/*#ifdef USE_KEYSTORAGE_4
 		if (!e4crypt_prepare_user_storage("", user_id, 0, flags)) {
 #else
 		if (!e4crypt_prepare_user_storage(nullptr, user_id, 0, flags)) {
 #endif
 			printf("failed to e4crypt_prepare_user_storage\n");
 			return false;
-		}
-		printf("Decrypted Successfully!\n");
+		}*/
+		printf("User %i Decrypted Successfully!\n", user_id);
 		return true;
 	}
 	if (stat("/data/system_de/0/spblob", &st) == 0) {
@@ -1343,14 +1346,14 @@
 		printf("e4crypt_unlock_user_key returned fail\n");
 		return false;
 	}
-#ifdef USE_KEYSTORAGE_4
+/*#ifdef USE_KEYSTORAGE_4
 		if (!e4crypt_prepare_user_storage("", user_id, 0, flags)) {
 #else
 		if (!e4crypt_prepare_user_storage(nullptr, user_id, 0, flags)) {
 #endif
 		printf("failed to e4crypt_prepare_user_storage\n");
 		return false;
-	}
-	printf("Decrypted Successfully!\n");
+	}*/
+	printf("User %i Decrypted Successfully!\n", user_id);
 	return true;
 }
diff --git a/crypto/ext4crypt/Ext4Crypt.cpp b/crypto/ext4crypt/Ext4Crypt.cpp
index c9e71fd..9360b1a 100644
--- a/crypto/ext4crypt/Ext4Crypt.cpp
+++ b/crypto/ext4crypt/Ext4Crypt.cpp
@@ -63,6 +63,7 @@
 #define MANAGE_MISC_DIRS 0
 
 #include <cutils/fs.h>
+#include <cutils/properties.h>
 
 #include <android-base/file.h>
 //#include <android-base/logging.h>
@@ -316,16 +317,6 @@
     return true;
 }
 
-static bool ensure_policy(const std::string& raw_ref __unused, const std::string& path) {
-    return true;
-    // ensure policy will set a policy if one is not set on an empty folder - we don't want to do this in recovery
-    /*if (e4crypt_policy_ensure(path.c_str(), raw_ref.data(), raw_ref.size()) != 0) {
-        LOG(ERROR) << "Failed to set policy on: " << path << "\n";
-        return false;
-    }
-    return true;*/
-}
-
 static bool is_numeric(const char* name) {
     for (const char* p = name; *p != '\0'; p++) {
         if (!isdigit(*p)) return false;
@@ -363,6 +354,9 @@
             if (!install_key(key, &raw_ref)) return false;
             s_de_key_raw_refs[user_id] = raw_ref;
             LOG(DEBUG) << "Installed de key for user " << user_id;
+
+            std::string user_prop = "twrp.user." + std::to_string(user_id) + ".decrypt";
+            property_set(user_prop.c_str(), "0");
         }
     }
     // ext4enc:TODO: go through all DE directories, ensure that all user dirs have the
@@ -411,13 +405,6 @@
         // explicit calls to install DE keys for secondary users
         if (!load_all_de_keys()) return false;
     }
-    // We can only safely prepare DE storage here, since CE keys are probably
-    // entangled with user credentials.  The framework will always prepare CE
-    // storage once CE keys are installed.
-    if (!e4crypt_prepare_user_storage(nullptr, 0, 0, FLAG_STORAGE_DE)) {
-        LOG(ERROR) << "Failed to prepare user 0 storage";
-        return false;
-    }
 
     // If this is a non-FBE device that recently left an emulated mode,
     // restore user data directories to known-good state.
@@ -458,79 +445,6 @@
         }
     } else {
 		printf("Emulation mode not supported in TWRP\n");
-        // When in emulation mode, we just use chmod. However, we also
-        // unlock directories when not in emulation mode, to bring devices
-        // back into a known-good state.
-        /*if (!emulated_unlock(android::vold::BuildDataSystemCePath(user_id), 0771) ||
-            !emulated_unlock(android::vold::BuildDataMiscCePath(user_id), 01771) ||
-            !emulated_unlock(android::vold::BuildDataMediaCePath(nullptr, user_id), 0770) ||
-            !emulated_unlock(android::vold::BuildDataUserCePath(nullptr, user_id), 0771)) {
-            LOG(ERROR) << "Failed to unlock user " << user_id;
-            return false;
-        }*/
     }
     return true;
 }
-
-bool e4crypt_prepare_user_storage(const char* volume_uuid, userid_t user_id, int serial __unused,
-        int flags) {
-
-    if (flags & FLAG_STORAGE_DE) {
-        // DE_sys key
-        auto system_legacy_path = android::vold::BuildDataSystemLegacyPath(user_id);
-        auto misc_legacy_path = android::vold::BuildDataMiscLegacyPath(user_id);
-        auto profiles_de_path = android::vold::BuildDataProfilesDePath(user_id);
-        auto foreign_de_path = android::vold::BuildDataProfilesForeignDexDePath(user_id);
-
-        // DE_n key
-        auto system_de_path = android::vold::BuildDataSystemDePath(user_id);
-        auto misc_de_path = android::vold::BuildDataMiscDePath(user_id);
-        auto user_de_path = android::vold::BuildDataUserDePath(volume_uuid, user_id);
-
-        if (!prepare_dir(system_legacy_path, 0700, AID_SYSTEM, AID_SYSTEM)) return false;
-#if MANAGE_MISC_DIRS
-        if (!prepare_dir(misc_legacy_path, 0750, multiuser_get_uid(user_id, AID_SYSTEM),
-                multiuser_get_uid(user_id, AID_EVERYBODY))) return false;
-#endif
-        if (!prepare_dir(profiles_de_path, 0771, AID_SYSTEM, AID_SYSTEM)) return false;
-        if (!prepare_dir(foreign_de_path, 0773, AID_SYSTEM, AID_SYSTEM)) return false;
-
-        if (!prepare_dir(system_de_path, 0770, AID_SYSTEM, AID_SYSTEM)) return false;
-        if (!prepare_dir(misc_de_path, 01771, AID_SYSTEM, AID_MISC)) return false;
-        if (!prepare_dir(user_de_path, 0771, AID_SYSTEM, AID_SYSTEM)) return false;
-
-        // For now, FBE is only supported on internal storage
-        if (e4crypt_is_native() && volume_uuid == nullptr) {
-            std::string de_raw_ref;
-            if (!lookup_key_ref(s_de_key_raw_refs, user_id, &de_raw_ref)) return false;
-            if (!ensure_policy(de_raw_ref, system_de_path)) return false;
-            if (!ensure_policy(de_raw_ref, misc_de_path)) return false;
-            if (!ensure_policy(de_raw_ref, user_de_path)) return false;
-        }
-    }
-
-    if (flags & FLAG_STORAGE_CE) {
-        // CE_n key
-        auto system_ce_path = android::vold::BuildDataSystemCePath(user_id);
-        auto misc_ce_path = android::vold::BuildDataMiscCePath(user_id);
-        auto media_ce_path = android::vold::BuildDataMediaCePath(volume_uuid, user_id);
-        auto user_ce_path = android::vold::BuildDataUserCePath(volume_uuid, user_id);
-
-        if (!prepare_dir(system_ce_path, 0770, AID_SYSTEM, AID_SYSTEM)) return false;
-        if (!prepare_dir(misc_ce_path, 01771, AID_SYSTEM, AID_MISC)) return false;
-        if (!prepare_dir(media_ce_path, 0770, AID_MEDIA_RW, AID_MEDIA_RW)) return false;
-        if (!prepare_dir(user_ce_path, 0771, AID_SYSTEM, AID_SYSTEM)) return false;
-
-        // For now, FBE is only supported on internal storage
-        if (e4crypt_is_native() && volume_uuid == nullptr) {
-            std::string ce_raw_ref;
-            if (!lookup_key_ref(s_ce_key_raw_refs, user_id, &ce_raw_ref)) return false;
-            if (!ensure_policy(ce_raw_ref, system_ce_path)) return false;
-            if (!ensure_policy(ce_raw_ref, misc_ce_path)) return false;
-            if (!ensure_policy(ce_raw_ref, media_ce_path)) return false;
-            if (!ensure_policy(ce_raw_ref, user_ce_path)) return false;
-        }
-    }
-
-    return true;
-}
diff --git a/crypto/ext4crypt/Ext4Crypt.h b/crypto/ext4crypt/Ext4Crypt.h
index 57623e3..beb5d8f 100644
--- a/crypto/ext4crypt/Ext4Crypt.h
+++ b/crypto/ext4crypt/Ext4Crypt.h
@@ -38,7 +38,7 @@
 bool e4crypt_unlock_user_key(userid_t user_id, int serial, const char* token, const char* secret);
 //bool e4crypt_lock_user_key(userid_t user_id);
 
-bool e4crypt_prepare_user_storage(const char* volume_uuid, userid_t user_id, int serial, int flags);
+//bool e4crypt_prepare_user_storage(const char* volume_uuid, userid_t user_id, int serial, int flags);
 //bool e4crypt_destroy_user_storage(const char* volume_uuid, userid_t user_id, int flags);
 
 bool lookup_key_ref(const std::map<userid_t, std::string>& key_map, userid_t user_id,
diff --git a/crypto/ext4crypt/Ext4CryptPie.cpp b/crypto/ext4crypt/Ext4CryptPie.cpp
index 548e4e4..48b4ec9 100644
--- a/crypto/ext4crypt/Ext4CryptPie.cpp
+++ b/crypto/ext4crypt/Ext4CryptPie.cpp
@@ -110,9 +110,9 @@
     return property_get_bool("persist.sys.emulate_fbe", false);
 }
 
-static const char* escape_empty(const std::string& value) {
+/*static const char* escape_empty(const std::string& value) {
     return value.empty() ? "null" : value.c_str();
-}
+}*/
 
 static std::string get_de_key_path(userid_t user_id) {
     return StringPrintf("%s/de/%d", user_key_dir.c_str(), user_id);
@@ -155,23 +155,6 @@
     return directory_path + "/current";
 }
 
-/*static bool get_ce_key_new_path(const std::string& directory_path,
-                                const std::vector<std::string>& paths,
-                                std::string *ce_key_path) {
-    if (paths.empty()) {
-        *ce_key_path = get_ce_key_current_path(directory_path);
-        return true;
-    }
-    for (unsigned int i = 0; i < UINT_MAX; i++) {
-        auto const candidate = StringPrintf("%s/cx%010u", directory_path.c_str(), i);
-        if (paths[0] < candidate) {
-            *ce_key_path = candidate;
-            return true;
-        }
-    }
-    return false;
-}*/
-
 // Discard all keys but the named one; rename it to canonical name.
 // No point in acting on errors in this; ignore them.
 static void fixate_user_ce_key(const std::string& directory_path, const std::string &to_fix,
@@ -259,15 +242,6 @@
     return true;
 }
 
-/*static bool destroy_dir(const std::string& dir) {
-    LOG(DEBUG) << "Destroying: " << dir;
-    if (rmdir(dir.c_str()) != 0 && errno != ENOENT) {
-        PLOG(ERROR) << "Failed to destroy " << dir;
-        return false;
-    }
-    return true;
-}*/
-
 // NB this assumes that there is only one thread listening for crypt commands, because
 // it creates keys in a fixed location.
 static bool create_and_install_user_keys(userid_t user_id, bool create_ephemeral) {
@@ -327,13 +301,6 @@
         android::base::GetProperty("fbe.filenames", "aes-256-heh");
 }
 
-static bool ensure_policy(const PolicyKeyRef& key_ref, const std::string& path) {
-    return true;
-    /*return e4crypt_policy_ensure(path.c_str(), key_ref.key_raw_ref.data(),
-                                 key_ref.key_raw_ref.size(), key_ref.contents_mode.c_str(),
-                                 key_ref.filenames_mode.c_str()) == 0;*/
-}
-
 static bool is_numeric(const char* name) {
     for (const char* p = name; *p != '\0'; p++) {
         if (!isdigit(*p)) return false;
@@ -379,6 +346,9 @@
             if (!android::vold::installKey(key, &raw_ref)) return false;
             s_de_key_raw_refs[user_id] = raw_ref;
             LOG(DEBUG) << "Installed de key for user " << user_id << std::endl;
+
+            std::string user_prop = "twrp.user." + std::to_string(user_id) + ".decrypt";
+            property_set(user_prop.c_str(), "0");
         }
     }
     // ext4enc:TODO: go through all DE directories, ensure that all user dirs have the
@@ -435,13 +405,6 @@
         // explicit calls to install DE keys for secondary users
         if (!load_all_de_keys()) return false;
     }
-    // We can only safely prepare DE storage here, since CE keys are probably
-    // entangled with user credentials.  The framework will always prepare CE
-    // storage once CE keys are installed.
-    if (!e4crypt_prepare_user_storage("", 0, 0, /*android::os::IVold::*/STORAGE_FLAG_DE)) {
-        LOG(ERROR) << "Failed to prepare user 0 storage" << std::endl;
-        return false;
-    }
 
     // If this is a non-FBE device that recently left an emulated mode,
     // restore user data directories to known-good state.
@@ -452,92 +415,6 @@
     return true;
 }
 
-/*bool e4crypt_vold_create_user_key(userid_t user_id, int serial, bool ephemeral) {
-    LOG(DEBUG) << "TWRP NOT e4crypt_vold_create_user_key for " << user_id << " serial " << serial;
-    return true;
-    if (!e4crypt_is_native()) {
-        return true;
-    }
-    // FIXME test for existence of key that is not loaded yet
-    if (s_ce_key_raw_refs.count(user_id) != 0) {
-        LOG(ERROR) << "Already exists, can't e4crypt_vold_create_user_key for " << user_id
-                   << " serial " << serial;
-        // FIXME should we fail the command?
-        return true;
-    }
-    if (!create_and_install_user_keys(user_id, ephemeral)) {
-        return false;
-    }
-    return true;
-}
-
-static void drop_caches() {
-    // Clean any dirty pages (otherwise they won't be dropped).
-    sync();
-    // Drop inode and page caches.
-    if (!WriteStringToFile("3", "/proc/sys/vm/drop_caches")) {
-        PLOG(ERROR) << "Failed to drop caches during key eviction";
-    }
-}
-
-static bool evict_ce_key(userid_t user_id) {
-	LOG(ERROR) << "TWRP NOT evict_ce_key\n";
-	return true;
-    s_ce_keys.erase(user_id);
-    bool success = true;
-    std::string raw_ref;
-    // If we haven't loaded the CE key, no need to evict it.
-    if (lookup_key_ref(s_ce_key_raw_refs, user_id, &raw_ref)) {
-        success &= android::vold::evictKey(raw_ref);
-        drop_caches();
-    }
-    s_ce_key_raw_refs.erase(user_id);
-    return success;
-}
-
-bool e4crypt_destroy_user_key(userid_t user_id) {
-    LOG(DEBUG) << "NOT e4crypt_destroy_user_key(" << user_id << ")";
-    return true;
-    if (!e4crypt_is_native()) {
-        return true;
-    }
-    bool success = true;
-    std::string raw_ref;
-    success &= evict_ce_key(user_id);
-    success &= lookup_key_ref(s_de_key_raw_refs, user_id, &raw_ref)
-        && android::vold::evictKey(raw_ref);
-    s_de_key_raw_refs.erase(user_id);
-    auto it = s_ephemeral_users.find(user_id);
-    if (it != s_ephemeral_users.end()) {
-        s_ephemeral_users.erase(it);
-    } else {
-        for (auto const path: get_ce_key_paths(get_ce_key_directory_path(user_id))) {
-            success &= android::vold::destroyKey(path);
-        }
-        auto de_key_path = get_de_key_path(user_id);
-        if (android::vold::pathExists(de_key_path)) {
-            success &= android::vold::destroyKey(de_key_path);
-        } else {
-            LOG(INFO) << "Not present so not erasing: " << de_key_path;
-        }
-    }
-    return success;
-}
-
-static bool emulated_lock(const std::string& path) {
-    if (chmod(path.c_str(), 0000) != 0) {
-        PLOG(ERROR) << "Failed to chmod " << path;
-        return false;
-    }
-#if EMULATED_USES_SELINUX
-    if (setfilecon(path.c_str(), "u:object_r:storage_stub_file:s0") != 0) {
-        PLOG(WARNING) << "Failed to setfilecon " << path;
-        return false;
-    }
-#endif
-    return true;
-}*/
-
 static bool emulated_unlock(const std::string& path, mode_t mode) {
     if (chmod(path.c_str(), mode) != 0) {
         PLOG(ERROR) << "Failed to chmod " << path << std::endl;
@@ -566,92 +443,6 @@
     return true;
 }
 
-static std::string volkey_path(const std::string& misc_path, const std::string& volume_uuid) {
-    return misc_path + "/vold/volume_keys/" + volume_uuid + "/default";
-}
-
-static std::string volume_secdiscardable_path(const std::string& volume_uuid) {
-    return systemwide_volume_key_dir + "/" + volume_uuid + "/secdiscardable";
-}
-
-static bool read_or_create_volkey(const std::string& misc_path, const std::string& volume_uuid,
-                                  PolicyKeyRef* key_ref) {
-    auto secdiscardable_path = volume_secdiscardable_path(volume_uuid);
-    std::string secdiscardable_hash;
-    bool wrapped_key_supported = false;
-    if (android::vold::pathExists(secdiscardable_path)) {
-        if (!android::vold::readSecdiscardable(secdiscardable_path, &secdiscardable_hash))
-            return false;
-    } else {
-        if (fs_mkdirs(secdiscardable_path.c_str(), 0700) != 0) {
-            PLOG(ERROR) << "Creating directories for: " << secdiscardable_path << std::endl;
-            return false;
-        }
-        if (!android::vold::createSecdiscardable(secdiscardable_path, &secdiscardable_hash))
-            return false;
-    }
-    auto key_path = volkey_path(misc_path, volume_uuid);
-    if (fs_mkdirs(key_path.c_str(), 0700) != 0) {
-        PLOG(ERROR) << "Creating directories for: " << key_path << std::endl;
-        return false;
-    }
-    android::vold::KeyAuthentication auth("", secdiscardable_hash);
-    wrapped_key_supported = is_wrapped_key_supported_external();
-    if (!android::vold::retrieveAndInstallKey(true, auth, key_path, key_path + "_tmp",
-                                              &key_ref->key_raw_ref, wrapped_key_supported))
-        return false;
-    key_ref->contents_mode =
-        android::base::GetProperty("ro.crypto.volume.contents_mode", "aes-256-xts");
-    key_ref->filenames_mode =
-        android::base::GetProperty("ro.crypto.volume.filenames_mode", "aes-256-heh");
-    return true;
-}
-
-/*static bool destroy_volkey(const std::string& misc_path, const std::string& volume_uuid) {
-    auto path = volkey_path(misc_path, volume_uuid);
-    if (!android::vold::pathExists(path)) return true;
-    return android::vold::destroyKey(path);
-}
-
-bool e4crypt_add_user_key_auth(userid_t user_id, int serial, const std::string& token_hex,
-                               const std::string& secret_hex) {
-    LOG(DEBUG) << "e4crypt_add_user_key_auth " << user_id << " serial=" << serial
-               << " token_present=" << (token_hex != "!");
-    if (!e4crypt_is_native()) return true;
-    if (s_ephemeral_users.count(user_id) != 0) return true;
-    std::string token, secret;
-    if (!parse_hex(token_hex, &token)) return false;
-    if (!parse_hex(secret_hex, &secret)) return false;
-    auto auth = secret.empty() ? kEmptyAuthentication
-                                   : android::vold::KeyAuthentication(token, secret);
-    auto it = s_ce_keys.find(user_id);
-    if (it == s_ce_keys.end()) {
-        LOG(ERROR) << "Key not loaded into memory, can't change for user " << user_id;
-        return false;
-    }
-    const auto &ce_key = it->second;
-    auto const directory_path = get_ce_key_directory_path(user_id);
-    auto const paths = get_ce_key_paths(directory_path);
-    std::string ce_key_path;
-    if (!get_ce_key_new_path(directory_path, paths, &ce_key_path)) return false;
-    if (!android::vold::storeKeyAtomically(ce_key_path, user_key_temp, auth, ce_key)) return false;
-    return true;
-}
-
-bool e4crypt_fixate_newest_user_key_auth(userid_t user_id) {
-    LOG(DEBUG) << "e4crypt_fixate_newest_user_key_auth " << user_id;
-    if (!e4crypt_is_native()) return true;
-    if (s_ephemeral_users.count(user_id) != 0) return true;
-    auto const directory_path = get_ce_key_directory_path(user_id);
-    auto const paths = get_ce_key_paths(directory_path);
-    if (paths.empty()) {
-        LOG(ERROR) << "No ce keys present, cannot fixate for user " << user_id;
-        return false;
-    }
-    fixate_user_ce_key(directory_path, paths[0], paths);
-    return true;
-}*/
-
 // TODO: rename to 'install' for consistency, and take flags to know which keys to install
 bool e4crypt_unlock_user_key(userid_t user_id, int serial, const std::string& token_hex,
                              const std::string& secret_hex) {
@@ -684,224 +475,3 @@
     }
     return true;
 }
-
-// TODO: rename to 'evict' for consistency
-/*bool e4crypt_lock_user_key(userid_t user_id) {
-    LOG(DEBUG) << "TWRP NOTe4crypt_lock_user_key " << user_id;
-    return true;
-    if (e4crypt_is_native()) {
-        return evict_ce_key(user_id);
-    } else if (e4crypt_is_emulated()) {
-        // When in emulation mode, we just use chmod
-        if (!emulated_lock(android::vold::BuildDataSystemCePath(user_id)) ||
-            !emulated_lock(android::vold::BuildDataMiscCePath(user_id)) ||
-            !emulated_lock(android::vold::BuildDataMediaCePath("", user_id)) ||
-            !emulated_lock(android::vold::BuildDataUserCePath("", user_id))) {
-            LOG(ERROR) << "Failed to lock user " << user_id;
-            return false;
-        }
-    }
-
-    return true;
-}*/
-
-static bool prepare_subdirs(const std::string& action, const std::string& volume_uuid,
-                            userid_t user_id, int flags) {
-    LOG(ERROR) << "not actually forking for vold_prepare_subdirs\n";
-    return true;
-    /*if (0 != android::vold::ForkExecvp(
-                 std::vector<std::string>{prepare_subdirs_path, action, volume_uuid,
-                                          std::to_string(user_id), std::to_string(flags)})) {
-        LOG(ERROR) << "vold_prepare_subdirs failed";
-        return false;
-    }
-    return true;*/
-}
-
-bool e4crypt_prepare_user_storage(const std::string& volume_uuid, userid_t user_id, int serial,
-                                  int flags) {
-    LOG(DEBUG) << "e4crypt_prepare_user_storage for volume " << escape_empty(volume_uuid)
-               << ", user " << user_id << ", serial " << serial << ", flags " << flags << std::endl;
-
-    if (flags & /*android::os::IVold::*/STORAGE_FLAG_DE) {
-        // DE_sys key
-        auto system_legacy_path = android::vold::BuildDataSystemLegacyPath(user_id);
-        auto misc_legacy_path = android::vold::BuildDataMiscLegacyPath(user_id);
-        auto profiles_de_path = android::vold::BuildDataProfilesDePath(user_id);
-
-        // DE_n key
-        auto system_de_path = android::vold::BuildDataSystemDePath(user_id);
-        auto misc_de_path = android::vold::BuildDataMiscDePath(user_id);
-        auto vendor_de_path = android::vold::BuildDataVendorDePath(user_id);
-        auto user_de_path = android::vold::BuildDataUserDePath(nullptr, user_id);
-
-        if (volume_uuid.empty()) {
-            if (!prepare_dir(system_legacy_path, 0700, AID_SYSTEM, AID_SYSTEM)) return false;
-#if MANAGE_MISC_DIRS
-            if (!prepare_dir(misc_legacy_path, 0750, multiuser_get_uid(user_id, AID_SYSTEM),
-                    multiuser_get_uid(user_id, AID_EVERYBODY))) return false;
-#endif
-            if (!prepare_dir(profiles_de_path, 0771, AID_SYSTEM, AID_SYSTEM)) return false;
-            if (!prepare_dir(system_de_path, 0770, AID_SYSTEM, AID_SYSTEM)) return false;
-            if (!prepare_dir(misc_de_path, 01771, AID_SYSTEM, AID_MISC)) return false;
-            if (!prepare_dir(vendor_de_path, 0771, AID_ROOT, AID_ROOT)) return false;
-        }
-        if (!prepare_dir(user_de_path, 0771, AID_SYSTEM, AID_SYSTEM)) return false;
-
-        if (e4crypt_is_native()) {
-            PolicyKeyRef de_ref;
-            if (volume_uuid.empty()) {
-                if (!lookup_key_ref(s_de_key_raw_refs, user_id, &de_ref.key_raw_ref)) return false;
-                get_data_file_encryption_modes(&de_ref);
-                if (!ensure_policy(de_ref, system_de_path)) return false;
-                if (!ensure_policy(de_ref, misc_de_path)) return false;
-                if (!ensure_policy(de_ref, vendor_de_path)) return false;
-            } else {
-                if (!read_or_create_volkey(misc_de_path, nullptr, &de_ref)) return false;
-            }
-            if (!ensure_policy(de_ref, user_de_path)) return false;
-        }
-    }
-
-    if (flags & /*android::os::IVold::*/STORAGE_FLAG_CE) {
-        // CE_n key
-        auto system_ce_path = android::vold::BuildDataSystemCePath(user_id);
-        auto misc_ce_path = android::vold::BuildDataMiscCePath(user_id);
-        auto vendor_ce_path = android::vold::BuildDataVendorCePath(user_id);
-        auto media_ce_path = android::vold::BuildDataMediaCePath(nullptr, user_id);
-        auto user_ce_path = android::vold::BuildDataUserCePath(nullptr, user_id);
-
-        if (volume_uuid.empty()) {
-            if (!prepare_dir(system_ce_path, 0770, AID_SYSTEM, AID_SYSTEM)) return false;
-            if (!prepare_dir(misc_ce_path, 01771, AID_SYSTEM, AID_MISC)) return false;
-            if (!prepare_dir(vendor_ce_path, 0771, AID_ROOT, AID_ROOT)) return false;
-        }
-        if (!prepare_dir(media_ce_path, 0770, AID_MEDIA_RW, AID_MEDIA_RW)) return false;
-        if (!prepare_dir(user_ce_path, 0771, AID_SYSTEM, AID_SYSTEM)) return false;
-
-        if (e4crypt_is_native()) {
-            PolicyKeyRef ce_ref;
-            if (volume_uuid.empty()) {
-                if (!lookup_key_ref(s_ce_key_raw_refs, user_id, &ce_ref.key_raw_ref)) return false;
-                get_data_file_encryption_modes(&ce_ref);
-                if (!ensure_policy(ce_ref, system_ce_path)) return false;
-                if (!ensure_policy(ce_ref, misc_ce_path)) return false;
-                if (!ensure_policy(ce_ref, vendor_ce_path)) return false;
-            } else {
-                if (!read_or_create_volkey(misc_ce_path, nullptr, &ce_ref)) return false;
-            }
-            if (!ensure_policy(ce_ref, media_ce_path)) return false;
-            if (!ensure_policy(ce_ref, user_ce_path)) return false;
-        }
-
-        if (volume_uuid.empty()) {
-            // Now that credentials have been installed, we can run restorecon
-            // over these paths
-            // NOTE: these paths need to be kept in sync with libselinux
-            //android::vold::RestoreconRecursive(system_ce_path);
-            //android::vold::RestoreconRecursive(misc_ce_path);
-        }
-    }
-    if (!prepare_subdirs("prepare", volume_uuid, user_id, flags)) return false;
-    return true;
-}
-
-/*bool e4crypt_destroy_user_storage(const std::string& volume_uuid, userid_t user_id, int flags) {
-    LOG(DEBUG) << "TWRP NOT e4crypt_destroy_user_storage for volume " << escape_empty(volume_uuid)
-               << ", user " << user_id << ", flags " << flags;
-    bool res = true;
-    return res;
-
-    res &= prepare_subdirs("destroy", volume_uuid, user_id, flags);
-
-    if (flags & android::os::IVold::STORAGE_FLAG_CE) {
-        // CE_n key
-        auto system_ce_path = android::vold::BuildDataSystemCePath(user_id);
-        auto misc_ce_path = android::vold::BuildDataMiscCePath(user_id);
-        auto vendor_ce_path = android::vold::BuildDataVendorCePath(user_id);
-        auto media_ce_path = android::vold::BuildDataMediaCePath(nullptr, user_id);
-        auto user_ce_path = android::vold::BuildDataUserCePath(nullptr, user_id);
-
-        res &= destroy_dir(media_ce_path);
-        res &= destroy_dir(user_ce_path);
-        if (volume_uuid.empty()) {
-            res &= destroy_dir(system_ce_path);
-            res &= destroy_dir(misc_ce_path);
-            res &= destroy_dir(vendor_ce_path);
-        } else {
-            if (e4crypt_is_native()) {
-                res &= destroy_volkey(misc_ce_path, volume_uuid);
-            }
-        }
-    }
-
-    if (flags & android::os::IVold::STORAGE_FLAG_DE) {
-        // DE_sys key
-        auto system_legacy_path = android::vold::BuildDataSystemLegacyPath(user_id);
-        auto misc_legacy_path = android::vold::BuildDataMiscLegacyPath(user_id);
-        auto profiles_de_path = android::vold::BuildDataProfilesDePath(user_id);
-
-        // DE_n key
-        auto system_de_path = android::vold::BuildDataSystemDePath(user_id);
-        auto misc_de_path = android::vold::BuildDataMiscDePath(user_id);
-        auto vendor_de_path = android::vold::BuildDataVendorDePath(user_id);
-        auto user_de_path = android::vold::BuildDataUserDePath(nullptr, user_id);
-
-        res &= destroy_dir(user_de_path);
-        if (volume_uuid.empty()) {
-            res &= destroy_dir(system_legacy_path);
-#if MANAGE_MISC_DIRS
-            res &= destroy_dir(misc_legacy_path);
-#endif
-            res &= destroy_dir(profiles_de_path);
-            res &= destroy_dir(system_de_path);
-            res &= destroy_dir(misc_de_path);
-            res &= destroy_dir(vendor_de_path);
-        } else {
-            if (e4crypt_is_native()) {
-                res &= destroy_volkey(misc_de_path, volume_uuid);
-            }
-        }
-    }
-
-    return res;
-}
-
-static bool destroy_volume_keys(const std::string& directory_path, const std::string& volume_uuid) {
-	LOG(ERROR) << "TWRP NOT destroy_volume_keys\n";
-	return true;
-    auto dirp = std::unique_ptr<DIR, int (*)(DIR*)>(opendir(directory_path.c_str()), closedir);
-    if (!dirp) {
-        PLOG(ERROR) << "Unable to open directory: " + directory_path;
-        return false;
-    }
-    bool res = true;
-    for (;;) {
-        errno = 0;
-        auto const entry = readdir(dirp.get());
-        if (!entry) {
-            if (errno) {
-                PLOG(ERROR) << "Unable to read directory: " + directory_path;
-                return false;
-            }
-            break;
-        }
-        if (entry->d_type != DT_DIR || entry->d_name[0] == '.') {
-            LOG(DEBUG) << "Skipping non-user " << entry->d_name;
-            continue;
-        }
-        res &= destroy_volkey(directory_path + "/" + entry->d_name, volume_uuid);
-    }
-    return res;
-}
-
-bool e4crypt_destroy_volume_keys(const std::string& volume_uuid) {
-    bool res = true;
-    LOG(DEBUG) << "TWRP NOT e4crypt_destroy_volume_keys for volume " << escape_empty(volume_uuid);
-    /*return res;
-    auto secdiscardable_path = volume_secdiscardable_path(volume_uuid);
-    res &= android::vold::runSecdiscardSingle(secdiscardable_path);
-    res &= destroy_volume_keys("/data/misc_ce", volume_uuid);
-    res &= destroy_volume_keys("/data/misc_de", volume_uuid);
-    return res;
-}*/
diff --git a/crypto/ext4crypt/Ext4CryptPie.h b/crypto/ext4crypt/Ext4CryptPie.h
index d6d6ecf..7236bc0 100644
--- a/crypto/ext4crypt/Ext4CryptPie.h
+++ b/crypto/ext4crypt/Ext4CryptPie.h
@@ -32,8 +32,8 @@
                              const std::string& secret);
 //bool e4crypt_lock_user_key(userid_t user_id);
 
-bool e4crypt_prepare_user_storage(const std::string& volume_uuid, userid_t user_id, int serial,
-                                  int flags);
+/*bool e4crypt_prepare_user_storage(const std::string& volume_uuid, userid_t user_id, int serial,
+                                  int flags);*/
 /*bool e4crypt_destroy_user_storage(const std::string& volume_uuid, userid_t user_id, int flags);
 
 bool e4crypt_destroy_volume_keys(const std::string& volume_uuid);*/
diff --git a/gui/action.cpp b/gui/action.cpp
index b7d9119..65526b9 100755
--- a/gui/action.cpp
+++ b/gui/action.cpp
@@ -64,6 +64,7 @@
 static string zip_queue[10];
 static int zip_queue_index;
 pid_t sideload_child_pid;
+extern std::vector<users_struct> Users_List;
 
 static void *ActionThread_work_wrapper(void *data);
 
@@ -1502,12 +1503,31 @@
 		simulate_progress_bar();
 	} else {
 		string Password;
+		string userID;
 		DataManager::GetValue("tw_crypto_password", Password);
-		op_status = PartitionManager.Decrypt_Device(Password);
+
+		if (DataManager::GetIntValue(TW_IS_FBE)) {  // for FBE
+			DataManager::GetValue("tw_crypto_user_id", userID);
+			if (userID != "") {
+				op_status = PartitionManager.Decrypt_Device(Password, atoi(userID.c_str()));
+				if (userID != "0") {
+					if (op_status != 0)
+						op_status = 1;
+					operation_end(op_status);
+	          		return 0;
+				}
+			} else {
+				LOGINFO("User ID not found\n");
+				op_status = 1;
+			}
+		::sleep(1);
+		} else {  // for FDE
+			op_status = PartitionManager.Decrypt_Device(Password);
+		}
+
 		if (op_status != 0)
 			op_status = 1;
 		else {
-
 			DataManager::SetValue(TW_IS_ENCRYPTED, 0);
 
 			int has_datamedia;
diff --git a/gui/gui.hpp b/gui/gui.hpp
index d5b9553..7e4ee4e 100644
--- a/gui/gui.hpp
+++ b/gui/gui.hpp
@@ -28,6 +28,7 @@
 void gui_err(const char* text);
 void gui_highlight(const char* text);
 void gui_msg(Message msg);
+void gui_err(Message msg);
 
 std::string gui_parse_text(std::string inText);
 std::string gui_lookup(const std::string& resource_name, const std::string& default_value);
diff --git a/gui/listbox.cpp b/gui/listbox.cpp
index 9fbe092..3386465 100644
--- a/gui/listbox.cpp
+++ b/gui/listbox.cpp
@@ -26,6 +26,7 @@
 #include "rapidxml.hpp"
 #include "objects.hpp"
 #include "../data.hpp"
+#include "../partitions.hpp"
 #include "pages.hpp"
 
 extern std::vector<language_struct> Language_List;
@@ -82,10 +83,28 @@
 					data.selected = 0;
 				mListItems.push_back(data);
 			}
+		} else if (mVariable == "tw_crypto_user_id") {
+			std::vector<users_struct>::iterator iter;
+			std::vector<users_struct>* Users_List = PartitionManager.Get_Users_List();
+			for (iter = Users_List->begin(); iter != Users_List->end(); iter++) {
+				if (!(*iter).isDecrypted) {
+					ListItem data;
+					data.displayName = (*iter).userName;
+					data.variableValue = (*iter).userId;
+					data.action = NULL;
+					DataManager::GetValue("tw_crypto_user_id", currentValue);
+					if (currentValue == (*iter).userId || currentValue == "") {
+						data.selected = 1;
+						DataManager::SetValue("tw_crypto_user_id", (*iter).userId);
+						DataManager::SetValue("tw_crypto_pwtype", (*iter).type);
+					} else
+						data.selected = 0;
+					mListItems.push_back(data);
+				}
+			}
 		}
-	}
-	else
-		allowSelection = false;		// allows using listbox as a read-only list or menu
+	} else
+		allowSelection = false;  // allows using listbox as a read-only list or menu
 
 	// Get the data for the list
 	child = FindNode(node, "listitem");
@@ -94,16 +113,14 @@
 		ListItem item;
 
 		attr = child->first_attribute("name");
-		if (!attr)
-			continue;
+		if (!attr) continue;
 		// We will parse display names when we get page focus to ensure that translating takes place
 		item.displayName = attr->value();
 		item.variableValue = gui_parse_text(child->value());
 		item.selected = (child->value() == currentValue);
 		item.action = NULL;
 		xml_node<>* action = child->first_node("action");
-		if (!action)
-			action = child->first_node("actions");
+		if (!action) action = child->first_node("actions");
 		if (action) {
 			item.action = new GUIAction(child);
 			allowSelection = true;
@@ -122,7 +139,7 @@
 		LoadConditions(child, item.mConditions);
 
 		mListItems.push_back(item);
-		mVisibleItems.push_back(mListItems.size()-1);
+		mVisibleItems.push_back(mListItems.size() - 1);
 
 		child = child->next_sibling("listitem");
 	}
@@ -137,6 +154,33 @@
 	if (!isConditionTrue())
 		return 0;
 
+	if (mVariable == "tw_crypto_user_id") {
+		mListItems.clear();
+		std::vector<users_struct>::iterator iter;
+		std::vector<users_struct>* Users_List = PartitionManager.Get_Users_List();
+		for (iter = Users_List->begin(); iter != Users_List->end(); iter++) {
+			if (!(*iter).isDecrypted) {
+				ListItem data;
+				data.displayName = (*iter).userName;
+				data.variableValue = (*iter).userId;
+				data.action = NULL;
+				DataManager::GetValue("tw_crypto_user_id", currentValue);
+				if (currentValue == (*iter).userId || currentValue == "") {
+					data.selected = 1;
+					DataManager::SetValue("tw_crypto_user_id", (*iter).userId);
+					DataManager::SetValue("tw_crypto_pwtype", (*iter).type);
+				} else
+				data.selected = 0;
+				mListItems.push_back(data);
+			}
+		}
+		mVisibleItems.clear();
+		for (size_t i = 0; i < mListItems.size(); i++) {
+			mVisibleItems.push_back(i);
+		}
+		mUpdate = 1;
+	}
+
 	GUIScrollList::Update();
 
 	if (mUpdate) {
diff --git a/gui/theme/common/landscape.xml b/gui/theme/common/landscape.xml
index 3af174e..7fc9980 100755
--- a/gui/theme/common/landscape.xml
+++ b/gui/theme/common/landscape.xml
@@ -759,6 +759,7 @@
 				<action function="set">tw_cancel_param=</action>
 				<action function="set">tw_show_exclamation=0</action>
 				<action function="set">tw_show_reboot=0</action>
+				<action function="set">tw_crypto_user_id=</action>
 				<action function="page">%tw_clear_destination%</action>
 			</action>
 		</page>
@@ -1062,8 +1063,13 @@
 			</text>
 
 			<text style="text_m_accent">
-				<condition var1="tw_has_data_media" var2="1"/>
 				<placement x="%center_x%" y="%row3_y%" placement="5"/>
+				<text>{@factory_reset5=(not including users/lockscreen)}</text>
+			</text>
+
+			<text style="text_m_accent">
+				<condition var1="tw_has_data_media" var2="1"/>
+				<placement x="%center_x%" y="%row4_y%" placement="5"/>
 				<text>{@factory_reset2=(not including internal storage)}</text>
 			</text>
 
@@ -2517,6 +2523,10 @@
 				</conditions>
 				<placement x="%col2_x_left%" y="%row15a_y%"/>
 				<text>{@decrypt_data_btn=Decrypt Data}</text>
+				<action function="set">tw_crypto_user_id=0</action>
+				<action function="set">tw_crypto_password=</action>
+				<action function="set">tw_password_fail=0</action>
+				<action function="set">tw_crypto_pwtype=%tw_crypto_pwtype_0%</action>
 				<action function="page">decrypt</action>
 			</button>
 
@@ -3383,6 +3393,16 @@
 
 			<listbox style="advanced_listbox">
 				<placement x="%center_x%" y="%row2_y%" w="%content_half_width%" h="%fileselector_install_height%"/>
+				<listitem name="{@decrypt_users=Decrypt Users}">
+					<conditions>
+						<condition var1="tw_is_fbe" var2="1"/>
+						<condition var1="tw_all_users_decrypted" var2="0"/>
+					</conditions>
+					<actions>
+						<action function="set">tw_crypto_user_id=</action>
+						<action function="page">decrypt_users</action>
+					</actions>
+				</listitem>
 				<listitem name="{@reload_theme_btn=Reload Theme}">
 					<action function="reload"/>
 				</listitem>
@@ -4396,10 +4416,17 @@
 			</text>
 
 			<text style="text_m_accent">
+				<condition var1="tw_is_fbe" op="!=" var2="1"/>
 				<placement x="%center_x%" y="%row2_y%" placement="5"/>
 				<text>{@decrypt_data_enter_pass=Enter Password:}</text>
 			</text>
 
+			<text style="text_m_accent">
+				<condition var1="tw_is_fbe" var2="1"/>
+				<placement x="%center_x%" y="%row2_y%" placement="5"/>
+				<text>{@decrypt_data_enter_pass_fbe=Enter Password for User [%tw_crypto_user_id%]}</text>
+			</text>
+
 			<input>
 				<placement x="%col1_x_left%" y="%row3_input_y%" w="%content_width%" h="%input_height%"/>
 				<text>%tw_crypto_display%</text>
@@ -5379,5 +5406,44 @@
 				<action function="screenshot"/>
 			</action>
 		</page>
+
+		<page name="decrypt_users">
+			<template name="page"/>
+
+			<text style="text_l">
+				<placement x="%col1_x_header%" y="%row3_header_y%"/>
+				<text>{@decrypt_users=Decrypt Users}</text>
+			</text>
+
+			<text style="text_m_accent">
+				<placement x="%center_x%" y="%row2_y%" placement="5"/>
+				<text>{@decrypt_users_selection=Select a user ID to decrypt}</text>
+			</text>
+
+			<listbox>
+				<placement x="%col1_x_left%" y="%row1a_y%" w="%content_width%" h="%partitionlist_mount_height%"/>
+				<text>{@select_user=Select User}</text>
+				<icon selected="radio_true" unselected="radio_false" />
+				<data name="tw_crypto_user_id" />
+			</listbox>
+
+			<button style="main_button_half_width">
+				<placement x="%col2_x_right%" y="%row15a_y%"/>
+				<text>{@decrypt_users=Decrypt Users}</text>
+				<action function="set">tw_crypto_password=</action>
+				<action function="set">tw_password_fail=0</action>
+				<action function="page">decrypt</action>
+			</button>
+
+			<action>
+				<touch key="home"/>
+				<action function="page">main</action>
+			</action>
+
+			<action>
+				<touch key="back"/>
+				<action function="page">advanced</action>
+			</action>
+		</page>
 	</pages>
 </recovery>
diff --git a/gui/theme/common/languages/en.xml b/gui/theme/common/languages/en.xml
index ac9472e..07d8e78 100755
--- a/gui/theme/common/languages/en.xml
+++ b/gui/theme/common/languages/en.xml
@@ -141,6 +141,7 @@
 		<string name="factory_reset2">(not including internal storage)</string>
 		<string name="factory_reset3">Most of the time this is</string>
 		<string name="factory_reset4">the only wipe that you need.</string>
+		<string name="factory_reset5">(not including users/lockscreen)</string>
 		<string name="factory_resetting">Factory Reset...</string>
 		<string name="advanced_wipe_hdr">Advanced Wipe</string>
 		<string name="advanced_wipe_btn">Advanced Wipe</string>
@@ -511,6 +512,15 @@
 		<string name="fix_recovery_loop_complete">Fix Recovery Bootloop Complete</string>
 		<string name="fixing_recovery_loop_patch">Patching kernel...</string>
 		<string name="fix_recovery_loop_patch_error">Error patching kernel.</string>
+		<string name="decrypt_users">Decrypt Users</string>
+		<string name="decrypt_users_selection">Select a user ID to decrypt</string>
+		<string name="select_user">Select User</string>
+		<string name="backup_storage_undecrypt_warning">Backup not include some files of user {1}, because the user is not decrypted.</string>
+		<string name="decrypting_user_fbe">Attempting to decrypt FBE for user {1}...</string>
+		<string name="decrypt_user_success_fbe">User {1} Decrypted Successfully</string>
+		<string name="decrypt_user_fail_fbe">Failed to decrypt user {1}</string>
+		<string name="decrypt_data_enter_pass_fbe">Enter Password for User [%tw_crypto_user_id%]</string>
+		<string name="decrypt_data_enter_pattern_fbe">Enter Pattern for User [%tw_crypto_user_id%]</string>
 
 		<!-- Various console messages - these consist of user displayed messages, oftentimes errors -->
 		<string name="no_kernel_selinux">Kernel does not have support for reading SELinux contexts.</string>
@@ -687,7 +697,7 @@
 		<!-- These 2 items are saved in the data manager instead of resource manager, so %llu, etc is correct instead of {1} -->
 		<string name="file_progress">%llu of %llu files, %i%%</string>
 		<string name="size_progress">%lluMB of %lluMB, %i%%</string>
-		<string name="decrypt_cmd">Attempting to decrypt data partition via command line.</string>
+		<string name="decrypt_cmd" version="2">Attempting to decrypt data partition or user data via command line.</string>
 		<string name="base_pkg_err">Failed to load base packages.</string>
 		<string name="simulating">Simulating actions...</string>
 		<string name="backup_cancel">Backup Cancelled</string>
diff --git a/gui/theme/common/portrait.xml b/gui/theme/common/portrait.xml
index 64b8776..a14fc43 100755
--- a/gui/theme/common/portrait.xml
+++ b/gui/theme/common/portrait.xml
@@ -710,6 +710,7 @@
 				<action function="set">tw_cancel_param=</action>
 				<action function="set">tw_show_exclamation=0</action>
 				<action function="set">tw_show_reboot=0</action>
+				<action function="set">tw_crypto_user_id=</action>
 				<action function="page">%tw_clear_destination%</action>
 			</action>
 		</page>
@@ -1013,8 +1014,13 @@
 			</text>
 
 			<text style="text_m_accent">
-				<condition var1="tw_has_data_media" var2="1"/>
 				<placement x="%center_x%" y="%row3_y%" placement="5"/>
+				<text>{@factory_reset5=(not including users/lockscreen)}</text>
+			</text>
+
+			<text style="text_m_accent">
+				<condition var1="tw_has_data_media" var2="1"/>
+				<placement x="%center_x%" y="%row4_y%" placement="5"/>
 				<text>{@factory_reset2=(not including internal storage)}</text>
 			</text>
 
@@ -2673,6 +2679,10 @@
 				</conditions>
 				<placement x="%center_x%" y="%row18a_y%"/>
 				<text>{@decrypt_data_btn=Decrypt Data}</text>
+				<action function="set">tw_crypto_user_id=0</action>
+				<action function="set">tw_crypto_password=</action>
+				<action function="set">tw_password_fail=0</action>
+				<action function="set">tw_crypto_pwtype=%tw_crypto_pwtype_0%</action>
 				<action function="page">decrypt</action>
 			</button>
 
@@ -3543,6 +3553,16 @@
 
 			<listbox style="advanced_listbox">
 				<placement x="%indent%" y="%row13a_y%" w="%content_width%" h="%listbox_advanced_height%"/>
+				<listitem name="{@decrypt_users=Decrypt Users}">
+					<conditions>
+						<condition var1="tw_is_fbe" var2="1"/>
+						<condition var1="tw_all_users_decrypted" var2="0"/>
+					</conditions>
+					<actions>
+						<action function="set">tw_crypto_user_id=</action>
+						<action function="page">decrypt_users</action>
+					</actions>
+				</listitem>
 				<listitem name="{@reload_theme_btn=Reload Theme}">
 					<action function="reload"/>
 				</listitem>
@@ -4557,10 +4577,17 @@
 			</text>
 
 			<text style="text_m_accent">
+				<condition var1="tw_is_fbe" op="!=" var2="1"/>
 				<placement x="%center_x%" y="%row2_y%" placement="5"/>
 				<text>{@decrypt_data_enter_pass=Enter Password:}</text>
 			</text>
 
+			<text style="text_m_accent">
+				<condition var1="tw_is_fbe" var2="1"/>
+				<placement x="%center_x%" y="%row2_y%" placement="5"/>
+				<text>{@decrypt_data_enter_pass_fbe=Enter Password for User [%tw_crypto_user_id%]}</text>
+			</text>
+
 			<input>
 				<placement x="%indent%" y="%row3_input_y%" w="%content_width%" h="%input_height%"/>
 				<text>%tw_crypto_display%</text>
@@ -4616,10 +4643,17 @@
 			</text>
 
 			<text style="text_m_accent">
+				<condition var1="tw_is_fbe" op="!=" var2="1"/>
 				<placement x="%center_x%" y="%row2_y%" placement="5"/>
 				<text>{@decrypt_data_enter_pattern=Enter Pattern.}</text>
 			</text>
 
+			<text style="text_m_accent">
+				<condition var1="tw_is_fbe" var2="1"/>
+				<placement x="%center_x%" y="%row2_y%" placement="5"/>
+				<text>{@decrypt_data_enter_pattern_fbe=Enter Pattern for User [%tw_crypto_user_id%]}</text>
+			</text>
+
 			<text style="text_m_fail">
 				<condition var1="tw_password_fail" var2="1"/>
 				<placement x="%center_x%" y="%row3_y%" placement="5"/>
@@ -5139,5 +5173,44 @@
 				<action function="screenshot"/>
 			</action>
 		</page>
+
+		<page name="decrypt_users">
+			<template name="page"/>
+
+			<text style="text_l">
+				<placement x="%col1_x_header%" y="%row3_header_y%"/>
+				<text>{@decrypt_users=Decrypt Users}</text>
+			</text>
+
+			<text style="text_m_accent">
+				<placement x="%center_x%" y="%row2_y%" placement="5"/>
+				<text>{@decrypt_users_selection=Select a user ID to decrypt}</text>
+			</text>
+
+			<listbox>
+				<placement x="%indent%" y="%row3_y%" w="%content_width%" h="%listbox_advanced_height%"/>
+				<text>{@select_user=Select User}</text>
+				<icon selected="radio_true" unselected="radio_false" />
+				<data name="tw_crypto_user_id" />
+			</listbox>
+
+			<button style="main_button_half_height">
+				<placement x="%center_x%" y="%row21a_y%"/>
+				<text>{@decrypt_users=Decrypt Users}</text>
+				<action function="set">tw_crypto_password=</action>
+				<action function="set">tw_password_fail=0</action>
+				<action function="page">decrypt</action>
+			</button>
+
+			<action>
+				<touch key="home"/>
+				<action function="page">main</action>
+			</action>
+
+			<action>
+				<touch key="back"/>
+				<action function="page">advanced</action>
+			</action>
+		</page>
 	</pages>
 </recovery>
diff --git a/gui/theme/common/watch.xml b/gui/theme/common/watch.xml
index 70ccf38..af6a643 100755
--- a/gui/theme/common/watch.xml
+++ b/gui/theme/common/watch.xml
@@ -975,6 +975,7 @@
 				<action function="set">tw_cancel_param=</action>
 				<action function="set">tw_show_exclamation=0</action>
 				<action function="set">tw_show_reboot=0</action>
+				<action function="set">tw_crypto_user_id=</action>
 				<action function="page">%tw_clear_destination%</action>
 			</action>
 		</page>
@@ -1385,8 +1386,13 @@
 			</text>
 
 			<text style="text_m_accent">
-				<condition var1="tw_has_data_media" var2="1"/>
 				<placement x="%center_x%" y="%row2_y%" placement="5"/>
+				<text>{@factory_reset5=(not including users/lockscreen)}</text>
+			</text>
+
+			<text style="text_m_accent">
+				<condition var1="tw_has_data_media" var2="1"/>
+				<placement x="%center_x%" y="%row3_y%" placement="5"/>
 				<text>{@factory_reset2=(not including internal storage)}</text>
 			</text>
 
@@ -3194,6 +3200,10 @@
 				</conditions>
 				<placement x="%col1_x_left%" y="%row6_y%"/>
 				<text>{@decrypt_data_btn=Decrypt Data}</text>
+				<action function="set">tw_crypto_user_id=0</action>
+				<action function="set">tw_crypto_password=</action>
+				<action function="set">tw_password_fail=0</action>
+				<action function="set">tw_crypto_pwtype=%tw_crypto_pwtype_0%</action>
 				<action function="page">decrypt</action>
 			</button>
 
@@ -4158,6 +4168,16 @@
 
 			<listbox style="advanced_listbox">
 				<placement x="%indent%" y="%row2_header_y%" w="%content_width%" h="%fileselector_install_height%"/>
+				<listitem name="{@decrypt_users=Decrypt Users}">
+					<conditions>
+						<condition var1="tw_is_fbe" var2="1"/>
+						<condition var1="tw_all_users_decrypted" var2="0"/>
+					</conditions>
+					<actions>
+						<action function="set">tw_crypto_user_id=</action>
+						<action function="page">decrypt_users</action>
+					</actions>
+				</listitem>
 				<listitem name="{@reload_theme_btn=Reload Theme}">
 					<action function="reload"/>
 				</listitem>
@@ -5256,10 +5276,17 @@
 			</text>
 
 			<text style="text_m_accent">
+				<condition var1="tw_is_fbe" op="!=" var2="1"/>
 				<placement x="%col1_x_left%" y="%row1_y%"/>
 				<text>{@decrypt_data_enter_pass=Enter Password:}</text>
 			</text>
 
+			<text style="text_m_accent">
+				<condition var1="tw_is_fbe" var2="1"/>
+				<placement x="%col1_x_left%" y="%row1_y%"/>
+				<text>{@decrypt_data_enter_pass_fbe=Enter Password for User [%tw_crypto_user_id%]}</text>
+			</text>
+
 			<input>
 				<placement x="%col1_x_left%" y="%row2_y%" w="%content_width%" h="%input_height%"/>
 				<text>%tw_crypto_display%</text>
@@ -5316,11 +5343,19 @@
 			</text>
 
 			<text style="text_m_accent">
+				<condition var1="tw_is_fbe" op="!=" var2="1"/>
 				<condition var1="tw_password_fail" op="!=" var2="1"/>
 				<placement x="%center_x%" y="%row5_y%" placement="5"/>
 				<text>{@decrypt_data_enter_pattern=Enter Pattern.}</text>
 			</text>
 
+			<text style="text_m_accent">
+				<condition var1="tw_is_fbe" var2="1"/>
+				<condition var1="tw_password_fail" op="!=" var2="1"/>
+				<placement x="%center_x%" y="%row5_y%" placement="5"/>
+				<text>{@decrypt_data_enter_pattern_fbe=Enter Pattern for User [%tw_crypto_user_id%]}</text>
+			</text>
+
 			<text style="text_m_fail">
 				<condition var1="tw_password_fail" var2="1"/>
 				<placement x="%center_x%" y="%row5_y%" placement="5"/>
@@ -5711,5 +5746,44 @@
 				<action function="screenshot"/>
 			</action>
 		</page>
+
+		<page name="decrypt_users">
+			<template name="page"/>
+
+			<text style="text_l">
+				<placement x="%col1_x_header%" y="%row3_header_y%"/>
+				<text>{@decrypt_users=Decrypt Users}</text>
+			</text>
+
+			<text style="text_m_accent">
+				<placement x="%center_x%" y="%row2_y%" placement="5"/>
+				<text>{@decrypt_users_selection=Select a user ID to decrypt}</text>
+			</text>
+
+			<listbox>
+				<placement x="%indent%" y="%row2_header_y%" w="%content_width%" h="%fileselector_install_height%"/>
+				<text>{@select_user=Select User}</text>
+				<icon selected="radio_true" unselected="radio_false" />
+				<data name="tw_crypto_user_id" />
+			</listbox>
+
+			<button style="main_button_half_height">
+				<placement x="%col1_x_left%" y="%row13_y%" textplacement="6"/>
+				<text>{@decrypt_users=Decrypt Users}</text>
+				<action function="set">tw_crypto_password=</action>
+				<action function="set">tw_password_fail=0</action>
+				<action function="page">decrypt</action>
+			</button>
+
+			<action>
+				<touch key="home"/>
+				<action function="page">main</action>
+			</action>
+
+			<action>
+				<touch key="back"/>
+				<action function="page">advanced</action>
+			</action>
+		</page>
 	</pages>
 </recovery>
diff --git a/openrecoveryscript.cpp b/openrecoveryscript.cpp
index a52211c..5d3b51f 100755
--- a/openrecoveryscript.cpp
+++ b/openrecoveryscript.cpp
@@ -404,13 +404,22 @@
 				if (ret_val != 0)
 					ret_val = 1; // failure
 			} else if (strcmp(command, "decrypt") == 0) {
+				// twrp cmd cannot decrypt a password with space, should decrypt on gui
 				if (*value) {
-					ret_val = PartitionManager.Decrypt_Device(value);
+					string tmp = value;
+					std::vector<string> args = TWFunc::Split_String(tmp, " ");
+
+					string pass = args[0];
+					string userid = "0";
+					if (args.size() > 1)
+						userid = args[1];
+
+					ret_val = PartitionManager.Decrypt_Device(pass, atoi(userid.c_str()));
 					if (ret_val != 0)
-						ret_val = 1; // failure
+						ret_val = 1;  // failure
 				} else {
 					gui_err("no_pwd=No password provided.");
-					ret_val = 1; // failure
+					ret_val = 1;  // failure
 				}
 			} else {
 				LOGERR("Unrecognized script command: '%s'\n", command);
@@ -421,23 +430,28 @@
 		unlink(SCRIPT_FILE_TMP);
 		gui_msg("done_ors=Done processing script file");
 	} else {
-		gui_msg(Msg(msg::kError, "error_opening_strerr=Error opening: '{1}' ({2})")(SCRIPT_FILE_TMP)(strerror(errno)));
+		gui_msg(Msg(msg::kError, "error_opening_strerr=Error opening: '{1}' ({2})")(SCRIPT_FILE_TMP)(
+			strerror(errno)));
 		return 1;
 	}
 
-	if (install_cmd && DataManager::GetIntValue(TW_HAS_INJECTTWRP) == 1 && DataManager::GetIntValue(TW_INJECT_AFTER_ZIP) == 1) {
+	if (install_cmd && DataManager::GetIntValue(TW_HAS_INJECTTWRP) == 1 &&
+	DataManager::GetIntValue(TW_INJECT_AFTER_ZIP) == 1) {
 		gui_msg("injecttwrp=Injecting TWRP into boot image...");
 		TWPartition* Boot = PartitionManager.Find_Partition_By_Path("/boot");
 		if (Boot == NULL || Boot->Current_File_System != "emmc")
-			TWFunc::Exec_Cmd("injecttwrp --dump /tmp/backup_recovery_ramdisk.img /tmp/injected_boot.img --flash");
+			TWFunc::Exec_Cmd(
+			"injecttwrp --dump /tmp/backup_recovery_ramdisk.img /tmp/injected_boot.img --flash");
 		else {
-			string injectcmd = "injecttwrp --dump /tmp/backup_recovery_ramdisk.img /tmp/injected_boot.img --flash bd=" + Boot->Actual_Block_Device;
+			string injectcmd =
+			"injecttwrp --dump /tmp/backup_recovery_ramdisk.img /tmp/injected_boot.img --flash bd=" +
+			Boot->Actual_Block_Device;
 			TWFunc::Exec_Cmd(injectcmd.c_str());
 		}
 		gui_msg("done=Done.");
 	}
 	if (sideload)
-		ret_val = 1; // Forces booting to the home page after sideload
+		ret_val = 1;  // Forces booting to the home page after sideload
 	return ret_val;
 }
 
@@ -650,26 +664,48 @@
 
 // this is called by the "twcmd" GUI action when a command is received via FIFO from the "twrp" command line tool
 void OpenRecoveryScript::Run_CLI_Command(const char* command) {
-	if (strlen(command) > 11 && strncmp(command, "runscript", 9) == 0) {
-		const char* filename = command + 10;
-		if (OpenRecoveryScript::copy_script_file(filename) == 0) {
-			LOGINFO("Unable to copy script file\n");
+	string tmp = command;
+	std::vector<string> parts =
+		TWFunc::Split_String(tmp, " ");  // pats[0] is cmd, parts[1...] is args
+	string cmd_str = parts[0];
+
+	if (cmd_str == "runscript") {
+		if (parts.size() > 1) {
+			string filename = parts[1];
+			if (OpenRecoveryScript::copy_script_file(filename) == 0) {
+				LOGINFO("Unable to copy script file\n");
+			} else {
+				OpenRecoveryScript::run_script_file();
+			}
 		} else {
-			OpenRecoveryScript::run_script_file();
+			LOGINFO("Missing parameter: script file name\n");
 		}
-	} else if (strlen(command) > 5 && strncmp(command, "get", 3) == 0) {
-		const char* varname = command + 4;
-		string value;
-		DataManager::GetValue(varname, value);
-		gui_print("%s = %s\n", varname, value.c_str());
-	} else if (strlen(command) > 9 && strncmp(command, "decrypt", 7) == 0) {
-		const char* pass = command + 8;
-		gui_msg("decrypt_cmd=Attempting to decrypt data partition via command line.");
-		if (PartitionManager.Decrypt_Device(pass) == 0) {
-			// set_page_done = 1;  // done by singleaction_page anyway
-			std::string orsFile = TWFunc::get_cache_dir() + "/openrecoveryscript";
-			if (TWFunc::Path_Exists(orsFile)) {
-				Run_OpenRecoveryScript_Action();
+	} else if (cmd_str == "get") {
+		if (parts.size() > 1) {
+			string varname = parts[1];
+			string value;
+			DataManager::GetValue(varname, value);
+			gui_print("%s = %s\n", varname.c_str(), value.c_str());
+		} else {
+			LOGINFO("Missing parameter: var name\n");
+		}
+	} else if (cmd_str == "decrypt") {
+		// twrp cmd cannot decrypt a password with space, should decrypt on gui
+		if (parts.size() == 1) {
+			gui_err("no_pwd=No password provided.");
+		} else {
+			string pass = parts[1];
+			string userid = "0";
+			if (parts.size() > 2)
+				userid = parts[2];
+
+			gui_msg("decrypt_cmd=Attempting to decrypt data partition or user data via command line.");
+			if (PartitionManager.Decrypt_Device(pass, atoi(userid.c_str())) == 0) {
+				// set_page_done = 1;  // done by singleaction_page anyway
+				std::string orsFile = TWFunc::get_cache_dir() + "/openrecoveryscript";
+				if (TWFunc::Path_Exists(orsFile)) {
+					Run_OpenRecoveryScript_Action();
+				}
 			}
 		}
 	} else if (OpenRecoveryScript::Insert_ORS_Command(command)) {
diff --git a/orscmd/orscmd.cpp b/orscmd/orscmd.cpp
index c47c0f6..0a12a08 100644
--- a/orscmd/orscmd.cpp
+++ b/orscmd/orscmd.cpp
@@ -45,7 +45,7 @@
 	printf("  wipe <partition name>\n");
 	printf("  sideload\n");
 	printf("  set <variable> [value]\n");
-	printf("  decrypt <password>\n");
+	printf("  decrypt <password> [USER ID]\n");
 	printf("  remountrw\n");
 	printf("  fixperms\n");
 	printf("  mount <path>\n");
diff --git a/partition.cpp b/partition.cpp
index 7f4189a..df9960d 100644
--- a/partition.cpp
+++ b/partition.cpp
@@ -651,17 +651,20 @@
 		DataManager::SetValue(TW_IS_DECRYPTED, 1);
 		Is_Encrypted = true;
 		Is_Decrypted = true;
-		if (Key_Directory.empty())
+		if (Key_Directory.empty()) {
 			Is_FBE = false;
-		else
+			DataManager::SetValue(TW_IS_FBE, 0);
+		} else {
 			Is_FBE = true;
-		DataManager::SetValue(TW_IS_FBE, 0);
+			DataManager::SetValue(TW_IS_FBE, 1);
+		}
 		Decrypted_Block_Device = crypto_blkdev;
 		LOGINFO("Data already decrypted, new block device: '%s'\n", crypto_blkdev);
 	} else if (!Mount(false)) {
 		if (Is_Present) {
 			if (Key_Directory.empty()) {
-				set_partition_data(Actual_Block_Device.c_str(), Crypto_Key_Location.c_str(), Fstab_File_System.c_str());
+				set_partition_data(Actual_Block_Device.c_str(), Crypto_Key_Location.c_str(),
+				Fstab_File_System.c_str());
 				if (cryptfs_check_footer() == 0) {
 					Is_Encrypted = true;
 					Is_Decrypted = false;
@@ -670,6 +673,7 @@
 					Setup_Image();
 					DataManager::SetValue(TW_IS_ENCRYPTED, 1);
 					DataManager::SetValue(TW_CRYPTO_PWTYPE, cryptfs_get_password_type());
+					DataManager::SetValue("tw_crypto_pwtype_0", cryptfs_get_password_type());
 					DataManager::SetValue(TW_CRYPTO_PASSWORD, "");
 					DataManager::SetValue("tw_crypto_display", "");
 				} else {
@@ -680,10 +684,10 @@
 				Is_Decrypted = false;
 			}
 		} else if (Key_Directory.empty()) {
-			LOGERR("Primary block device '%s' for mount point '%s' is not present!\n", Primary_Block_Device.c_str(), Mount_Point.c_str());
+			LOGERR("Primary block device '%s' for mount point '%s' is not present!\n",
+			Primary_Block_Device.c_str(), Mount_Point.c_str());
 		}
 	} else {
-
 		if (!Decrypt_FBE_DE()) {
 			char wrappedvalue[PROPERTY_VALUE_MAX];
 			property_get("fbe.data.wrappedkey", wrappedvalue, "");
@@ -715,46 +719,54 @@
 if (TWFunc::Path_Exists("/data/unencrypted/key/version")) {
 		LOGINFO("File Based Encryption is present\n");
 #ifdef TW_INCLUDE_FBE
-		ExcludeAll(Mount_Point + "/convert_fbe");
-		ExcludeAll(Mount_Point + "/unencrypted");
-		//ExcludeAll(Mount_Point + "/system/users/0"); // we WILL need to retain some of this if multiple users are present or we just need to delete more folders for the extra users somewhere else
-		ExcludeAll(Mount_Point + "/misc/vold/user_keys");
-		//ExcludeAll(Mount_Point + "/system_ce");
-		//ExcludeAll(Mount_Point + "/system_de");
-		//ExcludeAll(Mount_Point + "/misc_ce");
-		//ExcludeAll(Mount_Point + "/misc_de");
-		ExcludeAll(Mount_Point + "/system/gatekeeper.password.key");
-		ExcludeAll(Mount_Point + "/system/gatekeeper.pattern.key");
-		ExcludeAll(Mount_Point + "/system/locksettings.db");
-		//ExcludeAll(Mount_Point + "/system/locksettings.db-shm"); // don't seem to need this one, but the other 2 are needed
-		ExcludeAll(Mount_Point + "/system/locksettings.db-wal");
-		//ExcludeAll(Mount_Point + "/user_de");
-		//ExcludeAll(Mount_Point + "/misc/profiles/cur/0"); // might be important later
-		ExcludeAll(Mount_Point + "/misc/gatekeeper");
-		ExcludeAll(Mount_Point + "/misc/keystore");
-		ExcludeAll(Mount_Point + "/drm/kek.dat");
-		ExcludeAll(Mount_Point + "/system_de/0/spblob"); // contains data needed to decrypt pixel 2
-		int retry_count = 3;
-		while (!Decrypt_DE() && --retry_count)
-			usleep(2000);
-		if (retry_count > 0) {
-			property_set("ro.crypto.state", "encrypted");
-			Is_Encrypted = true;
-			Is_Decrypted = false;
-			Is_FBE = true;
-			DataManager::SetValue(TW_IS_FBE, 1);
-			DataManager::SetValue(TW_IS_ENCRYPTED, 1);
-			string filename;
-			int pwd_type = Get_Password_Type(0, filename);
-			if (pwd_type < 0) {
-				LOGERR("This TWRP does not have synthetic password decrypt support\n");
-				pwd_type = 0; // default password
-			}
-			DataManager::SetValue(TW_CRYPTO_PWTYPE, pwd_type);
-			DataManager::SetValue(TW_CRYPTO_PASSWORD, "");
-			DataManager::SetValue("tw_crypto_display", "");
-			return true;
+	Is_FBE = true;
+	DataManager::SetValue(TW_IS_FBE, 1);
+	ExcludeAll(Mount_Point + "/convert_fbe");
+	ExcludeAll(Mount_Point + "/unencrypted");
+	ExcludeAll(Mount_Point + "/misc/vold/user_keys");
+	ExcludeAll(Mount_Point + "/system/gatekeeper.password.key");
+	ExcludeAll(Mount_Point + "/system/gatekeeper.pattern.key");
+	ExcludeAll(Mount_Point + "/system/locksettings.db");
+	ExcludeAll(Mount_Point + "/system/locksettings.db-wal");
+	ExcludeAll(Mount_Point + "/misc/gatekeeper");
+	ExcludeAll(Mount_Point + "/misc/keystore");
+	ExcludeAll(Mount_Point + "/drm/kek.dat");
+	ExcludeAll(Mount_Point + "/system_de/0/spblob");  // contains data needed to decrypt pixel 2
+	ExcludeAll(Mount_Point + "/system/users/0/gatekeeper.password.key");
+	ExcludeAll(Mount_Point + "/system/users/0/gatekeeper.pattern.key");
+	ExcludeAll(Mount_Point + "/cache");
+	int retry_count = 3;
+	while (!Decrypt_DE() && --retry_count)
+		usleep(2000);
+	PartitionManager.Parse_Users();  // after load_all_de_keys() to parse_users
+	std::vector<users_struct>::iterator iter;
+	std::vector<users_struct>* userList = PartitionManager.Get_Users_List();
+	for (iter = userList->begin(); iter != userList->end(); iter++) {
+		if (atoi((*iter).userId.c_str()) != 0) {
+			ExcludeAll(Mount_Point + "/system_de/" + (*iter).userId + "/spblob");
+			ExcludeAll(Mount_Point + "/system/users/" + (*iter).userId + "/gatekeeper.password.key");
+			ExcludeAll(Mount_Point + "/system/users/" + (*iter).userId + "/gatekeeper.pattern.key");
+			ExcludeAll(Mount_Point + "/system/users/" + (*iter).userId + "/locksettings.db");
+			ExcludeAll(Mount_Point + "/system/users/" + (*iter).userId + "/locksettings.db-wal");
 		}
+	}
+	if (retry_count > 0) {
+		property_set("ro.crypto.state", "encrypted");
+		Is_Encrypted = true;
+		Is_Decrypted = false;
+		DataManager::SetValue(TW_IS_ENCRYPTED, 1);
+		string filename;
+		int pwd_type = Get_Password_Type(0, filename);
+		if (pwd_type < 0) {
+			LOGERR("This TWRP does not have synthetic password decrypt support\n");
+			pwd_type = 0;  // default password
+		}
+		DataManager::SetValue(TW_CRYPTO_PWTYPE, pwd_type);
+		DataManager::SetValue("tw_crypto_pwtype_0", pwd_type);
+		DataManager::SetValue(TW_CRYPTO_PASSWORD, "");
+		DataManager::SetValue("tw_crypto_display", "");
+		return true;
+	}
 #else
 		LOGERR("FBE found but FBE support not present in TWRP\n");
 #endif
@@ -2557,6 +2569,22 @@
 	Full_FileName = part_settings->Backup_Folder + "/" + Backup_FileName;
 	if (Has_Data_Media)
 		gui_msg(Msg(msg::kWarning, "backup_storage_warning=Backups of {1} do not include any files in internal storage such as pictures or downloads.")(Display_Name));
+	if (Mount_Point == "/data" && DataManager::GetIntValue(TW_IS_FBE)) {
+		std::vector<users_struct>::iterator iter;
+		std::vector<users_struct>* userList = PartitionManager.Get_Users_List();
+		for (iter = userList->begin(); iter != userList->end(); iter++) {
+			if (!(*iter).isDecrypted && (*iter).userId != "0") {
+				gui_msg(Msg(msg::kWarning,
+				"backup_storage_undecrypt_warning=Backup will not include some files from user {1} "
+				"because the user is not decrypted.")((*iter).userId));
+				backup_exclusions.add_absolute_dir("/data/system_ce/" + (*iter).userId);
+				backup_exclusions.add_absolute_dir("/data/misc_ce/" + (*iter).userId);
+				backup_exclusions.add_absolute_dir("/data/vendor_ce/" + (*iter).userId);
+				backup_exclusions.add_absolute_dir("/data/media/" + (*iter).userId);
+				backup_exclusions.add_absolute_dir("/data/user/" + (*iter).userId);
+			}
+		}
+	}
 	tar.part_settings = part_settings;
 	tar.backup_exclusions = &backup_exclusions;
 	tar.setdir(Backup_Path);
diff --git a/partitionmanager.cpp b/partitionmanager.cpp
index b6918f3..3b0e8a2 100755
--- a/partitionmanager.cpp
+++ b/partitionmanager.cpp
@@ -72,18 +72,18 @@
 }
 
 #ifdef TW_INCLUDE_CRYPTO
-	#include "crypto/fde/cryptfs.h"
-	#include "gui/rapidxml.hpp"
-	#include "gui/pages.hpp"
-	#ifdef TW_INCLUDE_FBE
-		#include "crypto/ext4crypt/Decrypt.h"
-		#ifdef TW_INCLUDE_FBE_METADATA_DECRYPT
-			#include "crypto/ext4crypt/MetadataCrypt.h"
-		#endif
-	#endif
-	#ifdef TW_CRYPTO_USE_SYSTEM_VOLD
-		#include "crypto/vold_decrypt/vold_decrypt.h"
-	#endif
+#include "crypto/fde/cryptfs.h"
+#include "gui/rapidxml.hpp"
+#include "gui/pages.hpp"
+#ifdef TW_INCLUDE_FBE
+#include "crypto/ext4crypt/Decrypt.h"
+#ifdef TW_INCLUDE_FBE_METADATA_DECRYPT
+#include "crypto/ext4crypt/MetadataCrypt.h"
+#endif
+#endif
+#ifdef TW_CRYPTO_USE_SYSTEM_VOLD
+#include "crypto/vold_decrypt/vold_decrypt.h"
+#endif
 #endif
 
 #ifdef AB_OTA_UPDATER
@@ -92,6 +92,7 @@
 #endif
 
 extern bool datamedia;
+std::vector<users_struct> Users_List;
 
 TWPartitionManager::TWPartitionManager(void) {
 	mtp_was_enabled = false;
@@ -349,10 +350,12 @@
 				}
 			} else {
 				DataManager::SetValue("TW_CRYPTO_TYPE", password_type);
+				DataManager::SetValue("tw_crypto_pwtype_0", password_type);
 			}
 		}
 	}
-	if (Decrypt_Data && (!Decrypt_Data->Is_Encrypted || Decrypt_Data->Is_Decrypted) && Decrypt_Data->Mount(false)) {
+	if (Decrypt_Data && (!Decrypt_Data->Is_Encrypted || Decrypt_Data->Is_Decrypted) &&
+	Decrypt_Data->Mount(false)) {
 		Decrypt_Adopted();
 	}
 #endif
@@ -1673,11 +1676,11 @@
 		} else {
 			gui_msg("decrypt_success_nodev=Data successfully decrypted");
 		}
+		property_set("twrp.decrypt.done", "true");
 		dat->Setup_File_System(false);
-		dat->Current_File_System = dat->Fstab_File_System; // Needed if we're ignoring blkid because encrypted devices start out as emmc
+		dat->Current_File_System = dat->Fstab_File_System;  // Needed if we're ignoring blkid because encrypted devices start out as emmc
 
-		// Sleep for a bit so that the device will be ready
-		sleep(1);
+		sleep(1); // Sleep for a bit so that the device will be ready
 		if (dat->Has_Data_Media && dat->Mount(false) && TWFunc::Path_Exists("/data/media/0")) {
 			dat->Storage_Path = "/data/media/0";
 			dat->Symlink_Path = dat->Storage_Path;
@@ -1692,7 +1695,92 @@
 		LOGERR("Unable to locate data partition.\n");
 }
 
-int TWPartitionManager::Decrypt_Device(string Password) {
+void TWPartitionManager::Parse_Users() {
+#ifdef TW_INCLUDE_FBE
+	char user_check_result[PROPERTY_VALUE_MAX];
+	for (int userId = 0; userId <= 9999; userId++) {
+		string prop = "twrp.user." + to_string(userId) + ".decrypt";
+		property_get(prop.c_str(), user_check_result, "-1");
+		if (strcmp(user_check_result, "-1") != 0) {
+			if (userId < 0 || userId > 9999) {
+				LOGINFO("Incorrect user id %d\n", userId);
+				continue;
+			}
+			struct users_struct user;
+			user.userId = to_string(userId);
+
+			// Attempt to get name of user. Fallback to user ID if this fails.
+			char* userFile = PageManager::LoadFileToBuffer("/data/system/users/" + to_string(userId) + ".xml", NULL);
+			if (userFile == NULL) 
+				user.userName = to_string(userId);
+			else {
+				xml_document<> *userXml = new xml_document<>();
+				userXml->parse<0>(userFile);
+				xml_node<>* userNode = userXml->first_node("user");
+				if (userNode == nullptr) {
+					user.userName = to_string(userId);
+				} else {
+					xml_node<>* nameNode = userNode->first_node("name");
+					if (nameNode == nullptr)
+						user.userName = to_string(userId);
+					else {
+						string userName = nameNode->value();
+						user.userName = userName + " (" + to_string(userId) + ")";
+					}
+				}
+			}
+
+			string filename;
+			user.type = Get_Password_Type(userId, filename);
+
+			user.isDecrypted = false;
+			if (strcmp(user_check_result, "1") == 0)
+				user.isDecrypted = true;
+			Users_List.push_back(user);
+		}
+	}
+	Check_Users_Decryption_Status();
+#endif
+}
+
+std::vector<users_struct>* TWPartitionManager::Get_Users_List() {
+	return &Users_List;
+}
+
+void TWPartitionManager::Mark_User_Decrypted(int userID) {
+#ifdef TW_INCLUDE_FBE
+	std::vector<users_struct>::iterator iter;
+	for (iter = Users_List.begin(); iter != Users_List.end(); iter++) {
+		if (atoi((*iter).userId.c_str()) == userID) {
+			(*iter).isDecrypted = true;
+			string user_prop_decrypted = "twrp.user." + to_string(userID) + ".decrypt";
+			property_set(user_prop_decrypted.c_str(), "1");
+			break;
+		}
+	}
+	Check_Users_Decryption_Status();
+#endif
+}
+
+void TWPartitionManager::Check_Users_Decryption_Status() {
+#ifdef TW_INCLUDE_FBE
+	int all_is_decrypted = 1;
+	std::vector<users_struct>::iterator iter;
+	for (iter = Users_List.begin(); iter != Users_List.end(); iter++) {
+		if (!(*iter).isDecrypted) {
+			all_is_decrypted = 0;
+			break;
+		}
+	}
+	if (all_is_decrypted == 1) {
+		DataManager::SetValue("tw_all_users_decrypted", "1");
+		property_set("twrp.all.users.decrypted", "true");
+	} else
+		DataManager::SetValue("tw_all_users_decrypted", "0");
+#endif
+}
+
+int TWPartitionManager::Decrypt_Device(string Password, int user_id) {
 #ifdef TW_INCLUDE_CRYPTO
 	char crypto_state[PROPERTY_VALUE_MAX], crypto_blkdev[PROPERTY_VALUE_MAX];
 	std::vector<TWPartition*>::iterator iter;
@@ -1716,14 +1804,49 @@
 #ifdef TW_INCLUDE_FBE
 		if (!Mount_By_Path("/data", true)) // /data has to be mounted for FBE
 			return -1;
+
+		bool user_need_decrypt = false;
+		std::vector<users_struct>::iterator iter;
+		for (iter = Users_List.begin(); iter != Users_List.end(); iter++) {
+			if (atoi((*iter).userId.c_str()) == user_id && !(*iter).isDecrypted) {
+				user_need_decrypt = true;
+			}
+		}
+		if (!user_need_decrypt) {
+			LOGINFO("User %d does not require decryption\n", user_id);
+			return 0;
+		}
+
 		int retry_count = 10;
 		while (!TWFunc::Path_Exists("/data/system/users/gatekeeper.password.key") && --retry_count)
-			usleep(2000); // A small sleep is needed after mounting /data to ensure reliable decrypt... maybe because of DE?
-		int user_id = DataManager::GetIntValue("tw_decrypt_user_id");
-		LOGINFO("Decrypting FBE for user %i\n", user_id);
+			usleep(2000); // A small sleep is needed after mounting /data to ensure reliable decrypt...maybe because of DE?
+		gui_msg(Msg("decrypting_user_fbe=Attempting to decrypt FBE for user {1}...")(user_id));
 		if (Decrypt_User(user_id, Password)) {
-			Post_Decrypt("");
+			gui_msg(Msg("decrypt_user_success_fbe=User {1} Decrypted Successfully")(user_id));
+			Mark_User_Decrypted(user_id);
+			if (user_id == 0) {
+				// When decrypting user 0 also try all other users
+				std::vector<users_struct>::iterator iter;
+				for (iter = Users_List.begin(); iter != Users_List.end(); iter++) {
+					if ((*iter).userId == "0" || (*iter).isDecrypted)
+						continue;
+
+					int tmp_user_id = atoi((*iter).userId.c_str());
+					gui_msg(Msg("decrypting_user_fbe=Attempting to decrypt FBE for user {1}...")(tmp_user_id));
+					if (Decrypt_User(tmp_user_id, Password) ||
+					(Password != "!" && Decrypt_User(tmp_user_id, "!"))) { // "!" means default password
+						gui_msg(Msg("decrypt_user_success_fbe=User {1} Decrypted Successfully")(tmp_user_id));
+						Mark_User_Decrypted(tmp_user_id);
+					} else {
+						gui_msg(Msg("decrypt_user_fail_fbe=Failed to decrypt user {1}")(tmp_user_id));
+					}
+				}
+				Post_Decrypt("");
+			}
+
 			return 0;
+		} else {
+			gui_msg(Msg(msg::kError, "decrypt_user_fail_fbe=Failed to decrypt user {1}")(user_id));
 		}
 #else
 		LOGERR("FBE support is not present\n");
@@ -1731,6 +1854,13 @@
 		return -1;
 	}
 
+	char isdecrypteddata[PROPERTY_VALUE_MAX];
+	property_get("twrp.decrypt.done", isdecrypteddata, "");
+	if (strcmp(isdecrypteddata, "true") == 0) {
+		LOGINFO("Data has no decryption required\n");
+		return 0;
+	}
+
 	int pwret = -1;
 	pid_t pid = fork();
 	if (pid < 0) {
diff --git a/partitions.hpp b/partitions.hpp
index 92970d9..977d798 100755
--- a/partitions.hpp
+++ b/partitions.hpp
@@ -298,6 +298,13 @@
 friend class PageManager;
 };
 
+struct users_struct {
+	std::string userId;
+	std::string userName;
+	int type;
+	bool isDecrypted;
+};
+
 class TWPartitionManager
 {
 public:
@@ -334,7 +341,8 @@
 	int Repair_By_Path(string Path, bool Display_Error);                      // Repairs a partition based on path
 	int Resize_By_Path(string Path, bool Display_Error);                      // Resizes a partition based on path
 	void Update_System_Details();                                             // Updates fstab, file systems, sizes, etc.
-	int Decrypt_Device(string Password);                                      // Attempt to decrypt any encrypted partitions
+	int Decrypt_Device(string Password, int user_id = 0);                     // Attempt to decrypt any encrypted partitions
+	void Parse_Users();                                                       // Parse FBE users
 	int usb_storage_enable(void);                                             // Enable USB storage mode
 	int usb_storage_disable(void);                                            // Disable USB storage mode
 	void Mount_All_Storage(void);                                             // Mounts all storage locations
@@ -380,6 +388,7 @@
 	bool Prepare_Repack(TWPartition* Part, const std::string& Temp_Folder_Destination, const bool Create_Backup, const std::string& Backup_Name); // Prepares an image for repacking by unpacking it to the temp folder destination
 	bool Prepare_Repack(const std::string& Source_Path, const std::string& Temp_Folder_Destination, const bool Copy_Source, const bool Create_Destination = true); // Prepares an image for repacking by unpacking it to the temp folder destination
 	bool Repack_Images(const std::string& Target_Image, const struct Repack_Options_struct& Repack_Options); // Repacks the boot image with a new kernel or a new ramdisk
+	std::vector<users_struct>* Get_Users_List();                              // Returns pointer to list of users
 
 private:
 	void Setup_Settings_Storage_Partition(TWPartition* Part);                 // Sets up settings storage
@@ -398,10 +407,13 @@
 	int mtp_write_fd;
 	pid_t tar_fork_pid;                                                       // PID of twrpTar fork
 	Backup_Method_enum Backup_Method;                                         // Method used for backup
+	void Mark_User_Decrypted(int userID);                                     // Marks given user ID in Users_List as decrypted
+	void Check_Users_Decryption_Status();                                      // Checks to see if all users are decrypted
 
 private:
 	std::vector<TWPartition*> Partitions;                                     // Vector list of all partitions
 	string Active_Slot_Display;                                               // Current Active Slot (A or B) for display purposes
+	std::vector<users_struct> Users_List;                                     // List of FBE users
 };
 
 extern TWPartitionManager PartitionManager;
diff --git a/twrp.cpp b/twrp.cpp
index 2b84cbb..22a6b8d 100755
--- a/twrp.cpp
+++ b/twrp.cpp
@@ -307,8 +307,11 @@
 
 	// Offer to decrypt if the device is encrypted
 	if (DataManager::GetIntValue(TW_IS_ENCRYPTED) != 0) {
-		if (SkipDecryption) {
-			LOGINFO("Skipping decryption\n");
+		LOGINFO("Is encrypted, do decrypt page first\n");
+	if (DataManager::GetIntValue(TW_IS_FBE))
+		DataManager::SetValue("tw_crypto_user_id", "0");
+	if (gui_startPage("decrypt", 1, 1) != 0) {
+		LOGERR("Failed to start decrypt GUI page.\n");
 		} else {
 			LOGINFO("Is encrypted, do decrypt page first\n");
 			if (gui_startPage("decrypt", 1, 1) != 0) {
@@ -329,8 +332,7 @@
 	}
 
 	// Fixup the RTC clock on devices which require it
-	if (crash_counter == 0)
-		TWFunc::Fixup_Time_On_Boot();
+	if (crash_counter == 0) TWFunc::Fixup_Time_On_Boot();
 
 	// Read the settings file
 	TWFunc::Update_Log_File();
@@ -341,7 +343,9 @@
 	// Run any outstanding OpenRecoveryScript
 	std::string cacheDir = TWFunc::get_cache_dir();
 	std::string orsFile = cacheDir + "/recovery/openrecoveryscript";
-	if ((DataManager::GetIntValue(TW_IS_ENCRYPTED) == 0 || SkipDecryption) && (TWFunc::Path_Exists(SCRIPT_FILE_TMP) || TWFunc::Path_Exists(orsFile))) {
+
+	if (TWFunc::Path_Exists(SCRIPT_FILE_TMP) ||
+	(DataManager::GetIntValue(TW_IS_ENCRYPTED) == 0 && TWFunc::Path_Exists(orsFile))) {
 		OpenRecoveryScript::Run_OpenRecoveryScript();
 	}