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

Android 安全編程 #00:勿在外部儲存(SD 卡)存放未加密的敏感資訊

編輯:關於 Android 程式設計

Android 提供多種保存持久化資料的方式,其中之一就是外部儲存(/sdcard、/mnt/sdcard)。外部儲存包括裝置內部的微型或標準 SD 卡、掛載到 PC 的儲存卡,以及 Android/obb 目錄。

在 Android 4.1 之前,存放於外部儲存的檔案是 world-readable(任何用戶可讀)與 world-writable(任何用戶可寫)。從 4.1 到 4.3,app 只要宣告 WRITE_EXTERNAL_STORAGE 權限即可寫入外部儲存的任意檔案。但從 4.4 開始,引入了基於目錄結構的分組與檔案模式,使 app 在外部儲存中只能在以自己套件名命名的目錄(Android/data/<package-name>/)下擁有讀寫權限,各 app 的權限被獨立開來。

上述權限限制的不足,導致寫入外部儲存的檔案可能存在被同裝置其他 app 修改與讀取的風險(Android 4.4 之前)。Android API 指南對 Storage Options 給出警告:使用者若將外部儲存掛載到 PC 或直接移除,會導致其不可用,而且沒有任何安全措施保證存放於外部儲存的檔案——所有應用都能讀寫,使用者也可隨意刪除。

因此,開發者不應在外部儲存中存放未加密的敏感資訊,因為外部儲存檔案無法保證可用性、完整性與機密性。

不符合安全要求的程式碼範例

private String filename = "myfile";
private String string = "sensitive data such as credit card number";
FileOutputStream fos = null;
try {
    File file = new File(getExternalFilesDir(TARGET_TYPE), filename);
    fos = new FileOutputStream(file, false);
    fos.write(string.getBytes());
} catch (Exception e) {
    // handle exception
} finally {
    if (fos != null) {
        try { fos.close(); } catch (IOException e) {}
    }
}

符合安全要求的解決方案 #1:保存到內部儲存

使用 openFileOutput() 在應用的 data 目錄建立檔案,並將訪問權限設為 MODE_PRIVATE,確保其他 app 無法訪問:

private String filename = "myfile";
private String string = "sensitive data such as credit card number";
FileOutputStream fos = null;
try {
    fos = openFileOutput(filename, Context.MODE_PRIVATE);
    fos.write(string.getBytes());
    fos.close();
} catch (Exception e) {
    // handle exception
}

符合安全要求的解決方案 #2:加密後再寫入外部儲存

若确需寫入外部儲存,應先對檔案內容進行加密,再進行保存,以確保機密性。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved