1

I have created an app whereby the user can save, edit and delete notes and it would be stored in the applications private storage area. the data that is being stored needs to be encrypted however I am new to programming and do not know much about how to do this so if anyone can advise please? I will put the code below for the method that is used to save the notes but for security reasons, encryption is required, what would be the easiest method to use for a beginner?

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();

    }

}

Edit: I have now added an example des encryption below the existing code it now looks like this, also how would I know the data is actually encrypted?

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();
        }
    }
}
Mel
  • 5,837
  • 10
  • 37
  • 42
Jay1
  • 29
  • 5

1 Answers1

0

DES (Data Encryption Standard) is pretty common for simple tasks like yours. There are a bunch of tutorials online for how to use it. Here's one example I've used: http://www.avajava.com/tutorials/lessons/how-do-i-encrypt-and-decrypt-files-using-des.html

There was another thread where a user shared a more advanced method, Password-Based Key Derivation Function, that is also worth trying. Here's the link: How to encrypt and salt the password using BouncyCastle API in Java?

coinbird
  • 1,202
  • 4
  • 24
  • 44
  • if i was to use the example code from that link for DES, would i create a new java class file and add it or replace the current one that i have put in this question? – Jay1 Apr 26 '17 at 13:50
  • @Jay1 You would add it to your current class. Just add in new methods (encrypt, decrypt, etc) to your class. You should be able to copy those exactly. You will need to customize the implementation for your project though. The Main method of the example should put you on the right track! – coinbird Apr 26 '17 at 14:14
  • okay, i have added the example code into the existing class below the current source code, i will edit post to show what i have done but how would i know the data is actually encrypted/decrypted? – Jay1 Apr 26 '17 at 14:41
  • If it's encrypted you should be able to open your file in notepad (or whatever) and see a bunch of garbage. It's not supposed to be human readable when it's encrypted. Then when it's decrypted you should be able to read the file again. – coinbird Apr 26 '17 at 15:15
  • ive opened the file in notepad but the code displays the same as in the application so i don't think it has been encrypted, what would i need to do? – Jay1 Apr 26 '17 at 15:52
  • It looks like you just copy and pasted the Main method. You will have to do some work to adapt the code in that Main method to work with your program. For example, the file names it comes with won't match yours. Read through the Main method, learn what it's doing, and incorporate your own data. If you don't understand everything that's happening in the Main method, try to look at the other methods you pasted and learn what they're doing. Look at the parameters they take so you can use them properly. You will have to do some research! It's not going to just be a simple full copy/paste solution. – coinbird Apr 26 '17 at 16:32