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