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