Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 保存使用者帳號密碼的三種作法與它們的取捨

編輯:關於 Android 程式設計

登入功能幾乎是每個 App 的標配,而「記住我」則是使用者體驗的關鍵——下次打開不必再敲一次帳密。Android 上常見的實素有/plain 文字檔、Properties 屬性檔、以及 SharedPreferences 三種,各自的適用情境與風險並不相同。

第一種:純文字檔

最直觀的做法是把帳號與密碼用某個分隔字串串接後寫入檔案:

public static boolean saveUserInfo(Context context, String username, String password) {
    try {
        // 用 Context 取得 App 私有目錄,不要寫死絕對路徑
        File file = new File(context.getFilesDir(), "userinfo.txt");
        FileOutputStream fos = new FileOutputStream(file);
        fos.write((username + "##" + password).getBytes());
        fos.close();
        return true;
    } catch (Exception e) {
        throw new RuntimeException();
    }
}

讀回時用 BufferedReader 逐行取出,再以 ## 切分,分別塞進 Map 供呼叫端使用:

public static Map<String, Object> getTxtFileInfo(Context context) {
    try {
        File file = new File(context.getFilesDir(), "userinfo.txt");
        FileInputStream fis = new FileInputStream(file);
        BufferedReader br = new BufferedReader(new InputStreamReader(fis));
        String content = br.readLine();

        Map<String, Object> map = new HashMap<String, Object>();
        String[] contents = content.split("##");
        map.put("username", contents[0]);
        map.put("password", contents[1]);

        fis.close();
        br.close();
        return map;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

寫死路徑 new File("data/data/com.example.xxx/info.txt") 是很多教學會犯的錯——一旦改了套件名稱或換裝置,路徑就失效。正確作法永遠是透過 context.getFilesDir() 取得私有目錄。

而這個方案真正的致命缺陷在於分隔符號:如果使用者密碼本身含有 #,切分出來的第二段就會是殘缺的密碼。這正是下一種方案存在的理由。

第二種:Properties 屬性檔

Java 標準的 Properties 以 key-value 成對存放,不必自己設計分隔規則,也不會有跳脫字元的困擾:

public static boolean saveProUserInfo(Context context, String username, String password) {
    try {
        File file = new File(context.getFilesDir(), "info.properties");
        FileOutputStream fos = new FileOutputStream(file);

        Properties pro = new Properties();
        pro.setProperty("username", username);
        pro.setProperty("password", password);
        pro.store(fos, "info.properties");

        fos.close();
        return true;
    } catch (Exception e) {
        throw new RuntimeException();
    }
}

public static Properties getProObject(Context context) {
    try {
        File file = new File(context.getFilesDir(), "info.properties");
        FileInputStream fis = new FileInputStream(file);
        Properties pro = new Properties();
        pro.load(fis);
        fis.close();
        return pro;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

呼叫端在啟動時讀取並回填輸入框:

Properties pro = LoginService.getProObject(this);
if (null != pro) {
    String username = pro.getProperty("username");
    String password = pro.getProperty("password");
    if (!TextUtils.isEmpty(username) && !TextUtils.isEmpty(password)) {
        etUsername.setText(username);
        etPassword.setText(password);
    }
}

第三種:SharedPreferences

這是 Android 官方為「少量鍵值設定」設計的元件,底層其實就是 XML 檔,但由 framework 負責讀寫與快取,API 最簡潔:

public static void saveLoginInfo(Context context, String username, String password) {
    SharedPreferences sharedPre = context.getSharedPreferences("config", context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPre.edit();
    editor.putString("username", username);
    editor.putString("password", password);
    editor.commit();
}

讀取:

SharedPreferences sharedPre = getSharedPreferences("config", MODE_PRIVATE);
String username = sharedPre.getString("username", "");
String password = sharedPre.getString("password", "");

寫到外部儲存空間

前兩種檔案也可以改放到 SD 卡,透過 Environment 取得外部儲存路徑:

File file = new File(Environment.getExternalStorageDirectory(), "info.properties");

或使用絕對路徑:

File file = new File("/sdcard/info.properties");

並在 AndroidManifest.xml 加上權限:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

一個必須提出的提醒

以上三種方式都是明文儲存。任何取得裝置 root 權限、或透過 ADB backup 的第三方,都能直接讀出密碼。實務上的建議是:

  • 只記住「使用者名稱」與一個「重新登入用的 token」,不要把密碼落地。
  • 若產品需求真的必須離線保存憑證,至少使用 Android Keystore 產生金鑰,以 AES 加密後再寫入 SharedPreferences。
  • 把檔案放在 getFilesDir() 或 MODE_PRIVATE 的 SharedPreferences(App 私有、其他 App 無法存取),而不要寫到外部儲存空間。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved