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