]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/activities/ImportExportActivity.java
bea58d3fe7a7e95542867389ecf2a1fdf5bf490e
[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.SharedPreferences;
26 import android.content.pm.PackageManager;
27 import android.media.MediaScannerConnection;
28 import android.os.Build;
29 import android.os.Bundle;
30 import android.os.Environment;
31 import android.os.Handler;
32 import android.preference.PreferenceManager;
33 import android.provider.DocumentsContract;
34 import android.text.Editable;
35 import android.text.TextWatcher;
36 import android.view.View;
37 import android.view.WindowManager;
38 import android.widget.AdapterView;
39 import android.widget.ArrayAdapter;
40 import android.widget.Button;
41 import android.widget.EditText;
42 import android.widget.LinearLayout;
43 import android.widget.RadioButton;
44 import android.widget.Spinner;
45 import android.widget.TextView;
46
47 import androidx.annotation.NonNull;
48 import androidx.appcompat.app.ActionBar;
49 import androidx.appcompat.app.AppCompatActivity;
50 import androidx.appcompat.widget.Toolbar;
51 import androidx.cardview.widget.CardView;
52 import androidx.core.app.ActivityCompat;
53 import androidx.core.content.ContextCompat;
54 import androidx.core.content.FileProvider;
55 import androidx.fragment.app.DialogFragment;
56
57 import com.google.android.material.snackbar.Snackbar;
58 import com.google.android.material.textfield.TextInputLayout;
59
60 import com.stoutner.privacybrowser.R;
61 import com.stoutner.privacybrowser.dialogs.StoragePermissionDialog;
62 import com.stoutner.privacybrowser.helpers.FileNameHelper;
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                     // Instantiate the file name helper.
570                     FileNameHelper fileNameHelper = new FileNameHelper();
571
572                     // Convert the file name URI to a file name path.
573                     String fileNamePath = fileNameHelper.convertUriToFileNamePath(data.getData());
574
575                     // Set the file name path as the text of the file name edit text.
576                     fileNameEditText.setText(fileNamePath);
577                 }
578                 break;
579
580             case OPENPGP_EXPORT_RESULT_CODE:
581                 // Get the temporary unencrypted export file.
582                 File temporaryUnencryptedExportFile = new File(getApplicationContext().getCacheDir() + "/" + getString(R.string.settings_pbs));
583
584                 // Delete the temporary unencrypted export file if it exists.
585                 if (temporaryUnencryptedExportFile.exists()) {
586                     //noinspection ResultOfMethodCallIgnored
587                     temporaryUnencryptedExportFile.delete();
588                 }
589                 break;
590         }
591     }
592
593     private void exportSettings() {
594         // Get a handle for the views.
595         Spinner encryptionSpinner = findViewById(R.id.encryption_spinner);
596         EditText fileNameEditText = findViewById(R.id.file_name_edittext);
597
598         // Instantiate the import export database helper.
599         ImportExportDatabaseHelper importExportDatabaseHelper = new ImportExportDatabaseHelper();
600
601         // Get the export file string.
602         String exportFileString = fileNameEditText.getText().toString();
603
604         // Get the export and temporary unencrypted export files.
605         File exportFile = new File(exportFileString);
606         File temporaryUnencryptedExportFile = new File(getApplicationContext().getCacheDir() + "/" + getString(R.string.settings_pbs));
607
608         // Create an export status string.
609         String exportStatus;
610
611         // Export according to the encryption type.
612         switch (encryptionSpinner.getSelectedItemPosition()) {
613             case NO_ENCRYPTION:
614                 // Export the unencrypted file.
615                 exportStatus = importExportDatabaseHelper.exportUnencrypted(exportFile, this);
616
617                 // Show a disposition snackbar.
618                 if (exportStatus.equals(ImportExportDatabaseHelper.EXPORT_SUCCESSFUL)) {
619                     Snackbar.make(fileNameEditText, getString(R.string.export_successful), Snackbar.LENGTH_SHORT).show();
620                 } else {
621                     Snackbar.make(fileNameEditText, getString(R.string.export_failed) + "  " + exportStatus, Snackbar.LENGTH_INDEFINITE).show();
622                 }
623                 break;
624
625             case PASSWORD_ENCRYPTION:
626                 // Create an unencrypted export in a private directory.
627                 exportStatus = importExportDatabaseHelper.exportUnencrypted(temporaryUnencryptedExportFile, this);
628
629                 try {
630                     // Create an unencrypted export file input stream.
631                     FileInputStream unencryptedExportFileInputStream = new FileInputStream(temporaryUnencryptedExportFile);
632
633                     // Delete the encrypted export file if it exists.
634                     if (exportFile.exists()) {
635                         //noinspection ResultOfMethodCallIgnored
636                         exportFile.delete();
637                     }
638
639                     // Create an encrypted export file output stream.
640                     FileOutputStream encryptedExportFileOutputStream = new FileOutputStream(exportFile);
641
642                     // Get a handle for the encryption password EditText.
643                     EditText encryptionPasswordEditText = findViewById(R.id.password_encryption_edittext);
644
645                     // Get the encryption password.
646                     String encryptionPasswordString = encryptionPasswordEditText.getText().toString();
647
648                     // Initialize a secure random number generator.
649                     SecureRandom secureRandom = new SecureRandom();
650
651                     // Get a 256 bit (32 byte) random salt.
652                     byte[] saltByteArray = new byte[32];
653                     secureRandom.nextBytes(saltByteArray);
654
655                     // Convert the encryption password to a byte array.
656                     byte[] encryptionPasswordByteArray = encryptionPasswordString.getBytes(StandardCharsets.UTF_8);
657
658                     // Append the salt to the encryption password byte array.  This protects against rainbow table attacks.
659                     byte[] encryptionPasswordWithSaltByteArray = new byte[encryptionPasswordByteArray.length + saltByteArray.length];
660                     System.arraycopy(encryptionPasswordByteArray, 0, encryptionPasswordWithSaltByteArray, 0, encryptionPasswordByteArray.length);
661                     System.arraycopy(saltByteArray, 0, encryptionPasswordWithSaltByteArray, encryptionPasswordByteArray.length, saltByteArray.length);
662
663                     // Get a SHA-512 message digest.
664                     MessageDigest messageDigest = MessageDigest.getInstance("SHA-512");
665
666                     // Hash the salted encryption password.  Otherwise, any characters after the 32nd character in the password are ignored.
667                     byte[] hashedEncryptionPasswordWithSaltByteArray = messageDigest.digest(encryptionPasswordWithSaltByteArray);
668
669                     // Truncate the encryption password byte array to 256 bits (32 bytes).
670                     byte[] truncatedHashedEncryptionPasswordWithSaltByteArray = Arrays.copyOf(hashedEncryptionPasswordWithSaltByteArray, 32);
671
672                     // Create an AES secret key from the encryption password byte array.
673                     SecretKeySpec secretKey = new SecretKeySpec(truncatedHashedEncryptionPasswordWithSaltByteArray, "AES");
674
675                     // Generate a random 12 byte initialization vector.  According to NIST, a 12 byte initialization vector is more secure than a 16 byte one.
676                     byte[] initializationVector = new byte[12];
677                     secureRandom.nextBytes(initializationVector);
678
679                     // 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.
680                     Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
681
682                     // Set the GCM tag length to be 128 bits (the maximum) and apply the initialization vector.
683                     GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, initializationVector);
684
685                     // Initialize the cipher.
686                     cipher.init(Cipher.ENCRYPT_MODE, secretKey, gcmParameterSpec);
687
688                     // Add the salt and the initialization vector to the export file.
689                     encryptedExportFileOutputStream.write(saltByteArray);
690                     encryptedExportFileOutputStream.write(initializationVector);
691
692                     // Create a cipher output stream.
693                     CipherOutputStream cipherOutputStream = new CipherOutputStream(encryptedExportFileOutputStream, cipher);
694
695                     // 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.
696                     int numberOfBytesRead;
697                     byte[] encryptedBytes = new byte[16];
698
699                     // 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.
700                     while ((numberOfBytesRead = unencryptedExportFileInputStream.read(encryptedBytes)) != -1) {
701                         // Write the data to the cipher output stream.
702                         cipherOutputStream.write(encryptedBytes, 0, numberOfBytesRead);
703                     }
704
705                     // Close the streams.
706                     cipherOutputStream.flush();
707                     cipherOutputStream.close();
708                     encryptedExportFileOutputStream.close();
709                     unencryptedExportFileInputStream.close();
710
711                     // Wipe the encryption data from memory.
712                     //noinspection UnusedAssignment
713                     encryptionPasswordString = "";
714                     Arrays.fill(saltByteArray, (byte) 0);
715                     Arrays.fill(encryptionPasswordByteArray, (byte) 0);
716                     Arrays.fill(encryptionPasswordWithSaltByteArray, (byte) 0);
717                     Arrays.fill(hashedEncryptionPasswordWithSaltByteArray, (byte) 0);
718                     Arrays.fill(truncatedHashedEncryptionPasswordWithSaltByteArray, (byte) 0);
719                     Arrays.fill(initializationVector, (byte) 0);
720                     Arrays.fill(encryptedBytes, (byte) 0);
721
722                     // Delete the temporary unencrypted export file.
723                     //noinspection ResultOfMethodCallIgnored
724                     temporaryUnencryptedExportFile.delete();
725                 } catch (Exception exception) {
726                     exportStatus = exception.toString();
727                 }
728
729                 // Show a disposition snackbar.
730                 if (exportStatus.equals(ImportExportDatabaseHelper.EXPORT_SUCCESSFUL)) {
731                     Snackbar.make(fileNameEditText, getString(R.string.export_successful), Snackbar.LENGTH_SHORT).show();
732                 } else {
733                     Snackbar.make(fileNameEditText, getString(R.string.export_failed) + "  " + exportStatus, Snackbar.LENGTH_INDEFINITE).show();
734                 }
735                 break;
736
737             case OPENPGP_ENCRYPTION:
738                 // Create an unencrypted export in the private location.
739                 importExportDatabaseHelper.exportUnencrypted(temporaryUnencryptedExportFile, this);
740
741                 // Create an encryption intent for OpenKeychain.
742                 Intent openKeychainEncryptIntent = new Intent("org.sufficientlysecure.keychain.action.ENCRYPT_DATA");
743
744                 // Include the temporary unencrypted export file URI.
745                 openKeychainEncryptIntent.setData(FileProvider.getUriForFile(this, getString(R.string.file_provider), temporaryUnencryptedExportFile));
746
747                 // Allow OpenKeychain to read the file URI.
748                 openKeychainEncryptIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
749
750                 // Send the intent to the OpenKeychain package.
751                 openKeychainEncryptIntent.setPackage("org.sufficientlysecure.keychain");
752
753                 // Make it so.
754                 startActivityForResult(openKeychainEncryptIntent, OPENPGP_EXPORT_RESULT_CODE);
755                 break;
756         }
757
758         // Add the file to the list of recent files.  This doesn't currently work, but maybe it will someday.
759         MediaScannerConnection.scanFile(this, new String[] {exportFileString}, new String[] {"application/x-sqlite3"}, null);
760     }
761
762     private void importSettings() {
763         // Get a handle for the views.
764         Spinner encryptionSpinner = findViewById(R.id.encryption_spinner);
765         EditText fileNameEditText = findViewById(R.id.file_name_edittext);
766
767         // Instantiate the import export database helper.
768         ImportExportDatabaseHelper importExportDatabaseHelper = new ImportExportDatabaseHelper();
769
770         // Get the import file.
771         File importFile = new File(fileNameEditText.getText().toString());
772
773         // Initialize the import status string
774         String importStatus = "";
775
776         // Import according to the encryption type.
777         switch (encryptionSpinner.getSelectedItemPosition()) {
778             case NO_ENCRYPTION:
779                 // Import the unencrypted file.
780                 importStatus = importExportDatabaseHelper.importUnencrypted(importFile, this);
781                 break;
782
783             case PASSWORD_ENCRYPTION:
784                 // Use a private temporary import location.
785                 File temporaryUnencryptedImportFile = new File(getApplicationContext().getCacheDir() + "/" + getString(R.string.settings_pbs));
786
787                 try {
788                     // Create an encrypted import file input stream.
789                     FileInputStream encryptedImportFileInputStream = new FileInputStream(importFile);
790
791                     // Delete the temporary import file if it exists.
792                     if (temporaryUnencryptedImportFile.exists()) {
793                         //noinspection ResultOfMethodCallIgnored
794                         temporaryUnencryptedImportFile.delete();
795                     }
796
797                     // Create an unencrypted import file output stream.
798                     FileOutputStream unencryptedImportFileOutputStream = new FileOutputStream(temporaryUnencryptedImportFile);
799
800                     // Get a handle for the encryption password EditText.
801                     EditText encryptionPasswordEditText = findViewById(R.id.password_encryption_edittext);
802
803                     // Get the encryption password.
804                     String encryptionPasswordString = encryptionPasswordEditText.getText().toString();
805
806                     // Get the salt from the beginning of the import file.
807                     byte[] saltByteArray = new byte[32];
808                     //noinspection ResultOfMethodCallIgnored
809                     encryptedImportFileInputStream.read(saltByteArray);
810
811                     // Get the initialization vector from the import file.
812                     byte[] initializationVector = new byte[12];
813                     //noinspection ResultOfMethodCallIgnored
814                     encryptedImportFileInputStream.read(initializationVector);
815
816                     // Convert the encryption password to a byte array.
817                     byte[] encryptionPasswordByteArray = encryptionPasswordString.getBytes(StandardCharsets.UTF_8);
818
819                     // Append the salt to the encryption password byte array.  This protects against rainbow table attacks.
820                     byte[] encryptionPasswordWithSaltByteArray = new byte[encryptionPasswordByteArray.length + saltByteArray.length];
821                     System.arraycopy(encryptionPasswordByteArray, 0, encryptionPasswordWithSaltByteArray, 0, encryptionPasswordByteArray.length);
822                     System.arraycopy(saltByteArray, 0, encryptionPasswordWithSaltByteArray, encryptionPasswordByteArray.length, saltByteArray.length);
823
824                     // Get a SHA-512 message digest.
825                     MessageDigest messageDigest = MessageDigest.getInstance("SHA-512");
826
827                     // Hash the salted encryption password.  Otherwise, any characters after the 32nd character in the password are ignored.
828                     byte[] hashedEncryptionPasswordWithSaltByteArray = messageDigest.digest(encryptionPasswordWithSaltByteArray);
829
830                     // Truncate the encryption password byte array to 256 bits (32 bytes).
831                     byte[] truncatedHashedEncryptionPasswordWithSaltByteArray = Arrays.copyOf(hashedEncryptionPasswordWithSaltByteArray, 32);
832
833                     // Create an AES secret key from the encryption password byte array.
834                     SecretKeySpec secretKey = new SecretKeySpec(truncatedHashedEncryptionPasswordWithSaltByteArray, "AES");
835
836                     // 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.
837                     Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
838
839                     // Set the GCM tag length to be 128 bits (the maximum) and apply the initialization vector.
840                     GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, initializationVector);
841
842                     // Initialize the cipher.
843                     cipher.init(Cipher.DECRYPT_MODE, secretKey, gcmParameterSpec);
844
845                     // Create a cipher input stream.
846                     CipherInputStream cipherInputStream = new CipherInputStream(encryptedImportFileInputStream, cipher);
847
848                     // 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.
849                     int numberOfBytesRead;
850                     byte[] decryptedBytes = new byte[16];
851
852                     // 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.
853                     while ((numberOfBytesRead = cipherInputStream.read(decryptedBytes)) != -1) {
854                         // Write the data to the unencrypted import file output stream.
855                         unencryptedImportFileOutputStream.write(decryptedBytes, 0, numberOfBytesRead);
856                     }
857
858                     // Close the streams.
859                     unencryptedImportFileOutputStream.flush();
860                     unencryptedImportFileOutputStream.close();
861                     cipherInputStream.close();
862                     encryptedImportFileInputStream.close();
863
864                     // Wipe the encryption data from memory.
865                     //noinspection UnusedAssignment
866                     encryptionPasswordString = "";
867                     Arrays.fill(saltByteArray, (byte) 0);
868                     Arrays.fill(initializationVector, (byte) 0);
869                     Arrays.fill(encryptionPasswordByteArray, (byte) 0);
870                     Arrays.fill(encryptionPasswordWithSaltByteArray, (byte) 0);
871                     Arrays.fill(hashedEncryptionPasswordWithSaltByteArray, (byte) 0);
872                     Arrays.fill(truncatedHashedEncryptionPasswordWithSaltByteArray, (byte) 0);
873                     Arrays.fill(decryptedBytes, (byte) 0);
874
875                     // Import the unencrypted database from the private location.
876                     importStatus = importExportDatabaseHelper.importUnencrypted(temporaryUnencryptedImportFile, this);
877
878                     // Delete the temporary unencrypted import file.
879                     //noinspection ResultOfMethodCallIgnored
880                     temporaryUnencryptedImportFile.delete();
881                 } catch (Exception exception) {
882                     importStatus = exception.toString();
883                 }
884                 break;
885
886             case OPENPGP_ENCRYPTION:
887                 try {
888                     // Create an decryption intent for OpenKeychain.
889                     Intent openKeychainDecryptIntent = new Intent("org.sufficientlysecure.keychain.action.DECRYPT_DATA");
890
891                     // Include the URI to be decrypted.
892                     openKeychainDecryptIntent.setData(FileProvider.getUriForFile(this, getString(R.string.file_provider), importFile));
893
894                     // Allow OpenKeychain to read the file URI.
895                     openKeychainDecryptIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
896
897                     // Send the intent to the OpenKeychain package.
898                     openKeychainDecryptIntent.setPackage("org.sufficientlysecure.keychain");
899
900                     // Make it so.
901                     startActivity(openKeychainDecryptIntent);
902                 } catch (IllegalArgumentException exception) {  // The file import location is not valid.
903                     // Display a snack bar with the import error.
904                     Snackbar.make(fileNameEditText, getString(R.string.import_failed) + "  " + exception.toString(), Snackbar.LENGTH_INDEFINITE).show();
905                 }
906                 break;
907         }
908
909         // Respond to the import disposition.
910         if (importStatus.equals(ImportExportDatabaseHelper.IMPORT_SUCCESSFUL)) {  // The import was successful.
911             // Create an intent to restart Privacy Browser.
912             Intent restartIntent = getParentActivityIntent();
913
914             // Assert that the intent is not null to remove the lint error below.
915             assert restartIntent != null;
916
917             // `Intent.FLAG_ACTIVITY_CLEAR_TASK` removes all activities from the stack.  It requires `Intent.FLAG_ACTIVITY_NEW_TASK`.
918             restartIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
919
920             // Create a restart handler.
921             Handler restartHandler = new Handler();
922
923             // Create a restart runnable.
924             Runnable restartRunnable =  () -> {
925                 // Restart Privacy Browser.
926                 startActivity(restartIntent);
927
928                 // Kill this instance of Privacy Browser.  Otherwise, the app exhibits sporadic behavior after the restart.
929                 System.exit(0);
930             };
931
932             // Restart Privacy Browser after 150 milliseconds to allow enough time for the preferences to be saved.
933             restartHandler.postDelayed(restartRunnable, 150);
934
935         } else if (!(encryptionSpinner.getSelectedItemPosition() == OPENPGP_ENCRYPTION)){  // The import was not successful.
936             // Display a snack bar with the import error.
937             Snackbar.make(fileNameEditText, getString(R.string.import_failed) + "  " + importStatus, Snackbar.LENGTH_INDEFINITE).show();
938         }
939     }
940 }