]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/activities/ImportExportActivity.java
Update the download snackbars to be more descriptive. https://redmine.stoutner.com...
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / activities / ImportExportActivity.java
1 /*
2  * Copyright © 2018-2021 Soren Stoutner <soren@stoutner.com>.
3  *
4  * This file is part of Privacy Browser <https://www.stoutner.com/privacy-browser>.
5  *
6  * Privacy Browser is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * Privacy Browser is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with Privacy Browser.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 package com.stoutner.privacybrowser.activities;
21
22 import android.app.Activity;
23 import android.content.Intent;
24 import android.content.SharedPreferences;
25 import android.content.pm.PackageManager;
26 import android.net.Uri;
27 import android.os.Build;
28 import android.os.Bundle;
29 import android.os.Handler;
30 import android.preference.PreferenceManager;
31 import android.text.Editable;
32 import android.text.TextWatcher;
33 import android.view.View;
34 import android.view.WindowManager;
35 import android.widget.AdapterView;
36 import android.widget.ArrayAdapter;
37 import android.widget.Button;
38 import android.widget.EditText;
39 import android.widget.LinearLayout;
40 import android.widget.RadioButton;
41 import android.widget.Spinner;
42 import android.widget.TextView;
43
44 import androidx.annotation.NonNull;
45 import androidx.appcompat.app.ActionBar;
46 import androidx.appcompat.app.AppCompatActivity;
47 import androidx.appcompat.widget.Toolbar;
48 import androidx.cardview.widget.CardView;
49 import androidx.core.content.FileProvider;
50
51 import com.google.android.material.snackbar.Snackbar;
52 import com.google.android.material.textfield.TextInputLayout;
53
54 import com.stoutner.privacybrowser.BuildConfig;
55 import com.stoutner.privacybrowser.R;
56 import com.stoutner.privacybrowser.helpers.ImportExportDatabaseHelper;
57
58 import java.io.File;
59 import java.io.FileInputStream;
60 import java.io.FileNotFoundException;
61 import java.io.FileOutputStream;
62 import java.io.InputStream;
63 import java.io.OutputStream;
64 import java.nio.charset.StandardCharsets;
65 import java.security.MessageDigest;
66 import java.security.SecureRandom;
67 import java.util.Arrays;
68
69 import javax.crypto.Cipher;
70 import javax.crypto.CipherInputStream;
71 import javax.crypto.CipherOutputStream;
72 import javax.crypto.spec.GCMParameterSpec;
73 import javax.crypto.spec.SecretKeySpec;
74
75 public class ImportExportActivity extends AppCompatActivity {
76     // Define the encryption constants.
77     private final int NO_ENCRYPTION = 0;
78     private final int PASSWORD_ENCRYPTION = 1;
79     private final int OPENPGP_ENCRYPTION = 2;
80
81     // Define the activity result constants.
82     private final int BROWSE_RESULT_CODE = 0;
83     private final int OPENPGP_IMPORT_RESULT_CODE = 1;
84     private final int OPENPGP_EXPORT_RESULT_CODE = 2;
85
86     // Define the saved instance state constants.
87     private final String ENCRYPTION_PASSWORD_TEXTINPUTLAYOUT_VISIBILITY = "encryption_password_textinputlayout_visibility";
88     private final String KITKAT_PASSWORD_ENCRYPTED_TEXTVIEW_VISIBILITY = "kitkat_password_encrypted_textview_visibility";
89     private final String OPEN_KEYCHAIN_REQUIRED_TEXTVIEW_VISIBILITY = "open_keychain_required_textview_visibility";
90     private final String FILE_LOCATION_CARD_VIEW = "file_location_card_view";
91     private final String FILE_NAME_LINEARLAYOUT_VISIBILITY = "file_name_linearlayout_visibility";
92     private final String OPEN_KEYCHAIN_IMPORT_INSTRUCTIONS_TEXTVIEW_VISIBILITY = "open_keychain_import_instructions_textview_visibility";
93     private final String IMPORT_EXPORT_BUTTON_VISIBILITY = "import_export_button_visibility";
94     private final String FILE_NAME_TEXT = "file_name_text";
95     private final String IMPORT_EXPORT_BUTTON_TEXT = "import_export_button_text";
96
97     // Define the class views.
98     Spinner encryptionSpinner;
99     TextInputLayout encryptionPasswordTextInputLayout;
100     EditText encryptionPasswordEditText;
101     TextView kitKatPasswordEncryptionTextView;
102     TextView openKeychainRequiredTextView;
103     CardView fileLocationCardView;
104     RadioButton importRadioButton;
105     LinearLayout fileNameLinearLayout;
106     EditText fileNameEditText;
107     TextView openKeychainImportInstructionsTextView;
108     Button importExportButton;
109
110     // Define the class variables.
111     private boolean openKeychainInstalled;
112     private File temporaryPgpEncryptedImportFile;
113     private File temporaryPreEncryptedExportFile;
114
115     @Override
116     public void onCreate(Bundle savedInstanceState) {
117         // Get a handle for the shared preferences.
118         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
119
120         // Get the screenshot preference.
121         boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
122
123         // Disable screenshots if not allowed.
124         if (!allowScreenshots) {
125             getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
126         }
127
128         // Set the theme.
129         setTheme(R.style.PrivacyBrowser);
130
131         // Run the default commands.
132         super.onCreate(savedInstanceState);
133
134         // Set the content view.
135         setContentView(R.layout.import_export_coordinatorlayout);
136
137         // Set the support action bar.
138         Toolbar toolbar = findViewById(R.id.import_export_toolbar);
139         setSupportActionBar(toolbar);
140
141         // Get a handle for the action bar.
142         ActionBar actionBar = getSupportActionBar();
143
144         // Remove the incorrect lint warning that the action bar might be null.
145         assert actionBar != null;
146
147         // Display the home arrow on the support action bar.
148         actionBar.setDisplayHomeAsUpEnabled(true);
149
150         // Find out if the system is running KitKat
151         boolean runningKitKat = (Build.VERSION.SDK_INT == 19);
152
153         // Find out if OpenKeychain is installed.
154         try {
155             openKeychainInstalled = !getPackageManager().getPackageInfo("org.sufficientlysecure.keychain", 0).versionName.isEmpty();
156         } catch (PackageManager.NameNotFoundException exception) {
157             openKeychainInstalled = false;
158         }
159
160         // Get handles for the views that need to be modified.
161         encryptionSpinner = findViewById(R.id.encryption_spinner);
162         encryptionPasswordTextInputLayout = findViewById(R.id.encryption_password_textinputlayout);
163         encryptionPasswordEditText = findViewById(R.id.encryption_password_edittext);
164         kitKatPasswordEncryptionTextView = findViewById(R.id.kitkat_password_encryption_textview);
165         openKeychainRequiredTextView = findViewById(R.id.openkeychain_required_textview);
166         fileLocationCardView = findViewById(R.id.file_location_cardview);
167         importRadioButton = findViewById(R.id.import_radiobutton);
168         RadioButton exportRadioButton = findViewById(R.id.export_radiobutton);
169         fileNameLinearLayout = findViewById(R.id.file_name_linearlayout);
170         fileNameEditText = findViewById(R.id.file_name_edittext);
171         openKeychainImportInstructionsTextView = findViewById(R.id.openkeychain_import_instructions_textview);
172         importExportButton = findViewById(R.id.import_export_button);
173
174         // Create an array adapter for the spinner.
175         ArrayAdapter<CharSequence> encryptionArrayAdapter = ArrayAdapter.createFromResource(this, R.array.encryption_type, R.layout.spinner_item);
176
177         // Set the drop down view resource on the spinner.
178         encryptionArrayAdapter.setDropDownViewResource(R.layout.spinner_dropdown_items);
179
180         // Set the array adapter for the spinner.
181         encryptionSpinner.setAdapter(encryptionArrayAdapter);
182
183         // Update the UI when the spinner changes.
184         encryptionSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
185             @Override
186             public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
187                 switch (position) {
188                     case NO_ENCRYPTION:
189                         // Hide the unneeded layout items.
190                         encryptionPasswordTextInputLayout.setVisibility(View.GONE);
191                         kitKatPasswordEncryptionTextView.setVisibility(View.GONE);
192                         openKeychainRequiredTextView.setVisibility(View.GONE);
193                         openKeychainImportInstructionsTextView.setVisibility(View.GONE);
194
195                         // Show the file location card.
196                         fileLocationCardView.setVisibility(View.VISIBLE);
197
198                         // Show the file name linear layout if either import or export is checked.
199                         if (importRadioButton.isChecked() || exportRadioButton.isChecked()) {
200                             fileNameLinearLayout.setVisibility(View.VISIBLE);
201                         }
202
203                         // Reset the text of the import button, which may have been changed to `Decrypt`.
204                         if (importRadioButton.isChecked()) {
205                             importExportButton.setText(R.string.import_button);
206                         }
207
208                         // Enable the import/export button if the file name is populated.
209                         importExportButton.setEnabled(!fileNameEditText.getText().toString().isEmpty());
210                         break;
211
212                     case PASSWORD_ENCRYPTION:
213                         if (runningKitKat) {
214                             // Show the KitKat password encryption message.
215                             kitKatPasswordEncryptionTextView.setVisibility(View.VISIBLE);
216
217                             // Hide the OpenPGP required text view and the file location card.
218                             openKeychainRequiredTextView.setVisibility(View.GONE);
219                             fileLocationCardView.setVisibility(View.GONE);
220                         } else {
221                             // Hide the OpenPGP layout items.
222                             openKeychainRequiredTextView.setVisibility(View.GONE);
223                             openKeychainImportInstructionsTextView.setVisibility(View.GONE);
224
225                             // Show the password encryption layout items.
226                             encryptionPasswordTextInputLayout.setVisibility(View.VISIBLE);
227
228                             // Show the file location card.
229                             fileLocationCardView.setVisibility(View.VISIBLE);
230
231                             // Show the file name linear layout if either import or export is checked.
232                             if (importRadioButton.isChecked() || exportRadioButton.isChecked()) {
233                                 fileNameLinearLayout.setVisibility(View.VISIBLE);
234                             }
235
236                             // Reset the text of the import button, which may have been changed to `Decrypt`.
237                             if (importRadioButton.isChecked()) {
238                                 importExportButton.setText(R.string.import_button);
239                             }
240
241                             // Enable the import/button if both the password and the file name are populated.
242                             importExportButton.setEnabled(!fileNameEditText.getText().toString().isEmpty() && !encryptionPasswordEditText.getText().toString().isEmpty());
243                         }
244                         break;
245
246                     case OPENPGP_ENCRYPTION:
247                         // Hide the password encryption layout items.
248                         encryptionPasswordTextInputLayout.setVisibility(View.GONE);
249                         kitKatPasswordEncryptionTextView.setVisibility(View.GONE);
250
251                         // Updated items based on the installation status of OpenKeychain.
252                         if (openKeychainInstalled) {  // OpenKeychain is installed.
253                             // Show the file location card.
254                             fileLocationCardView.setVisibility(View.VISIBLE);
255
256                             if (importRadioButton.isChecked()) {
257                                 // Show the file name linear layout and the OpenKeychain import instructions.
258                                 fileNameLinearLayout.setVisibility(View.VISIBLE);
259                                 openKeychainImportInstructionsTextView.setVisibility(View.VISIBLE);
260
261                                 // Set the text of the import button to be `Decrypt`.
262                                 importExportButton.setText(R.string.decrypt);
263
264                                 // Enable the import button if the file name is populated.
265                                 importExportButton.setEnabled(!fileNameEditText.getText().toString().isEmpty());
266                             } else if (exportRadioButton.isChecked()) {
267                                 // Hide the file name linear layout and the OpenKeychain import instructions.
268                                 fileNameLinearLayout.setVisibility(View.GONE);
269                                 openKeychainImportInstructionsTextView.setVisibility(View.GONE);
270
271                                 // Enable the export button.
272                                 importExportButton.setEnabled(true);
273                             }
274                         } else {  // OpenKeychain is not installed.
275                             // Show the OpenPGP required layout item.
276                             openKeychainRequiredTextView.setVisibility(View.VISIBLE);
277
278                             // Hide the file location card.
279                             fileLocationCardView.setVisibility(View.GONE);
280                         }
281                         break;
282                 }
283             }
284
285             @Override
286             public void onNothingSelected(AdapterView<?> parent) {
287
288             }
289         });
290
291         // Update the status of the import/export button when the password changes.
292         encryptionPasswordEditText.addTextChangedListener(new TextWatcher() {
293             @Override
294             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
295                 // Do nothing.
296             }
297
298             @Override
299             public void onTextChanged(CharSequence s, int start, int before, int count) {
300                 // Do nothing.
301             }
302
303             @Override
304             public void afterTextChanged(Editable s) {
305                 // Enable the import/export button if both the file string and the password are populated.
306                 importExportButton.setEnabled(!fileNameEditText.getText().toString().isEmpty() && !encryptionPasswordEditText.getText().toString().isEmpty());
307             }
308         });
309
310         // Update the UI when the file name EditText changes.
311         fileNameEditText.addTextChangedListener(new TextWatcher() {
312             @Override
313             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
314                 // Do nothing.
315             }
316
317             @Override
318             public void onTextChanged(CharSequence s, int start, int before, int count) {
319                 // Do nothing.
320             }
321
322             @Override
323             public void afterTextChanged(Editable s) {
324                 // Adjust the UI according to the encryption spinner position.
325                 if (encryptionSpinner.getSelectedItemPosition() == PASSWORD_ENCRYPTION) {
326                     // Enable the import/export button if both the file name and the password are populated.
327                     importExportButton.setEnabled(!fileNameEditText.getText().toString().isEmpty() && !encryptionPasswordEditText.getText().toString().isEmpty());
328                 } else {
329                     // Enable the export button if the file name is populated.
330                     importExportButton.setEnabled(!fileNameEditText.getText().toString().isEmpty());
331                 }
332             }
333         });
334
335         // Check to see if the activity has been restarted.
336         if (savedInstanceState == null) {  // The app has not been restarted.
337             // Initially hide the unneeded views.
338             encryptionPasswordTextInputLayout.setVisibility(View.GONE);
339             kitKatPasswordEncryptionTextView.setVisibility(View.GONE);
340             openKeychainRequiredTextView.setVisibility(View.GONE);
341             fileNameLinearLayout.setVisibility(View.GONE);
342             openKeychainImportInstructionsTextView.setVisibility(View.GONE);
343             importExportButton.setVisibility(View.GONE);
344         } else {  // The app has been restarted.
345             // Restore the visibility of the views.
346             encryptionPasswordTextInputLayout.setVisibility(savedInstanceState.getInt(ENCRYPTION_PASSWORD_TEXTINPUTLAYOUT_VISIBILITY));
347             kitKatPasswordEncryptionTextView.setVisibility(savedInstanceState.getInt(KITKAT_PASSWORD_ENCRYPTED_TEXTVIEW_VISIBILITY));
348             openKeychainRequiredTextView.setVisibility(savedInstanceState.getInt(OPEN_KEYCHAIN_REQUIRED_TEXTVIEW_VISIBILITY));
349             fileLocationCardView.setVisibility(savedInstanceState.getInt(FILE_LOCATION_CARD_VIEW));
350             fileNameLinearLayout.setVisibility(savedInstanceState.getInt(FILE_NAME_LINEARLAYOUT_VISIBILITY));
351             openKeychainImportInstructionsTextView.setVisibility(savedInstanceState.getInt(OPEN_KEYCHAIN_IMPORT_INSTRUCTIONS_TEXTVIEW_VISIBILITY));
352             importExportButton.setVisibility(savedInstanceState.getInt(IMPORT_EXPORT_BUTTON_VISIBILITY));
353
354             // Restore the text.
355             fileNameEditText.post(() -> fileNameEditText.setText(savedInstanceState.getString(FILE_NAME_TEXT)));
356             importExportButton.setText(savedInstanceState.getString(IMPORT_EXPORT_BUTTON_TEXT));
357         }
358     }
359
360     @Override
361     public void onSaveInstanceState (@NonNull Bundle savedInstanceState) {
362         // Run the default commands.
363         super.onSaveInstanceState(savedInstanceState);
364
365         // Save the visibility of the views.
366         savedInstanceState.putInt(ENCRYPTION_PASSWORD_TEXTINPUTLAYOUT_VISIBILITY, encryptionPasswordTextInputLayout.getVisibility());
367         savedInstanceState.putInt(KITKAT_PASSWORD_ENCRYPTED_TEXTVIEW_VISIBILITY, kitKatPasswordEncryptionTextView.getVisibility());
368         savedInstanceState.putInt(OPEN_KEYCHAIN_REQUIRED_TEXTVIEW_VISIBILITY, openKeychainRequiredTextView.getVisibility());
369         savedInstanceState.putInt(FILE_LOCATION_CARD_VIEW, fileLocationCardView.getVisibility());
370         savedInstanceState.putInt(FILE_NAME_LINEARLAYOUT_VISIBILITY, fileNameLinearLayout.getVisibility());
371         savedInstanceState.putInt(OPEN_KEYCHAIN_IMPORT_INSTRUCTIONS_TEXTVIEW_VISIBILITY, openKeychainImportInstructionsTextView.getVisibility());
372         savedInstanceState.putInt(IMPORT_EXPORT_BUTTON_VISIBILITY, importExportButton.getVisibility());
373
374         // Save the text.
375         savedInstanceState.putString(FILE_NAME_TEXT, fileNameEditText.getText().toString());
376         savedInstanceState.putString(IMPORT_EXPORT_BUTTON_TEXT, importExportButton.getText().toString());
377     }
378
379     public void onClickRadioButton(View view) {
380         // Get the current file name.
381         String fileNameString = fileNameEditText.getText().toString();
382
383         // Convert the file name string to a file.
384         File file = new File(fileNameString);
385
386         // Check to see if import or export was selected.
387         if (view.getId() == R.id.import_radiobutton) {  // The import radio button is selected.
388             // Check to see if OpenPGP encryption is selected.
389             if (encryptionSpinner.getSelectedItemPosition() == OPENPGP_ENCRYPTION) {  // OpenPGP encryption selected.
390                 // Show the OpenKeychain import instructions.
391                 openKeychainImportInstructionsTextView.setVisibility(View.VISIBLE);
392
393                 // Set the text on the import/export button to be `Decrypt`.
394                 importExportButton.setText(R.string.decrypt);
395             } else {  // OpenPGP encryption not selected.
396                 // Hide the OpenKeychain import instructions.
397                 openKeychainImportInstructionsTextView.setVisibility(View.GONE);
398
399                 // Set the text on the import/export button to be `Import`.
400                 importExportButton.setText(R.string.import_button);
401             }
402
403             // Display the file name views.
404             fileNameLinearLayout.setVisibility(View.VISIBLE);
405             importExportButton.setVisibility(View.VISIBLE);
406
407             // Check to see if the file exists.
408             if (file.exists()) {  // The file exists.
409                 // Check to see if password encryption is selected.
410                 if (encryptionSpinner.getSelectedItemPosition() == PASSWORD_ENCRYPTION) {  // Password encryption is selected.
411                     // Enable the import button if the encryption password is populated.
412                     importExportButton.setEnabled(!encryptionPasswordEditText.getText().toString().isEmpty());
413                 } else {  // Password encryption is not selected.
414                     // Enable the import/decrypt button.
415                     importExportButton.setEnabled(true);
416                 }
417             } else {  // The file does not exist.
418                 // Disable the import/decrypt button.
419                 importExportButton.setEnabled(false);
420             }
421         } else {  // The export radio button is selected.
422             // Hide the OpenKeychain import instructions.
423             openKeychainImportInstructionsTextView.setVisibility(View.GONE);
424
425             // Set the text on the import/export button to be `Export`.
426             importExportButton.setText(R.string.export);
427
428             // Show the import/export button.
429             importExportButton.setVisibility(View.VISIBLE);
430
431             // Check to see if OpenPGP encryption is selected.
432             if (encryptionSpinner.getSelectedItemPosition() == OPENPGP_ENCRYPTION) {  // OpenPGP encryption is selected.
433                 // Hide the file name views.
434                 fileNameLinearLayout.setVisibility(View.GONE);
435
436                 // Enable the export button.
437                 importExportButton.setEnabled(true);
438             } else {  // OpenPGP encryption is not selected.
439                 // Show the file name view.
440                 fileNameLinearLayout.setVisibility(View.VISIBLE);
441
442                 // Check the encryption type.
443                 if (encryptionSpinner.getSelectedItemPosition() == NO_ENCRYPTION) {  // No encryption is selected.
444                     // Enable the export button if the file name is populated.
445                     importExportButton.setEnabled(!fileNameString.isEmpty());
446                 } else {  // Password encryption is selected.
447                     // Enable the export button if the file name and the password are populated.
448                     importExportButton.setEnabled(!fileNameString.isEmpty() && !encryptionPasswordEditText.getText().toString().isEmpty());
449                 }
450             }
451         }
452     }
453
454     public void browse(View view) {
455         // Check to see if import or export is selected.
456         if (importRadioButton.isChecked()) {  // Import is selected.
457             // Create the file picker intent.
458             Intent importBrowseIntent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
459
460             // Set the intent MIME type to include all files so that everything is visible.
461             importBrowseIntent.setType("*/*");
462
463             // Request a file that can be opened.
464             importBrowseIntent.addCategory(Intent.CATEGORY_OPENABLE);
465
466             // Launch the file picker.
467             startActivityForResult(importBrowseIntent, BROWSE_RESULT_CODE);
468         } else {  // Export is selected
469             // Create the file picker intent.
470             Intent exportBrowseIntent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
471
472             // Set the intent MIME type to include all files so that everything is visible.
473             exportBrowseIntent.setType("*/*");
474
475             // Set the initial export file name according to the encryption type.
476             if (encryptionSpinner.getSelectedItemPosition() == NO_ENCRYPTION) {  // No encryption is selected.
477                 exportBrowseIntent.putExtra(Intent.EXTRA_TITLE, getString(R.string.settings) + " " + BuildConfig.VERSION_NAME + ".pbs");
478             } else {  // Password encryption is selected.
479                 exportBrowseIntent.putExtra(Intent.EXTRA_TITLE, getString(R.string.settings) + " " + BuildConfig.VERSION_NAME + ".pbs.aes");
480             }
481
482             // Request a file that can be opened.
483             exportBrowseIntent.addCategory(Intent.CATEGORY_OPENABLE);
484
485             // Launch the file picker.
486             startActivityForResult(exportBrowseIntent, BROWSE_RESULT_CODE);
487         }
488     }
489
490     @Override
491     public void onActivityResult(int requestCode, int resultCode, Intent returnedIntent) {
492         // Run the default commands.
493         super.onActivityResult(requestCode, resultCode, returnedIntent);
494
495         switch (requestCode) {
496             case (BROWSE_RESULT_CODE):
497                 // Only do something if the user didn't press back from the file picker.
498                 if (resultCode == Activity.RESULT_OK) {
499                     // Get the file path URI from the intent.
500                     Uri fileNameUri = returnedIntent.getData();
501
502                     // Get the file name string from the URI.
503                     String fileNameString = fileNameUri.toString();
504
505                     // Set the file name name text.
506                     fileNameEditText.setText(fileNameString);
507
508                     // Move the cursor to the end of the file name edit text.
509                     fileNameEditText.setSelection(fileNameString.length());
510                 }
511                 break;
512
513             case OPENPGP_IMPORT_RESULT_CODE:
514                 // Delete the temporary PGP encrypted import file.
515                 if (temporaryPgpEncryptedImportFile.exists()) {
516                     //noinspection ResultOfMethodCallIgnored
517                     temporaryPgpEncryptedImportFile.delete();
518                 }
519                 break;
520
521             case OPENPGP_EXPORT_RESULT_CODE:
522                 // Delete the temporary pre-encrypted export file if it exists.
523                 if (temporaryPreEncryptedExportFile.exists()) {
524                     //noinspection ResultOfMethodCallIgnored
525                     temporaryPreEncryptedExportFile.delete();
526                 }
527                 break;
528         }
529     }
530
531     public void importExport(View view) {
532         // Instantiate the import export database helper.
533         ImportExportDatabaseHelper importExportDatabaseHelper = new ImportExportDatabaseHelper();
534
535         // Check to see if import or export is selected.
536         if (importRadioButton.isChecked()) {  // Import is selected.
537             // Initialize the import status string
538             String importStatus = "";
539
540             // Get the file name string.
541             String fileNameString = fileNameEditText.getText().toString();
542
543             // Import according to the encryption type.
544             switch (encryptionSpinner.getSelectedItemPosition()) {
545                 case NO_ENCRYPTION:
546                     try {
547                         // Get an input stream for the file name.
548                         InputStream inputStream = getContentResolver().openInputStream(Uri.parse(fileNameString));
549
550                         // Import the unencrypted file.
551                         importStatus = importExportDatabaseHelper.importUnencrypted(inputStream, this);
552                     } catch (FileNotFoundException exception) {
553                         // Update the import status.
554                         importStatus = exception.toString();
555                     }
556
557                     // Restart Privacy Browser if successful.
558                     if (importStatus.equals(ImportExportDatabaseHelper.IMPORT_SUCCESSFUL)) {
559                         restartPrivacyBrowser();
560                     }
561                     break;
562
563                 case PASSWORD_ENCRYPTION:
564                     try {
565                         // Get the encryption password.
566                         String encryptionPasswordString = encryptionPasswordEditText.getText().toString();
567
568                         // Get an input stream for the file name.
569                         InputStream inputStream = getContentResolver().openInputStream(Uri.parse(fileNameString));
570
571                         // Get the salt from the beginning of the import file.
572                         byte[] saltByteArray = new byte[32];
573                         //noinspection ResultOfMethodCallIgnored
574                         inputStream.read(saltByteArray);
575
576                         // Get the initialization vector from the import file.
577                         byte[] initializationVector = new byte[12];
578                         //noinspection ResultOfMethodCallIgnored
579                         inputStream.read(initializationVector);
580
581                         // Convert the encryption password to a byte array.
582                         byte[] encryptionPasswordByteArray = encryptionPasswordString.getBytes(StandardCharsets.UTF_8);
583
584                         // Append the salt to the encryption password byte array.  This protects against rainbow table attacks.
585                         byte[] encryptionPasswordWithSaltByteArray = new byte[encryptionPasswordByteArray.length + saltByteArray.length];
586                         System.arraycopy(encryptionPasswordByteArray, 0, encryptionPasswordWithSaltByteArray, 0, encryptionPasswordByteArray.length);
587                         System.arraycopy(saltByteArray, 0, encryptionPasswordWithSaltByteArray, encryptionPasswordByteArray.length, saltByteArray.length);
588
589                         // Get a SHA-512 message digest.
590                         MessageDigest messageDigest = MessageDigest.getInstance("SHA-512");
591
592                         // Hash the salted encryption password.  Otherwise, any characters after the 32nd character in the password are ignored.
593                         byte[] hashedEncryptionPasswordWithSaltByteArray = messageDigest.digest(encryptionPasswordWithSaltByteArray);
594
595                         // Truncate the encryption password byte array to 256 bits (32 bytes).
596                         byte[] truncatedHashedEncryptionPasswordWithSaltByteArray = Arrays.copyOf(hashedEncryptionPasswordWithSaltByteArray, 32);
597
598                         // Create an AES secret key from the encryption password byte array.
599                         SecretKeySpec secretKey = new SecretKeySpec(truncatedHashedEncryptionPasswordWithSaltByteArray, "AES");
600
601                         // Get a Advanced Encryption Standard, Galois/Counter Mode, No Padding cipher instance. Galois/Counter mode protects against modification of the ciphertext.  It doesn't use padding.
602                         Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
603
604                         // Set the GCM tag length to be 128 bits (the maximum) and apply the initialization vector.
605                         GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, initializationVector);
606
607                         // Initialize the cipher.
608                         cipher.init(Cipher.DECRYPT_MODE, secretKey, gcmParameterSpec);
609
610                         // Create a cipher input stream.
611                         CipherInputStream cipherInputStream = new CipherInputStream(inputStream, cipher);
612
613                         // Initialize variables to store data as it is moved from the cipher input stream to the unencrypted import file output stream.  Move 128 bits (16 bytes) at a time.
614                         int numberOfBytesRead;
615                         byte[] decryptedBytes = new byte[16];
616
617
618                         // Create a private temporary unencrypted import file.
619                         File temporaryUnencryptedImportFile = File.createTempFile("temporary_unencrypted_import_file", null, getApplicationContext().getCacheDir());
620
621                         // Create an temporary unencrypted import file output stream.
622                         FileOutputStream temporaryUnencryptedImportFileOutputStream = new FileOutputStream(temporaryUnencryptedImportFile);
623
624
625                         // Read up to 128 bits (16 bytes) of data from the cipher input stream.  `-1` will be returned when the end fo the file is reached.
626                         while ((numberOfBytesRead = cipherInputStream.read(decryptedBytes)) != -1) {
627                             // Write the data to the temporary unencrypted import file output stream.
628                             temporaryUnencryptedImportFileOutputStream.write(decryptedBytes, 0, numberOfBytesRead);
629                         }
630
631
632                         // Flush the temporary unencrypted import file output stream.
633                         temporaryUnencryptedImportFileOutputStream.flush();
634
635                         // Close the streams.
636                         temporaryUnencryptedImportFileOutputStream.close();
637                         cipherInputStream.close();
638                         inputStream.close();
639
640                         // Wipe the encryption data from memory.
641                         //noinspection UnusedAssignment
642                         encryptionPasswordString = "";
643                         Arrays.fill(saltByteArray, (byte) 0);
644                         Arrays.fill(initializationVector, (byte) 0);
645                         Arrays.fill(encryptionPasswordByteArray, (byte) 0);
646                         Arrays.fill(encryptionPasswordWithSaltByteArray, (byte) 0);
647                         Arrays.fill(hashedEncryptionPasswordWithSaltByteArray, (byte) 0);
648                         Arrays.fill(truncatedHashedEncryptionPasswordWithSaltByteArray, (byte) 0);
649                         Arrays.fill(decryptedBytes, (byte) 0);
650
651                         // Create a temporary unencrypted import file input stream.
652                         FileInputStream temporaryUnencryptedImportFileInputStream = new FileInputStream(temporaryUnencryptedImportFile);
653
654                         // Import the temporary unencrypted import file.
655                         importStatus = importExportDatabaseHelper.importUnencrypted(temporaryUnencryptedImportFileInputStream, this);
656
657                         // Close the temporary unencrypted import file input stream.
658                         temporaryUnencryptedImportFileInputStream.close();
659
660                         // Delete the temporary unencrypted import file.
661                         //noinspection ResultOfMethodCallIgnored
662                         temporaryUnencryptedImportFile.delete();
663
664                         // Restart Privacy Browser if successful.
665                         if (importStatus.equals(ImportExportDatabaseHelper.IMPORT_SUCCESSFUL)) {
666                             restartPrivacyBrowser();
667                         }
668                     } catch (Exception exception) {
669                         // Update the import status.
670                         importStatus = exception.toString();
671                     }
672                     break;
673
674                 case OPENPGP_ENCRYPTION:
675                     try {
676                         // Set the temporary PGP encrypted import file.
677                         temporaryPgpEncryptedImportFile = File.createTempFile("temporary_pgp_encrypted_import_file", null, getApplicationContext().getCacheDir());
678
679                         // Create a temporary PGP encrypted import file output stream.
680                         FileOutputStream temporaryPgpEncryptedImportFileOutputStream = new FileOutputStream(temporaryPgpEncryptedImportFile);
681
682                         // Get an input stream for the file name.
683                         InputStream inputStream = getContentResolver().openInputStream(Uri.parse(fileNameString));
684
685                         // Create a transfer byte array.
686                         byte[] transferByteArray = new byte[1024];
687
688                         // Create an integer to track the number of bytes read.
689                         int bytesRead;
690
691                         // Copy the input stream to the temporary PGP encrypted import file.
692                         while ((bytesRead = inputStream.read(transferByteArray)) > 0) {
693                             temporaryPgpEncryptedImportFileOutputStream.write(transferByteArray, 0, bytesRead);
694                         }
695
696                         // Flush the temporary PGP encrypted import file output stream.
697                         temporaryPgpEncryptedImportFileOutputStream.flush();
698
699                         // Close the streams.
700                         inputStream.close();
701                         temporaryPgpEncryptedImportFileOutputStream.flush();
702
703
704                         // Create an decryption intent for OpenKeychain.
705                         Intent openKeychainDecryptIntent = new Intent("org.sufficientlysecure.keychain.action.DECRYPT_DATA");
706
707                         // Include the URI to be decrypted.
708                         openKeychainDecryptIntent.setData(FileProvider.getUriForFile(this, getString(R.string.file_provider), temporaryPgpEncryptedImportFile));
709
710                         // Allow OpenKeychain to read the file URI.
711                         openKeychainDecryptIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
712
713                         // Send the intent to the OpenKeychain package.
714                         openKeychainDecryptIntent.setPackage("org.sufficientlysecure.keychain");
715
716                         // Make it so.
717                         startActivityForResult(openKeychainDecryptIntent, OPENPGP_IMPORT_RESULT_CODE);
718
719                         // Update the import status.
720                         importStatus = ImportExportDatabaseHelper.IMPORT_SUCCESSFUL;
721                     } catch (Exception exception) {
722                         // Update the import status.
723                         importStatus = exception.toString();
724                     }
725                     break;
726             }
727
728             // Respond to the import status.
729             if (!importStatus.equals(ImportExportDatabaseHelper.IMPORT_SUCCESSFUL)) {
730                 // Display a snack bar with the import error.
731                 Snackbar.make(fileNameEditText, getString(R.string.import_failed) + "  " + importStatus, Snackbar.LENGTH_INDEFINITE).show();
732             }
733         } else {  // Export is selected.
734             // Export according to the encryption type.
735             switch (encryptionSpinner.getSelectedItemPosition()) {
736                 case NO_ENCRYPTION:
737                     // Get the file name string.
738                     String noEncryptionFileNameString = fileNameEditText.getText().toString();
739
740                     try {
741                         // Get the export file output stream.
742                         OutputStream exportFileOutputStream = getContentResolver().openOutputStream(Uri.parse(noEncryptionFileNameString));
743
744                         // Export the unencrypted file.
745                         String noEncryptionExportStatus = importExportDatabaseHelper.exportUnencrypted(exportFileOutputStream, this);
746
747                         // Display an export disposition snackbar.
748                         if (noEncryptionExportStatus.equals(ImportExportDatabaseHelper.EXPORT_SUCCESSFUL)) {
749                             Snackbar.make(fileNameEditText, getString(R.string.export_successful), Snackbar.LENGTH_SHORT).show();
750                         } else {
751                             Snackbar.make(fileNameEditText, getString(R.string.export_failed) + "  " + noEncryptionExportStatus, Snackbar.LENGTH_INDEFINITE).show();
752                         }
753                     } catch (FileNotFoundException fileNotFoundException) {
754                         // Display a snackbar with the exception.
755                         Snackbar.make(fileNameEditText, getString(R.string.export_failed) + "  " + fileNotFoundException, Snackbar.LENGTH_INDEFINITE).show();
756                     }
757                     break;
758
759                 case PASSWORD_ENCRYPTION:
760                     try {
761                         // Create a temporary unencrypted export file.
762                         File temporaryUnencryptedExportFile = File.createTempFile("temporary_unencrypted_export_file", null, getApplicationContext().getCacheDir());
763
764                         // Create a temporary unencrypted export output stream.
765                         FileOutputStream temporaryUnencryptedExportOutputStream = new FileOutputStream(temporaryUnencryptedExportFile);
766
767                         // Populate the temporary unencrypted export.
768                         String passwordEncryptionExportStatus = importExportDatabaseHelper.exportUnencrypted(temporaryUnencryptedExportOutputStream, this);
769
770                         // Close the temporary unencrypted export output stream.
771                         temporaryUnencryptedExportOutputStream.close();
772
773                         // Create an unencrypted export file input stream.
774                         FileInputStream unencryptedExportFileInputStream = new FileInputStream(temporaryUnencryptedExportFile);
775
776                         // Get the encryption password.
777                         String encryptionPasswordString = encryptionPasswordEditText.getText().toString();
778
779                         // Initialize a secure random number generator.
780                         SecureRandom secureRandom = new SecureRandom();
781
782                         // Get a 256 bit (32 byte) random salt.
783                         byte[] saltByteArray = new byte[32];
784                         secureRandom.nextBytes(saltByteArray);
785
786                         // Convert the encryption password to a byte array.
787                         byte[] encryptionPasswordByteArray = encryptionPasswordString.getBytes(StandardCharsets.UTF_8);
788
789                         // Append the salt to the encryption password byte array.  This protects against rainbow table attacks.
790                         byte[] encryptionPasswordWithSaltByteArray = new byte[encryptionPasswordByteArray.length + saltByteArray.length];
791                         System.arraycopy(encryptionPasswordByteArray, 0, encryptionPasswordWithSaltByteArray, 0, encryptionPasswordByteArray.length);
792                         System.arraycopy(saltByteArray, 0, encryptionPasswordWithSaltByteArray, encryptionPasswordByteArray.length, saltByteArray.length);
793
794                         // Get a SHA-512 message digest.
795                         MessageDigest messageDigest = MessageDigest.getInstance("SHA-512");
796
797                         // Hash the salted encryption password.  Otherwise, any characters after the 32nd character in the password are ignored.
798                         byte[] hashedEncryptionPasswordWithSaltByteArray = messageDigest.digest(encryptionPasswordWithSaltByteArray);
799
800                         // Truncate the encryption password byte array to 256 bits (32 bytes).
801                         byte[] truncatedHashedEncryptionPasswordWithSaltByteArray = Arrays.copyOf(hashedEncryptionPasswordWithSaltByteArray, 32);
802
803                         // Create an AES secret key from the encryption password byte array.
804                         SecretKeySpec secretKey = new SecretKeySpec(truncatedHashedEncryptionPasswordWithSaltByteArray, "AES");
805
806                         // Generate a random 12 byte initialization vector.  According to NIST, a 12 byte initialization vector is more secure than a 16 byte one.
807                         byte[] initializationVector = new byte[12];
808                         secureRandom.nextBytes(initializationVector);
809
810                         // Get a Advanced Encryption Standard, Galois/Counter Mode, No Padding cipher instance. Galois/Counter mode protects against modification of the ciphertext.  It doesn't use padding.
811                         Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
812
813                         // Set the GCM tag length to be 128 bits (the maximum) and apply the initialization vector.
814                         GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, initializationVector);
815
816                         // Initialize the cipher.
817                         cipher.init(Cipher.ENCRYPT_MODE, secretKey, gcmParameterSpec);
818
819                         // Get the file name string.
820                         String passwordEncryptionFileNameString = fileNameEditText.getText().toString();
821
822                         // Get the export file output stream.
823                         OutputStream exportFileOutputStream = getContentResolver().openOutputStream(Uri.parse(passwordEncryptionFileNameString));
824
825                         // Add the salt and the initialization vector to the export file output stream.
826                         exportFileOutputStream.write(saltByteArray);
827                         exportFileOutputStream.write(initializationVector);
828
829                         // Create a cipher output stream.
830                         CipherOutputStream cipherOutputStream = new CipherOutputStream(exportFileOutputStream, cipher);
831
832                         // Initialize variables to store data as it is moved from the unencrypted export file input stream to the cipher output stream.  Move 128 bits (16 bytes) at a time.
833                         int numberOfBytesRead;
834                         byte[] encryptedBytes = new byte[16];
835
836                         // Read up to 128 bits (16 bytes) of data from the unencrypted export file stream.  `-1` will be returned when the end of the file is reached.
837                         while ((numberOfBytesRead = unencryptedExportFileInputStream.read(encryptedBytes)) != -1) {
838                             // Write the data to the cipher output stream.
839                             cipherOutputStream.write(encryptedBytes, 0, numberOfBytesRead);
840                         }
841
842                         // Close the streams.
843                         cipherOutputStream.flush();
844                         cipherOutputStream.close();
845                         exportFileOutputStream.close();
846                         unencryptedExportFileInputStream.close();
847
848                         // Wipe the encryption data from memory.
849                         //noinspection UnusedAssignment
850                         encryptionPasswordString = "";
851                         Arrays.fill(saltByteArray, (byte) 0);
852                         Arrays.fill(encryptionPasswordByteArray, (byte) 0);
853                         Arrays.fill(encryptionPasswordWithSaltByteArray, (byte) 0);
854                         Arrays.fill(hashedEncryptionPasswordWithSaltByteArray, (byte) 0);
855                         Arrays.fill(truncatedHashedEncryptionPasswordWithSaltByteArray, (byte) 0);
856                         Arrays.fill(initializationVector, (byte) 0);
857                         Arrays.fill(encryptedBytes, (byte) 0);
858
859                         // Delete the temporary unencrypted export file.
860                         //noinspection ResultOfMethodCallIgnored
861                         temporaryUnencryptedExportFile.delete();
862
863                         // Display an export disposition snackbar.
864                         if (passwordEncryptionExportStatus.equals(ImportExportDatabaseHelper.EXPORT_SUCCESSFUL)) {
865                             Snackbar.make(fileNameEditText, getString(R.string.export_successful), Snackbar.LENGTH_SHORT).show();
866                         } else {
867                             Snackbar.make(fileNameEditText, getString(R.string.export_failed) + "  " + passwordEncryptionExportStatus, Snackbar.LENGTH_INDEFINITE).show();
868                         }
869                     } catch (Exception exception) {
870                         // Display a snackbar with the exception.
871                         Snackbar.make(fileNameEditText, getString(R.string.export_failed) + "  " + exception, Snackbar.LENGTH_INDEFINITE).show();
872                     }
873                     break;
874
875                 case OPENPGP_ENCRYPTION:
876                     try {
877                         // Set the temporary pre-encrypted export file.
878                         temporaryPreEncryptedExportFile = new File(getApplicationContext().getCacheDir() + "/" + getString(R.string.settings) + " " + BuildConfig.VERSION_NAME + ".pbs");
879
880                         // Delete the temporary pre-encrypted export file if it already exists.
881                         if (temporaryPreEncryptedExportFile.exists()) {
882                             //noinspection ResultOfMethodCallIgnored
883                             temporaryPreEncryptedExportFile.delete();
884                         }
885
886                         // Create a temporary pre-encrypted export output stream.
887                         FileOutputStream temporaryPreEncryptedExportOutputStream = new FileOutputStream(temporaryPreEncryptedExportFile);
888
889                         // Populate the temporary pre-encrypted export file.
890                         String openpgpEncryptionExportStatus = importExportDatabaseHelper.exportUnencrypted(temporaryPreEncryptedExportOutputStream, this);
891
892                         // Flush the temporary pre-encryption export output stream.
893                         temporaryPreEncryptedExportOutputStream.flush();
894
895                         // Close the temporary pre-encryption export output stream.
896                         temporaryPreEncryptedExportOutputStream.close();
897
898                         // Display an export error snackbar if the temporary pre-encrypted export failed.
899                         if (!openpgpEncryptionExportStatus.equals(ImportExportDatabaseHelper.EXPORT_SUCCESSFUL)) {
900                             Snackbar.make(fileNameEditText, getString(R.string.export_failed) + "  " + openpgpEncryptionExportStatus, Snackbar.LENGTH_INDEFINITE).show();
901                         }
902
903                         // Create an encryption intent for OpenKeychain.
904                         Intent openKeychainEncryptIntent = new Intent("org.sufficientlysecure.keychain.action.ENCRYPT_DATA");
905
906                         // Include the temporary unencrypted export file URI.
907                         openKeychainEncryptIntent.setData(FileProvider.getUriForFile(this, getString(R.string.file_provider), temporaryPreEncryptedExportFile));
908
909                         // Allow OpenKeychain to read the file URI.
910                         openKeychainEncryptIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
911
912                         // Send the intent to the OpenKeychain package.
913                         openKeychainEncryptIntent.setPackage("org.sufficientlysecure.keychain");
914
915                         // Make it so.
916                         startActivityForResult(openKeychainEncryptIntent, OPENPGP_EXPORT_RESULT_CODE);
917                     } catch (Exception exception) {
918                         // Display a snackbar with the exception.
919                         Snackbar.make(fileNameEditText, getString(R.string.export_failed) + "  " + exception, Snackbar.LENGTH_INDEFINITE).show();
920                     }
921                     break;
922             }
923         }
924     }
925
926     private void restartPrivacyBrowser() {
927         // Create an intent to restart Privacy Browser.
928         Intent restartIntent = getParentActivityIntent();
929
930         // Assert that the intent is not null to remove the lint error below.
931         assert restartIntent != null;
932
933         // `Intent.FLAG_ACTIVITY_CLEAR_TASK` removes all activities from the stack.  It requires `Intent.FLAG_ACTIVITY_NEW_TASK`.
934         restartIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
935
936         // Create a restart handler.
937         Handler restartHandler = new Handler();
938
939         // Create a restart runnable.
940         Runnable restartRunnable =  () -> {
941             // Restart Privacy Browser.
942             startActivity(restartIntent);
943
944             // Kill this instance of Privacy Browser.  Otherwise, the app exhibits sporadic behavior after the restart.
945             System.exit(0);
946         };
947
948         // Restart Privacy Browser after 150 milliseconds to allow enough time for the preferences to be saved.
949         restartHandler.postDelayed(restartRunnable, 150);
950     }
951 }