0

I am new to Android, and I am trying to encrypt and decrypt a file and want to display in Android device after decrypt.

Here I am downloading the file from the URL and storing in SD card and I don't now how to encrypt the file and then store in SD card and file size may be more then 20MB.

Code:

File downloadFile(String dwnload_file_path) {
    File file = null;
    try {
        String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
        File folder = new File(extStorageDirectory, "SampleFolder");
        folder.mkdir();

        file = new File(folder, dest_file_path);

        try{
            file.createNewFile();
        }catch (IOException e){
            e.printStackTrace();
        }
      
        URL url = new URL(dwnload_file_path);
        HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
        urlConnection.connect();

        InputStream inputStream = urlConnection.getInputStream();
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        int totalSize = urlConnection.getContentLength();

        byte[] buffer = new byte[MEGABYTE];
        int bufferLength = 0;
        while((bufferLength = inputStream.read(buffer))>0 ){
            fileOutputStream.write(buffer, 0, bufferLength);
        }
        fileOutputStream.close();
        //ToastManager.toast(this, "Download Complete. Open PDF Application installed in the device.");
    } catch (final MalformedURLException e) {
        //ToastManager.toast(this, "Some error occured. Press try again.");
    } catch (final IOException e) {
        //ToastManager.toast(this, "Some error occured. Press try again.");
    } catch (final Exception e) {
        //ToastManager.toast(this, "Failed to download image. Please check your internet connection.");
    }
    return file;
}

Here I am displaying the file in Android device but after decrypting the file, how can I display it?

Code:

File pdfFile = new File(Environment.getExternalStorageDirectory() + "/SampleFolder/" + "Sample."pref.getString(Constants.PrefConstants.PATH_NAME));
            File f = new File(pdfFile.toString());
            if(f.exists()) {
                    Uri path = Uri.fromFile(pdfFile);
                    Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
                    pdfIntent.setDataAndType(path, pref.getString(Constants.PrefConstants.PATH_NAME_APP));
                    //pdfIntent.setFlags(Intent. FLAG_ACTIVITY_CLEAR_TOP);
                    pdfIntent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                    startActivity(pdfIntent);
                } else {
                    //uiManager.execute(Constants.Commands.REQGET_INSTRUCTIONS_SCREEN,null);
                    ToastManager.toast(getApplicationContext(), "No data available...");
                }

How can I resolve this issue?

halfer
  • 19,824
  • 17
  • 99
  • 186
Atul Dhanuka
  • 1,453
  • 5
  • 20
  • 56
  • 3
    Possible duplicate of [How to encrypt and decrypt file in Android?](http://stackoverflow.com/questions/4275311/how-to-encrypt-and-decrypt-file-in-android) – Artjom B. Oct 18 '16 at 05:24

1 Answers1

-1

You need to use the SecretKeySpec library . Example of encrypt method

static void encrypt() throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
    // Here you read the cleartext.
    FileInputStream fis = new FileInputStream("SampleFolder/yourfilename");
    // This stream write the encrypted text. This stream will be wrapped by another stream.
    FileOutputStream fos = new FileOutputStream("SampleFolder/yourencryptedfilename");

    // Length is 16 byte
    // Careful when taking user input!!! https://stackoverflow.com/a/3452620/1188357
    SecretKeySpec sks = new SecretKeySpec("MyDifficultPassw".getBytes(), "AES");
    // Create cipher
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.ENCRYPT_MODE, sks);
    // Wrap the output stream
    CipherOutputStream cos = new CipherOutputStream(fos, cipher);
    // Write bytes
    int b;
    byte[] d = new byte[8];
    while((b = fis.read(d)) != -1) {
        cos.write(d, 0, b);
    }
    // Flush and close streams.
    cos.flush();
    cos.close();
    fis.close();
}

For decrypt method see the link below. More details : How to encrypt file from SD card using AES in Android?

Community
  • 1
  • 1
Ashish Rawat
  • 5,541
  • 1
  • 20
  • 17
  • General advice: **Always use a fully qualified Cipher string.** `Cipher.getInstance("AES");` may result in different ciphers depending on the default security provider. It most likely results in `"AES/ECB/PKCS5Padding"`, but it doesn't have to be. If it changes, you'll lose compatibility between different JVMs. For reference: [Java default Crypto/AES behavior](http://stackoverflow.com/q/6258047/1816580) – Artjom B. Oct 18 '16 at 05:05
  • **Never use [ECB mode](http://crypto.stackexchange.com/q/14487/13022)**. It's deterministic and therefore not semantically secure. You should at the very least use a randomized mode like [CBC](http://crypto.stackexchange.com/q/22260/13022) or [CTR](http://crypto.stackexchange.com/a/2378/13022). It is better to authenticate your ciphertexts so that attacks like a [padding oracle attack](http://crypto.stackexchange.com/q/18185/13022) are not possible. This can be done with authenticated modes like GCM or EAX, or with an [encrypt-then-MAC](http://crypto.stackexchange.com/q/202/13022) scheme. – Artjom B. Oct 18 '16 at 05:06
  • It is frowned upon to copy code from some other answer. If you think this is a duplicate, you should have flagged the question as a duplicate. – Artjom B. Oct 18 '16 at 05:08
  • The question is similar but can't say duplicate, if i only paste link, that also is forbidden, so i have put some code customised to the answer and link..:P – Ashish Rawat Oct 18 '16 at 05:30