如何加密存储在应用程序私有存储中的数据

时间:2017-04-26 13:26:52

标签: java android encryption aes

我创建了一个应用程序,用户可以保存,编辑和删除笔记,并将其存储在应用程序专用存储区域中。存储的数据需要加密,但我是编程新手,并不知道如何做到这一点,所以如果有人可以建议吗?我将把下面的代码放在用于保存笔记的方法中,但出于安全考虑,需要加密,对于初学者来说,最简单的方法是什么?

public class Utilities {

    public static final String FILE_EXTENSION = ".bin";

    public static boolean saveNote(Context context, Notes notes){
        String fileName = String.valueOf(notes.getDateTime()) + FILE_EXTENSION;

        FileOutputStream fos;
        ObjectOutputStream oos;

        try {
            fos = context.openFileOutput(fileName, context.MODE_PRIVATE);
            oos = new ObjectOutputStream(fos);
            oos.writeObject(notes);
            oos.close();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
            return false; //tell the user something went wrong
        }
        return true;
    }

    public static ArrayList<Notes> getSavedNotes(Context context) {
        ArrayList<Notes> notes = new ArrayList<>();

        File filesDir = context.getFilesDir();
        filesDir.getAbsolutePath();
        ArrayList<String> noteFiles = new ArrayList<>();

        for(String file : filesDir.list()) {
            if(file.endsWith(FILE_EXTENSION)) {
                noteFiles.add(file);
            }
        }

        FileInputStream fis;
        ObjectInputStream ois;

        for(int i = 0; i < noteFiles.size(); i++) {
            try{
                fis = context.openFileInput(noteFiles.get(i));
                ois = new ObjectInputStream(fis);

                notes.add((Notes)ois.readObject());

                fis.close();
                ois.close();



            } catch (IOException | ClassNotFoundException e) {
                e.printStackTrace();
                return null;

            }
        }

        return notes;

    }

    public static Notes getNoteByName(Context context, String fileName) {
        File file = new File(context.getFilesDir(), fileName);
        Notes notes;

        if(file.exists()) {
            FileInputStream fis;
            ObjectInputStream ois;

            try {
                fis = context.openFileInput(fileName);
                ois = new ObjectInputStream(fis);

                notes = (Notes) ois.readObject();

                fis.close();
                ois.close();

            } catch(IOException | ClassNotFoundException e){
                e.printStackTrace();
                return null;
            }

            return notes;
        }

        return null;
    }

    public static void deleteNote(Context context, String fileName) {
        File Dir = context.getFilesDir();
        File file = new File(Dir, fileName);

        if (file.exists()) file.delete();
    }

    public static void main(String[] args) {
        try {
            String key = "squirrel123"; // needs to be at least 8 characters for DES

            FileInputStream fis = new FileInputStream("original.txt");
            FileOutputStream fos = new FileOutputStream("encrypted.txt");
            encrypt(key, fis, fos);

            FileInputStream fis2 = new FileInputStream("encrypted.txt");
            FileOutputStream fos2 = new FileOutputStream("decrypted.txt");
            decrypt(key, fis2, fos2);
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

    public static void encrypt(String key, InputStream is, OutputStream os) throws Throwable {
        encryptOrDecrypt(key, Cipher.ENCRYPT_MODE, is, os);
    }

    public static void decrypt(String key, InputStream is, OutputStream os) throws Throwable {
        encryptOrDecrypt(key, Cipher.DECRYPT_MODE, is, os);
    }

    public static void encryptOrDecrypt(String key, int mode, InputStream is, OutputStream os) throws Throwable {
        DESKeySpec dks = new DESKeySpec(key.getBytes());
        SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
        SecretKey desKey = skf.generateSecret(dks);
        Cipher cipher = Cipher.getInstance("DES"); // DES/ECB/PKCS5Padding for SunJCE

        if (mode == Cipher.ENCRYPT_MODE) {
            cipher.init(Cipher.ENCRYPT_MODE, desKey);
            CipherInputStream cis = new CipherInputStream(is, cipher);
            doCopy(cis, os);
        } else if (mode == Cipher.DECRYPT_MODE) {
            cipher.init(Cipher.DECRYPT_MODE, desKey);
            CipherOutputStream cos = new CipherOutputStream(os, cipher);
            doCopy(is, cos);
        }
    }

    public static void doCopy(InputStream is, OutputStream os) throws IOException {
        byte[] bytes = new byte[64];
        int numBytes;
        while ((numBytes = is.read(bytes)) != -1) {
            os.write(bytes, 0, numBytes);
        }
        os.flush();
        os.close();
        is.close();

    }

}

编辑:  我现在在现有代码下面添加了一个des加密示例,它现在看起来像这样,我怎么知道数据实际上是加密的?

public class Utilities {

    public static final String FILE_EXTENSION = ".bin";

    public static boolean saveNote(Context context, Notes notes){
        String fileName = String.valueOf(notes.getDateTime()) + FILE_EXTENSION;

        FileOutputStream fos;
        ObjectOutputStream oos;

        try {
            fos = context.openFileOutput(fileName, context.MODE_PRIVATE);
            oos = new ObjectOutputStream(fos);
            oos.writeObject(notes);
            oos.close();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
            return false; //tell the user something went wrong
        }
        return true;
    }

    public static ArrayList<Notes> getSavedNotes(Context context) {
        ArrayList<Notes> notes = new ArrayList<>();

        File filesDir = context.getFilesDir();
        filesDir.getAbsolutePath();
        ArrayList<String> noteFiles = new ArrayList<>();

        for(String file : filesDir.list()) {
            if(file.endsWith(FILE_EXTENSION)) {
                noteFiles.add(file);
            }
        }

        FileInputStream fis;
        ObjectInputStream ois;

        for(int i = 0; i < noteFiles.size(); i++) {
            try{
                fis = context.openFileInput(noteFiles.get(i));
                ois = new ObjectInputStream(fis);

                notes.add((Notes)ois.readObject());

                fis.close();
                ois.close();
            } catch (IOException | ClassNotFoundException e) {
                e.printStackTrace();
                return null;
            }
        }

        return notes;
    }

    public static Notes getNoteByName(Context context, String fileName) {
        File file = new File(context.getFilesDir(), fileName);
        Notes notes;

        if(file.exists()) {
            FileInputStream fis;
            ObjectInputStream ois;

            try {
                fis = context.openFileInput(fileName);
                ois = new ObjectInputStream(fis);

                notes = (Notes) ois.readObject();

                fis.close();
                ois.close();
            } catch(IOException | ClassNotFoundException e){
                e.printStackTrace();
                return null;
            }

            return notes;
        }

        return null;
    }

    public static void deleteNote(Context context, String fileName) {
        File Dir = context.getFilesDir();
        File file = new File(Dir, fileName);

        if(file.exists()) {
            file.delete();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

对于像您这样的简单任务,DES(数据加密标准)非常常见。网上有很多关于如何使用它的教程。以下是我使用过的一个例子:http://www.avajava.com/tutorials/lessons/how-do-i-encrypt-and-decrypt-files-using-des.html

还有另一个线程,用户共享更高级的方法,基于密码的密钥派生函数,这也是值得尝试的。这是链接:How to encrypt and salt the password using BouncyCastle API in Java?

相关问题