1 В избранное 0 Ответвления 0

OSCHINA-MIRROR/wizardforcel-android-app-sec-guidebook

Клонировать/Скачать
4.6.1.1.md 7.5 КБ
Копировать Редактировать Web IDE Исходные данные Просмотреть построчно История
gitlife-traslator Отправлено 27.11.2024 20:24 c13bfb7

4.6.1.1 Использование приватных файлов

В этом случае файлы, которые используются, могут быть прочитаны или записаны только в одном приложении, и это один из самых безопасных способов использования файлов. В принципе, независимо от того, является ли информация, хранящаяся в файле, общедоступной, следует по возможности использовать приватные файлы, а при обмене необходимой информацией с другими приложениями следует использовать другое приложение на Android (контент-провайдер, сервис).

Основные моменты:

  1. Файл должен быть создан в каталоге приложения.

  2. Права доступа к файлу должны быть установлены как приватные, чтобы другие приложения не могли его использовать.

  3. Можно хранить конфиденциальную информацию.

  4. Для информации, хранящейся в файле, необходимо тщательно и безопасно обрабатывать данные файла.

PrivateFileActivity.java

package org.jssec.android.file.privatefile;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class PrivateFileActivity extends Activity {
    private TextView mFileView;
    private static final String FILE_NAME = "private_file.dat";
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.file);
        mFileView = (TextView) findViewById(R.id.file_view);
    }
    
    /**
    * Create file process
    *
    * @param view
    */
    public void onCreateFileClick(View view) {
        FileOutputStream fos = null;
        try {
            // *** POINT 1 *** Files must be created in application directory.
            // *** POINT 2 *** The access privilege of file must be set private mode in order not to be used by other applications.
            fos = openFileOutput(FILE_NAME, MODE_PRIVATE);
            // *** POINT 3 *** Sensitive information can be stored.
            // *** POINT 4 *** Regarding the information to be stored in files, handle file data carefully and securely.
            // Omitted, since this is a sample. Please refer to "3.2 Handling Input Data Carefully and Securely."
            fos.write(new String("Not sensotive information (File Activity)¥n").getBytes());
        } catch (FileNotFoundException e) {
            mFileView.setText(R.string.file_view);
        } catch (IOException e) {
            android.util.Log.e("PrivateFileActivity", "failed to read file");
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    android.util.Log.e("PrivateFileActivity", "failed to close file");
                }
            }
        }
        finish();
    }
    
    /**
    * Read file process
    *
    * @param view
    */
    public void onReadFileClick(View view) {
        FileInputStream fis = null;
        try {
            fis = openFileInput(FILE_NAME);
            byte[] data = new byte[(int) fis.getChannel().size()];
            fis.read(data);
            String str = new String(data);
            mFileView.setText(str);
        } catch (FileNotFoundException e) {
            mFileView.setText(R.string.file_view);
        } catch (IOException e) {
            android.util.Log.e("PrivateFileActivity", "failed to read file");
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    android.util.Log.e("PrivateFileActivity", "failed to close file");
                }
            }
        }
    }
    
    /**
    * Delete file process
    *
    * @param view
    */
    public void onDeleteFileClick(View view) {
        File file = new File(this.getFilesDir() + "/" + FILE_NAME);
        file.delete();
        mFileView.setText(R.string.file_view);
    }
}

PrivateUserActivity.java

package org.jssec.android.file.privatefile;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class PrivateUserActivity extends Activity {

    private TextView mFileView;
    private static final String FILE_NAME = "private_file.dat";
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
``` Данный фрагмент написан на языке Java.

Вот его перевод на русский язык:

setContentView(R.layout.user); mFileView = (TextView) findViewById(R.id.file_view); }

private void callFileActivity() { Intent intent = new Intent(); intent.setClass(this, PrivateFileActivity.class); startActivity(intent); }

/**

  • Call file Activity process
  • @param view */ public void onCallFileActivityClick(View view) { callFileActivity(); }

/**

  • Read file process
  • @param view */ public void onReadFileClick(View view) { FileInputStream fis = null; try { fis = openFileInput(FILE_NAME); byte[] data = new byte[(int) fis.getChannel().size()]; fis.read(data); // *** POINT 4 *** Regarding the information to be stored in files, handle file data carefully and securely. // Omitted, since this is a sample. Please refer to "3.2 Handling Input Data Carefully and Securely." String str = new String(data); mFileView.setText(str); } catch (FileNotFoundException e) { mFileView.setText(R.string.file_view); } catch (IOException e) { android.util.Log.e("PrivateUserActivity", "failed to read file"); } finally { if (fis != null) { try { fis.close(); } catch (IOException e) { android.util.Log.e("PrivateUserActivity", "failed to close file"); } } } }

/**

  • Rewrite file process
  • @param view */ public void onWriteFileClick(View view) { FileOutputStream fos = null; try { // *** POINT 1 *** Files must be created in application directory. // *** POINT 2 *** The access privilege of file must be set private mode in order not to be used by other applications. fos = openFileOutput(FILE_NAME, MODE_APPEND); // *** POINT 3 *** Sensitive information can be stored. // *** POINT 4 *** Regarding the information to be stored in files, handle file data carefully and securely. // Omitted, since this is a sample. Please refer to "3.2 Handling Input Data Carefully and Securely." fos.write(new String("Sensitive information (User Activity)¥n").getBytes()); } catch (FileNotFoundException e) { mFileView.setText(R.string.file_view); } catch (IOException e) { android.util.Log.e("PrivateUserActivity", "failed to read file"); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { android.util.Log.e("PrivateUserActivity", "failed to close file"); } } } callFileActivity(); }

Опубликовать ( 0 )

Вы можете оставить комментарий после Вход в систему

1
https://api.gitlife.ru/oschina-mirror/wizardforcel-android-app-sec-guidebook.git
git@api.gitlife.ru:oschina-mirror/wizardforcel-android-app-sec-guidebook.git
oschina-mirror
wizardforcel-android-app-sec-guidebook
wizardforcel-android-app-sec-guidebook
master