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