2 * Copyright © 2018-2020 Soren Stoutner <soren@stoutner.com>.
4 * This file is part of Privacy Browser <https://www.stoutner.com/privacy-browser>.
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.
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.
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/>.
20 package com.stoutner.privacybrowser.activities;
22 import android.Manifest;
23 import android.app.Activity;
24 import android.content.Intent;
25 import android.content.SharedPreferences;
26 import android.content.pm.PackageManager;
27 import android.media.MediaScannerConnection;
28 import android.net.Uri;
29 import android.os.Build;
30 import android.os.Bundle;
31 import android.os.Environment;
32 import android.os.Handler;
33 import android.preference.PreferenceManager;
34 import android.provider.DocumentsContract;
35 import android.text.Editable;
36 import android.text.TextWatcher;
37 import android.view.View;
38 import android.view.WindowManager;
39 import android.widget.AdapterView;
40 import android.widget.ArrayAdapter;
41 import android.widget.Button;
42 import android.widget.EditText;
43 import android.widget.LinearLayout;
44 import android.widget.RadioButton;
45 import android.widget.Spinner;
46 import android.widget.TextView;
48 import androidx.annotation.NonNull;
49 import androidx.appcompat.app.ActionBar;
50 import androidx.appcompat.app.AppCompatActivity;
51 import androidx.appcompat.widget.Toolbar;
52 import androidx.cardview.widget.CardView;
53 import androidx.core.app.ActivityCompat;
54 import androidx.core.content.ContextCompat;
55 import androidx.core.content.FileProvider;
56 import androidx.fragment.app.DialogFragment;
58 import com.google.android.material.snackbar.Snackbar;
59 import com.google.android.material.textfield.TextInputLayout;
61 import com.stoutner.privacybrowser.R;
62 import com.stoutner.privacybrowser.dialogs.StoragePermissionDialog;
63 import com.stoutner.privacybrowser.helpers.DownloadLocationHelper;
64 import com.stoutner.privacybrowser.helpers.FileNameHelper;
65 import com.stoutner.privacybrowser.helpers.ImportExportDatabaseHelper;
68 import java.io.FileInputStream;
69 import java.io.FileOutputStream;
70 import java.nio.charset.StandardCharsets;
71 import java.security.MessageDigest;
72 import java.security.SecureRandom;
73 import java.util.Arrays;
75 import javax.crypto.Cipher;
76 import javax.crypto.CipherInputStream;
77 import javax.crypto.CipherOutputStream;
78 import javax.crypto.spec.GCMParameterSpec;
79 import javax.crypto.spec.SecretKeySpec;
81 public class ImportExportActivity extends AppCompatActivity implements StoragePermissionDialog.StoragePermissionDialogListener {
82 // Create the encryption constants.
83 private final int NO_ENCRYPTION = 0;
84 private final int PASSWORD_ENCRYPTION = 1;
85 private final int OPENPGP_ENCRYPTION = 2;
87 // Create the activity result constants.
88 private final int BROWSE_RESULT_CODE = 0;
89 private final int OPENPGP_EXPORT_RESULT_CODE = 1;
91 // `openKeychainInstalled` is accessed from an inner class.
92 private boolean openKeychainInstalled;
95 public void onCreate(Bundle savedInstanceState) {
96 // Get a handle for the shared preferences.
97 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
99 // Get the screenshot preference.
100 boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
102 // Disable screenshots if not allowed.
103 if (!allowScreenshots) {
104 getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
108 setTheme(R.style.PrivacyBrowser);
110 // Run the default commands.
111 super.onCreate(savedInstanceState);
113 // Set the content view.
114 setContentView(R.layout.import_export_coordinatorlayout);
116 // Set the support action bar.
117 Toolbar toolbar = findViewById(R.id.import_export_toolbar);
118 setSupportActionBar(toolbar);
120 // Get a handle for the action bar.
121 ActionBar actionBar = getSupportActionBar();
123 // Remove the incorrect lint warning that the action bar might be null.
124 assert actionBar != null;
126 // Display the home arrow on the support action bar.
127 actionBar.setDisplayHomeAsUpEnabled(true);
129 // Find out if the system is running KitKat
130 boolean runningKitKat = (Build.VERSION.SDK_INT == 19);
132 // Find out if OpenKeychain is installed.
134 openKeychainInstalled = !getPackageManager().getPackageInfo("org.sufficientlysecure.keychain", 0).versionName.isEmpty();
135 } catch (PackageManager.NameNotFoundException exception) {
136 openKeychainInstalled = false;
139 // Get handles for the views that need to be modified.
140 Spinner encryptionSpinner = findViewById(R.id.encryption_spinner);
141 TextInputLayout passwordEncryptionTextInputLayout = findViewById(R.id.password_encryption_textinputlayout);
142 EditText encryptionPasswordEditText = findViewById(R.id.password_encryption_edittext);
143 TextView kitKatPasswordEncryptionTextView = findViewById(R.id.kitkat_password_encryption_textview);
144 TextView openKeychainRequiredTextView = findViewById(R.id.openkeychain_required_textview);
145 CardView fileLocationCardView = findViewById(R.id.file_location_cardview);
146 RadioButton importRadioButton = findViewById(R.id.import_radiobutton);
147 RadioButton exportRadioButton = findViewById(R.id.export_radiobutton);
148 LinearLayout fileNameLinearLayout = findViewById(R.id.file_name_linearlayout);
149 EditText fileNameEditText = findViewById(R.id.file_name_edittext);
150 TextView fileDoesNotExistTextView = findViewById(R.id.file_does_not_exist_textview);
151 TextView fileExistsWarningTextView = findViewById(R.id.file_exists_warning_textview);
152 TextView openKeychainImportInstructionsTextView = findViewById(R.id.openkeychain_import_instructions_textview);
153 Button importExportButton = findViewById(R.id.import_export_button);
154 TextView storagePermissionTextView = findViewById(R.id.import_export_storage_permission_textview);
156 // Create an array adapter for the spinner.
157 ArrayAdapter<CharSequence> encryptionArrayAdapter = ArrayAdapter.createFromResource(this, R.array.encryption_type, R.layout.spinner_item);
159 // Set the drop down view resource on the spinner.
160 encryptionArrayAdapter.setDropDownViewResource(R.layout.spinner_dropdown_items);
162 // Set the array adapter for the spinner.
163 encryptionSpinner.setAdapter(encryptionArrayAdapter);
165 // Initially hide the unneeded views.
166 passwordEncryptionTextInputLayout.setVisibility(View.GONE);
167 kitKatPasswordEncryptionTextView.setVisibility(View.GONE);
168 openKeychainRequiredTextView.setVisibility(View.GONE);
169 fileNameLinearLayout.setVisibility(View.GONE);
170 fileDoesNotExistTextView.setVisibility(View.GONE);
171 fileExistsWarningTextView.setVisibility(View.GONE);
172 openKeychainImportInstructionsTextView.setVisibility(View.GONE);
173 importExportButton.setVisibility(View.GONE);
175 // Instantiate the download location helper.
176 DownloadLocationHelper downloadLocationHelper = new DownloadLocationHelper();
178 // Get the default file path.
179 String defaultFilePath = downloadLocationHelper.getDownloadLocation(this) + "/" + getString(R.string.settings_pbs);
181 // Set the other default file paths.
182 String defaultPasswordEncryptionFilePath = defaultFilePath + ".aes";
183 String defaultPgpFilePath = defaultFilePath + ".pgp";
185 // Set the default file path.
186 fileNameEditText.setText(defaultFilePath);
188 // Hide the storage permission text view if the permission has already been granted.
189 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
190 storagePermissionTextView.setVisibility(View.GONE);
193 // Update the UI when the spinner changes.
194 encryptionSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
196 public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
199 // Hide the unneeded layout items.
200 passwordEncryptionTextInputLayout.setVisibility(View.GONE);
201 kitKatPasswordEncryptionTextView.setVisibility(View.GONE);
202 openKeychainRequiredTextView.setVisibility(View.GONE);
203 openKeychainImportInstructionsTextView.setVisibility(View.GONE);
205 // Show the file location card.
206 fileLocationCardView.setVisibility(View.VISIBLE);
208 // Show the file name linear layout if either import or export is checked.
209 if (importRadioButton.isChecked() || exportRadioButton.isChecked()) {
210 fileNameLinearLayout.setVisibility(View.VISIBLE);
213 // Reset the text of the import button, which may have been changed to `Decrypt`.
214 if (importRadioButton.isChecked()) {
215 importExportButton.setText(R.string.import_button);
218 // Reset the default file path.
219 fileNameEditText.setText(defaultFilePath);
222 case PASSWORD_ENCRYPTION:
224 // Show the KitKat password encryption message.
225 kitKatPasswordEncryptionTextView.setVisibility(View.VISIBLE);
227 // Hide the OpenPGP required text view and the file location card.
228 openKeychainRequiredTextView.setVisibility(View.GONE);
229 fileLocationCardView.setVisibility(View.GONE);
231 // Hide the OpenPGP layout items.
232 openKeychainRequiredTextView.setVisibility(View.GONE);
233 openKeychainImportInstructionsTextView.setVisibility(View.GONE);
235 // Show the password encryption layout items.
236 passwordEncryptionTextInputLayout.setVisibility(View.VISIBLE);
238 // Show the file location card.
239 fileLocationCardView.setVisibility(View.VISIBLE);
241 // Show the file name linear layout if either import or export is checked.
242 if (importRadioButton.isChecked() || exportRadioButton.isChecked()) {
243 fileNameLinearLayout.setVisibility(View.VISIBLE);
246 // Reset the text of the import button, which may have been changed to `Decrypt`.
247 if (importRadioButton.isChecked()) {
248 importExportButton.setText(R.string.import_button);
251 // Update the default file path.
252 fileNameEditText.setText(defaultPasswordEncryptionFilePath);
256 case OPENPGP_ENCRYPTION:
257 // Hide the password encryption layout items.
258 passwordEncryptionTextInputLayout.setVisibility(View.GONE);
259 kitKatPasswordEncryptionTextView.setVisibility(View.GONE);
261 // Updated items based on the installation status of OpenKeychain.
262 if (openKeychainInstalled) { // OpenKeychain is installed.
263 // Update the default file path.
264 fileNameEditText.setText(defaultPgpFilePath);
266 // Show the file location card.
267 fileLocationCardView.setVisibility(View.VISIBLE);
269 if (importRadioButton.isChecked()) {
270 // Show the file name linear layout and the OpenKeychain import instructions.
271 fileNameLinearLayout.setVisibility(View.VISIBLE);
272 openKeychainImportInstructionsTextView.setVisibility(View.VISIBLE);
274 // Set the text of the import button to be `Decrypt`.
275 importExportButton.setText(R.string.decrypt);
276 } else if (exportRadioButton.isChecked()) {
277 // Hide the file name linear layout and the OpenKeychain import instructions.
278 fileNameLinearLayout.setVisibility(View.GONE);
279 openKeychainImportInstructionsTextView.setVisibility(View.GONE);
281 } else { // OpenKeychain is not installed.
282 // Show the OpenPGP required layout item.
283 openKeychainRequiredTextView.setVisibility(View.VISIBLE);
285 // Hide the file location card.
286 fileLocationCardView.setVisibility(View.GONE);
293 public void onNothingSelected(AdapterView<?> parent) {
298 // Update the status of the import/export button when the password changes.
299 encryptionPasswordEditText.addTextChangedListener(new TextWatcher() {
301 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
306 public void onTextChanged(CharSequence s, int start, int before, int count) {
311 public void afterTextChanged(Editable s) {
312 // Get the current file name.
313 String fileNameString = fileNameEditText.getText().toString();
315 // Convert the file name string to a file.
316 File file = new File(fileNameString);
318 // Update the import/export button.
319 if (importRadioButton.isChecked()) { // The import radio button is checked.
320 // Enable the import button if the file and the password exists.
321 importExportButton.setEnabled(file.exists() && !encryptionPasswordEditText.getText().toString().isEmpty());
322 } else if (exportRadioButton.isChecked()) { // The export radio button is checked.
323 // Enable the export button if the file string and the password exists.
324 importExportButton.setEnabled(!fileNameString.isEmpty() && !encryptionPasswordEditText.getText().toString().isEmpty());
329 // Update the UI when the file name EditText changes.
330 fileNameEditText.addTextChangedListener(new TextWatcher() {
332 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
337 public void onTextChanged(CharSequence s, int start, int before, int count) {
342 public void afterTextChanged(Editable s) {
343 // Get the current file name.
344 String fileNameString = fileNameEditText.getText().toString();
346 // Convert the file name string to a file.
347 File file = new File(fileNameString);
349 // Adjust the UI according to the encryption spinner position.
350 switch (encryptionSpinner.getSelectedItemPosition()) {
352 // Determine if import or export is checked.
353 if (exportRadioButton.isChecked()) { // The export radio button is checked.
354 // Hide the file does not exist text view.
355 fileDoesNotExistTextView.setVisibility(View.GONE);
357 // Display a warning if the file already exists.
359 fileExistsWarningTextView.setVisibility(View.VISIBLE);
361 fileExistsWarningTextView.setVisibility(View.GONE);
364 // Enable the export button if the file name is populated.
365 importExportButton.setEnabled(!fileNameString.isEmpty());
366 } else if (importRadioButton.isChecked()) { // The import radio button is checked.
367 // Hide the file exists warning text view.
368 fileExistsWarningTextView.setVisibility(View.GONE);
370 // Check if the file exists.
371 if (file.exists()) { // The file exists.
372 // Hide the notification that the file does not exist.
373 fileDoesNotExistTextView.setVisibility(View.GONE);
375 // Enable the import button.
376 importExportButton.setEnabled(true);
377 } else { // The file does not exist.
378 // Show a notification that the file does not exist.
379 fileDoesNotExistTextView.setVisibility(View.VISIBLE);
381 // Disable the import button.
382 importExportButton.setEnabled(false);
384 } else { // Neither radio button is checked.
385 // Hide the file notification text views.
386 fileExistsWarningTextView.setVisibility(View.GONE);
387 fileDoesNotExistTextView.setVisibility(View.GONE);
391 case PASSWORD_ENCRYPTION:
392 // Determine if import or export is checked.
393 if (exportRadioButton.isChecked()) { // The export radio button is checked.
394 // Hide the notification that the file does not exist.
395 fileDoesNotExistTextView.setVisibility(View.GONE);
397 // Display a warning if the file already exists.
399 fileExistsWarningTextView.setVisibility(View.VISIBLE);
401 fileExistsWarningTextView.setVisibility(View.GONE);
404 // Enable the export button if the file name and the password are populated.
405 importExportButton.setEnabled(!fileNameString.isEmpty() && !encryptionPasswordEditText.getText().toString().isEmpty());
406 } else if (importRadioButton.isChecked()) { // The import radio button is checked.
407 // Hide the file exists warning text view.
408 fileExistsWarningTextView.setVisibility(View.GONE);
410 // Check if the file exists.
411 if (file.exists()) { // The file exists.
412 // Hide the notification that the file does not exist.
413 fileDoesNotExistTextView.setVisibility(View.GONE);
415 // Enable the import button if the password is populated.
416 importExportButton.setEnabled(!encryptionPasswordEditText.getText().toString().isEmpty());
417 } else { // The file does not exist.
418 // Show a notification that the file does not exist.
419 fileDoesNotExistTextView.setVisibility(View.VISIBLE);
421 // Disable the import button.
422 importExportButton.setEnabled(false);
424 } else { // Neither radio button is checked.
425 // Hide the file notification text views.
426 fileExistsWarningTextView.setVisibility(View.GONE);
427 fileDoesNotExistTextView.setVisibility(View.GONE);
431 case OPENPGP_ENCRYPTION:
432 // Hide the file exists warning text view.
433 fileExistsWarningTextView.setVisibility(View.GONE);
435 if (importRadioButton.isChecked()) { // The import radio button is checked.
436 if (file.exists()) { // The file exists.
437 // Hide the notification that the file does not exist.
438 fileDoesNotExistTextView.setVisibility(View.GONE);
440 // Enable the import button if OpenKeychain is installed.
441 importExportButton.setEnabled(openKeychainInstalled);
442 } else { // The file does not exist.
443 // Show the notification that the file does not exist.
444 fileDoesNotExistTextView.setVisibility(View.VISIBLE);
446 // Disable the import button.
447 importExportButton.setEnabled(false);
449 } else if (exportRadioButton.isChecked()){ // The export radio button is checked.
450 // Hide the notification that the file does not exist.
451 fileDoesNotExistTextView.setVisibility(View.GONE);
453 // Enable the export button.
454 importExportButton.setEnabled(true);
455 } else { // Neither radio button is checked.
456 // Hide the notification that the file does not exist.
457 fileDoesNotExistTextView.setVisibility(View.GONE);
465 public void onClickRadioButton(View view) {
466 // Get handles for the views.
467 Spinner encryptionSpinner = findViewById(R.id.encryption_spinner);
468 LinearLayout fileNameLinearLayout = findViewById(R.id.file_name_linearlayout);
469 EditText passwordEncryptionEditText = findViewById(R.id.password_encryption_edittext);
470 EditText fileNameEditText = findViewById(R.id.file_name_edittext);
471 TextView fileDoesNotExistTextView = findViewById(R.id.file_does_not_exist_textview);
472 TextView fileExistsWarningTextView = findViewById(R.id.file_exists_warning_textview);
473 TextView openKeychainImportInstructionTextView = findViewById(R.id.openkeychain_import_instructions_textview);
474 Button importExportButton = findViewById(R.id.import_export_button);
476 // Get the current file name.
477 String fileNameString = fileNameEditText.getText().toString();
479 // Convert the file name string to a file.
480 File file = new File(fileNameString);
482 // Check to see if import or export was selected.
483 switch (view.getId()) {
484 case R.id.import_radiobutton:
485 // Check to see if OpenPGP encryption is selected.
486 if (encryptionSpinner.getSelectedItemPosition() == OPENPGP_ENCRYPTION) { // OpenPGP encryption selected.
487 // Show the OpenKeychain import instructions.
488 openKeychainImportInstructionTextView.setVisibility(View.VISIBLE);
490 // Set the text on the import/export button to be `Decrypt`.
491 importExportButton.setText(R.string.decrypt);
492 } else { // OpenPGP encryption not selected.
493 // Hide the OpenKeychain import instructions.
494 openKeychainImportInstructionTextView.setVisibility(View.GONE);
496 // Set the text on the import/export button to be `Import`.
497 importExportButton.setText(R.string.import_button);
500 // Hide the file exists warning text view.
501 fileExistsWarningTextView.setVisibility(View.GONE);
503 // Display the file name views.
504 fileNameLinearLayout.setVisibility(View.VISIBLE);
505 importExportButton.setVisibility(View.VISIBLE);
507 // Check to see if the file exists.
508 if (file.exists()) { // The file exists.
509 // Hide the notification that the file does not exist.
510 fileDoesNotExistTextView.setVisibility(View.GONE);
512 // Check to see if password encryption is selected.
513 if (encryptionSpinner.getSelectedItemPosition() == PASSWORD_ENCRYPTION) { // Password encryption is selected.
514 // Enable the import button if the encryption password is populated.
515 importExportButton.setEnabled(!passwordEncryptionEditText.getText().toString().isEmpty());
516 } else { // Password encryption is not selected.
517 // Enable the import/decrypt button.
518 importExportButton.setEnabled(true);
520 } else { // The file does not exist.
521 // Show the notification that the file does not exist.
522 fileDoesNotExistTextView.setVisibility(View.VISIBLE);
524 // Disable the import/decrypt button.
525 importExportButton.setEnabled(false);
529 case R.id.export_radiobutton:
530 // Hide the OpenKeychain import instructions.
531 openKeychainImportInstructionTextView.setVisibility(View.GONE);
533 // Set the text on the import/export button to be `Export`.
534 importExportButton.setText(R.string.export);
536 // Show the import/export button.
537 importExportButton.setVisibility(View.VISIBLE);
539 // Check to see if OpenPGP encryption is selected.
540 if (encryptionSpinner.getSelectedItemPosition() == OPENPGP_ENCRYPTION) { // OpenPGP encryption is selected.
541 // Hide the file name views.
542 fileNameLinearLayout.setVisibility(View.GONE);
543 fileDoesNotExistTextView.setVisibility(View.GONE);
544 fileExistsWarningTextView.setVisibility(View.GONE);
546 // Enable the export button.
547 importExportButton.setEnabled(true);
548 } else { // OpenPGP encryption is not selected.
549 // Show the file name view.
550 fileNameLinearLayout.setVisibility(View.VISIBLE);
552 // Hide the notification that the file name does not exist.
553 fileDoesNotExistTextView.setVisibility(View.GONE);
555 // Display a warning if the file already exists.
557 fileExistsWarningTextView.setVisibility(View.VISIBLE);
559 fileExistsWarningTextView.setVisibility(View.GONE);
562 // Check the encryption type.
563 if (encryptionSpinner.getSelectedItemPosition() == NO_ENCRYPTION) { // No encryption is selected.
564 // Enable the export button if the file name is populated.
565 importExportButton.setEnabled(!fileNameString.isEmpty());
566 } else { // Password encryption is selected.
567 // Enable the export button if the file name and the password are populated.
568 importExportButton.setEnabled(!fileNameString.isEmpty() && !passwordEncryptionEditText.getText().toString().isEmpty());
575 public void browse(View view) {
576 // Get a handle for the views.
577 Spinner encryptionSpinner = findViewById(R.id.encryption_spinner);
578 RadioButton importRadioButton = findViewById(R.id.import_radiobutton);
580 // Check to see if import or export is selected.
581 if (importRadioButton.isChecked()) { // Import is selected.
582 // Create the file picker intent.
583 Intent importBrowseIntent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
585 // Set the intent MIME type to include all files so that everything is visible.
586 importBrowseIntent.setType("*/*");
588 // Set the initial directory if the minimum API >= 26.
589 if (Build.VERSION.SDK_INT >= 26) {
590 importBrowseIntent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, Environment.getExternalStorageDirectory());
593 // Request a file that can be opened.
594 importBrowseIntent.addCategory(Intent.CATEGORY_OPENABLE);
596 // Launch the file picker.
597 startActivityForResult(importBrowseIntent, BROWSE_RESULT_CODE);
598 } else { // Export is selected
599 // Create the file picker intent.
600 Intent exportBrowseIntent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
602 // Set the intent MIME type to include all files so that everything is visible.
603 exportBrowseIntent.setType("*/*");
605 // Set the initial export file name according to the encryption type.
606 if (encryptionSpinner.getSelectedItemPosition() == NO_ENCRYPTION) { // No encryption is selected.
607 exportBrowseIntent.putExtra(Intent.EXTRA_TITLE, getString(R.string.settings_pbs));
608 } else { // Password encryption is selected.
609 exportBrowseIntent.putExtra(Intent.EXTRA_TITLE, getString(R.string.settings_pbs) + ".aes");
612 // Set the initial directory if the minimum API >= 26.
613 if (Build.VERSION.SDK_INT >= 26) {
614 exportBrowseIntent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, Environment.getExternalStorageDirectory());
617 // Request a file that can be opened.
618 exportBrowseIntent.addCategory(Intent.CATEGORY_OPENABLE);
620 // Launch the file picker.
621 startActivityForResult(exportBrowseIntent, BROWSE_RESULT_CODE);
625 public void importExport(View view) {
626 // Get a handle for the views.
627 Spinner encryptionSpinner = findViewById(R.id.encryption_spinner);
628 RadioButton importRadioButton = findViewById(R.id.import_radiobutton);
629 RadioButton exportRadioButton = findViewById(R.id.export_radiobutton);
631 // Check to see if the storage permission is needed.
632 if ((encryptionSpinner.getSelectedItemPosition() == OPENPGP_ENCRYPTION) && exportRadioButton.isChecked()) { // Permission not needed to export via OpenKeychain.
633 // Export the settings.
635 } else if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // The storage permission has been granted.
636 // Check to see if import or export is selected.
637 if (importRadioButton.isChecked()) { // Import is selected.
638 // Import the settings.
640 } else { // Export is selected.
641 // Export the settings.
644 } else { // The storage permission has not been granted.
645 // Get a handle for the file name EditText.
646 EditText fileNameEditText = findViewById(R.id.file_name_edittext);
648 // Get the file name string.
649 String fileNameString = fileNameEditText.getText().toString();
651 // Get the external private directory `File`.
652 File externalPrivateDirectoryFile = getExternalFilesDir(null);
654 // Remove the incorrect lint error below that the file might be null.
655 assert externalPrivateDirectoryFile != null;
657 // Get the external private directory string.
658 String externalPrivateDirectory = externalPrivateDirectoryFile.toString();
660 // Check to see if the file path is in the external private directory.
661 if (fileNameString.startsWith(externalPrivateDirectory)) { // The file path is in the external private directory.
662 // Check to see if import or export is selected.
663 if (importRadioButton.isChecked()) { // Import is selected.
664 // Import the settings.
666 } else { // Export is selected.
667 // Export the settings.
670 } else { // The file path is in a public directory.
671 // Check if the user has previously denied the storage permission.
672 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
673 // Instantiate the storage permission alert dialog.
674 DialogFragment storagePermissionDialogFragment = StoragePermissionDialog.displayDialog(0);
676 // Show the storage permission alert dialog. The permission will be requested when the dialog is closed.
677 storagePermissionDialogFragment.show(getSupportFragmentManager(), getString(R.string.storage_permission));
678 } else { // Show the permission request directly.
679 // Request the storage permission. The export will be run when it finishes.
680 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
687 public void onCloseStoragePermissionDialog(int type) {
688 // Request the write external storage permission. The import/export will be run when it finishes.
689 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
693 public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
694 // Get a handle for the import radiobutton.
695 RadioButton importRadioButton = findViewById(R.id.import_radiobutton);
697 // Check to see if the storage permission was granted. If the dialog was canceled the grant results will be empty.
698 if ((grantResults.length > 0) && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) { // The storage permission was granted.
699 // Run the import or export methods according to which radio button is selected.
700 if (importRadioButton.isChecked()) { // Import is selected.
701 // Import the settings.
703 } else { // Export is selected.
704 // Export the settings.
707 } else { // The storage permission was not granted.
708 // Display an error snackbar.
709 Snackbar.make(importRadioButton, getString(R.string.cannot_use_location), Snackbar.LENGTH_LONG).show();
714 public void onActivityResult(int requestCode, int resultCode, Intent intent) {
715 // Run the default commands.
716 super.onActivityResult(requestCode, resultCode, intent);
718 switch (requestCode) {
719 case (BROWSE_RESULT_CODE):
720 // Don't do anything if the user pressed back from the file picker.
721 if (resultCode == Activity.RESULT_OK) {
722 // Get a handle for the views.
723 EditText fileNameEditText = findViewById(R.id.file_name_edittext);
724 TextView fileExistsWarningTextView = findViewById(R.id.file_exists_warning_textview);
726 // Instantiate the file name helper.
727 FileNameHelper fileNameHelper = new FileNameHelper();
729 // Get the file path URI from the intent.
730 Uri filePathUri = intent.getData();
732 // Use the file path from the intent if it exists.
733 if (filePathUri != null) {
734 // Convert the file name URI to a file name path.
735 String fileNamePath = fileNameHelper.convertUriToFileNamePath(filePathUri);
737 // Set the file name path as the text of the file name edit text.
738 fileNameEditText.setText(fileNamePath);
740 // Hide the file exists warning text view, because the file picker will have just created a file if export was selected.
741 fileExistsWarningTextView.setVisibility(View.GONE);
746 case OPENPGP_EXPORT_RESULT_CODE:
747 // Get the temporary unencrypted export file.
748 File temporaryUnencryptedExportFile = new File(getApplicationContext().getCacheDir() + "/" + getString(R.string.settings_pbs));
750 // Delete the temporary unencrypted export file if it exists.
751 if (temporaryUnencryptedExportFile.exists()) {
752 //noinspection ResultOfMethodCallIgnored
753 temporaryUnencryptedExportFile.delete();
759 private void exportSettings() {
760 // Get a handle for the views.
761 Spinner encryptionSpinner = findViewById(R.id.encryption_spinner);
762 EditText fileNameEditText = findViewById(R.id.file_name_edittext);
764 // Instantiate the import export database helper.
765 ImportExportDatabaseHelper importExportDatabaseHelper = new ImportExportDatabaseHelper();
767 // Get the export file string.
768 String exportFileString = fileNameEditText.getText().toString();
770 // Get the export and temporary unencrypted export files.
771 File exportFile = new File(exportFileString);
772 File temporaryUnencryptedExportFile = new File(getApplicationContext().getCacheDir() + "/" + getString(R.string.settings_pbs));
774 // Create an export status string.
777 // Export according to the encryption type.
778 switch (encryptionSpinner.getSelectedItemPosition()) {
780 // Export the unencrypted file.
781 exportStatus = importExportDatabaseHelper.exportUnencrypted(exportFile, this);
783 // Show a disposition snackbar.
784 if (exportStatus.equals(ImportExportDatabaseHelper.EXPORT_SUCCESSFUL)) {
785 Snackbar.make(fileNameEditText, getString(R.string.export_successful), Snackbar.LENGTH_SHORT).show();
787 Snackbar.make(fileNameEditText, getString(R.string.export_failed) + " " + exportStatus, Snackbar.LENGTH_INDEFINITE).show();
791 case PASSWORD_ENCRYPTION:
792 // Create an unencrypted export in a private directory.
793 exportStatus = importExportDatabaseHelper.exportUnencrypted(temporaryUnencryptedExportFile, this);
796 // Create an unencrypted export file input stream.
797 FileInputStream unencryptedExportFileInputStream = new FileInputStream(temporaryUnencryptedExportFile);
799 // Delete the encrypted export file if it exists.
800 if (exportFile.exists()) {
801 //noinspection ResultOfMethodCallIgnored
805 // Create an encrypted export file output stream.
806 FileOutputStream encryptedExportFileOutputStream = new FileOutputStream(exportFile);
808 // Get a handle for the encryption password EditText.
809 EditText encryptionPasswordEditText = findViewById(R.id.password_encryption_edittext);
811 // Get the encryption password.
812 String encryptionPasswordString = encryptionPasswordEditText.getText().toString();
814 // Initialize a secure random number generator.
815 SecureRandom secureRandom = new SecureRandom();
817 // Get a 256 bit (32 byte) random salt.
818 byte[] saltByteArray = new byte[32];
819 secureRandom.nextBytes(saltByteArray);
821 // Convert the encryption password to a byte array.
822 byte[] encryptionPasswordByteArray = encryptionPasswordString.getBytes(StandardCharsets.UTF_8);
824 // Append the salt to the encryption password byte array. This protects against rainbow table attacks.
825 byte[] encryptionPasswordWithSaltByteArray = new byte[encryptionPasswordByteArray.length + saltByteArray.length];
826 System.arraycopy(encryptionPasswordByteArray, 0, encryptionPasswordWithSaltByteArray, 0, encryptionPasswordByteArray.length);
827 System.arraycopy(saltByteArray, 0, encryptionPasswordWithSaltByteArray, encryptionPasswordByteArray.length, saltByteArray.length);
829 // Get a SHA-512 message digest.
830 MessageDigest messageDigest = MessageDigest.getInstance("SHA-512");
832 // Hash the salted encryption password. Otherwise, any characters after the 32nd character in the password are ignored.
833 byte[] hashedEncryptionPasswordWithSaltByteArray = messageDigest.digest(encryptionPasswordWithSaltByteArray);
835 // Truncate the encryption password byte array to 256 bits (32 bytes).
836 byte[] truncatedHashedEncryptionPasswordWithSaltByteArray = Arrays.copyOf(hashedEncryptionPasswordWithSaltByteArray, 32);
838 // Create an AES secret key from the encryption password byte array.
839 SecretKeySpec secretKey = new SecretKeySpec(truncatedHashedEncryptionPasswordWithSaltByteArray, "AES");
841 // Generate a random 12 byte initialization vector. According to NIST, a 12 byte initialization vector is more secure than a 16 byte one.
842 byte[] initializationVector = new byte[12];
843 secureRandom.nextBytes(initializationVector);
845 // 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.
846 Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
848 // Set the GCM tag length to be 128 bits (the maximum) and apply the initialization vector.
849 GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, initializationVector);
851 // Initialize the cipher.
852 cipher.init(Cipher.ENCRYPT_MODE, secretKey, gcmParameterSpec);
854 // Add the salt and the initialization vector to the export file.
855 encryptedExportFileOutputStream.write(saltByteArray);
856 encryptedExportFileOutputStream.write(initializationVector);
858 // Create a cipher output stream.
859 CipherOutputStream cipherOutputStream = new CipherOutputStream(encryptedExportFileOutputStream, cipher);
861 // 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.
862 int numberOfBytesRead;
863 byte[] encryptedBytes = new byte[16];
865 // 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.
866 while ((numberOfBytesRead = unencryptedExportFileInputStream.read(encryptedBytes)) != -1) {
867 // Write the data to the cipher output stream.
868 cipherOutputStream.write(encryptedBytes, 0, numberOfBytesRead);
871 // Close the streams.
872 cipherOutputStream.flush();
873 cipherOutputStream.close();
874 encryptedExportFileOutputStream.close();
875 unencryptedExportFileInputStream.close();
877 // Wipe the encryption data from memory.
878 //noinspection UnusedAssignment
879 encryptionPasswordString = "";
880 Arrays.fill(saltByteArray, (byte) 0);
881 Arrays.fill(encryptionPasswordByteArray, (byte) 0);
882 Arrays.fill(encryptionPasswordWithSaltByteArray, (byte) 0);
883 Arrays.fill(hashedEncryptionPasswordWithSaltByteArray, (byte) 0);
884 Arrays.fill(truncatedHashedEncryptionPasswordWithSaltByteArray, (byte) 0);
885 Arrays.fill(initializationVector, (byte) 0);
886 Arrays.fill(encryptedBytes, (byte) 0);
888 // Delete the temporary unencrypted export file.
889 //noinspection ResultOfMethodCallIgnored
890 temporaryUnencryptedExportFile.delete();
891 } catch (Exception exception) {
892 exportStatus = exception.toString();
895 // Show a disposition snackbar.
896 if (exportStatus.equals(ImportExportDatabaseHelper.EXPORT_SUCCESSFUL)) {
897 Snackbar.make(fileNameEditText, getString(R.string.export_successful), Snackbar.LENGTH_SHORT).show();
899 Snackbar.make(fileNameEditText, getString(R.string.export_failed) + " " + exportStatus, Snackbar.LENGTH_INDEFINITE).show();
903 case OPENPGP_ENCRYPTION:
904 // Create an unencrypted export in the private location.
905 importExportDatabaseHelper.exportUnencrypted(temporaryUnencryptedExportFile, this);
907 // Create an encryption intent for OpenKeychain.
908 Intent openKeychainEncryptIntent = new Intent("org.sufficientlysecure.keychain.action.ENCRYPT_DATA");
910 // Include the temporary unencrypted export file URI.
911 openKeychainEncryptIntent.setData(FileProvider.getUriForFile(this, getString(R.string.file_provider), temporaryUnencryptedExportFile));
913 // Allow OpenKeychain to read the file URI.
914 openKeychainEncryptIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
916 // Send the intent to the OpenKeychain package.
917 openKeychainEncryptIntent.setPackage("org.sufficientlysecure.keychain");
920 startActivityForResult(openKeychainEncryptIntent, OPENPGP_EXPORT_RESULT_CODE);
924 // Add the file to the list of recent files. This doesn't currently work, but maybe it will someday.
925 MediaScannerConnection.scanFile(this, new String[] {exportFileString}, new String[] {"application/x-sqlite3"}, null);
928 private void importSettings() {
929 // Get a handle for the views.
930 Spinner encryptionSpinner = findViewById(R.id.encryption_spinner);
931 EditText fileNameEditText = findViewById(R.id.file_name_edittext);
933 // Instantiate the import export database helper.
934 ImportExportDatabaseHelper importExportDatabaseHelper = new ImportExportDatabaseHelper();
936 // Get the import file.
937 File importFile = new File(fileNameEditText.getText().toString());
939 // Initialize the import status string
940 String importStatus = "";
942 // Import according to the encryption type.
943 switch (encryptionSpinner.getSelectedItemPosition()) {
945 // Import the unencrypted file.
946 importStatus = importExportDatabaseHelper.importUnencrypted(importFile, this);
949 case PASSWORD_ENCRYPTION:
950 // Use a private temporary import location.
951 File temporaryUnencryptedImportFile = new File(getApplicationContext().getCacheDir() + "/" + getString(R.string.settings_pbs));
954 // Create an encrypted import file input stream.
955 FileInputStream encryptedImportFileInputStream = new FileInputStream(importFile);
957 // Delete the temporary import file if it exists.
958 if (temporaryUnencryptedImportFile.exists()) {
959 //noinspection ResultOfMethodCallIgnored
960 temporaryUnencryptedImportFile.delete();
963 // Create an unencrypted import file output stream.
964 FileOutputStream unencryptedImportFileOutputStream = new FileOutputStream(temporaryUnencryptedImportFile);
966 // Get a handle for the encryption password EditText.
967 EditText encryptionPasswordEditText = findViewById(R.id.password_encryption_edittext);
969 // Get the encryption password.
970 String encryptionPasswordString = encryptionPasswordEditText.getText().toString();
972 // Get the salt from the beginning of the import file.
973 byte[] saltByteArray = new byte[32];
974 //noinspection ResultOfMethodCallIgnored
975 encryptedImportFileInputStream.read(saltByteArray);
977 // Get the initialization vector from the import file.
978 byte[] initializationVector = new byte[12];
979 //noinspection ResultOfMethodCallIgnored
980 encryptedImportFileInputStream.read(initializationVector);
982 // Convert the encryption password to a byte array.
983 byte[] encryptionPasswordByteArray = encryptionPasswordString.getBytes(StandardCharsets.UTF_8);
985 // Append the salt to the encryption password byte array. This protects against rainbow table attacks.
986 byte[] encryptionPasswordWithSaltByteArray = new byte[encryptionPasswordByteArray.length + saltByteArray.length];
987 System.arraycopy(encryptionPasswordByteArray, 0, encryptionPasswordWithSaltByteArray, 0, encryptionPasswordByteArray.length);
988 System.arraycopy(saltByteArray, 0, encryptionPasswordWithSaltByteArray, encryptionPasswordByteArray.length, saltByteArray.length);
990 // Get a SHA-512 message digest.
991 MessageDigest messageDigest = MessageDigest.getInstance("SHA-512");
993 // Hash the salted encryption password. Otherwise, any characters after the 32nd character in the password are ignored.
994 byte[] hashedEncryptionPasswordWithSaltByteArray = messageDigest.digest(encryptionPasswordWithSaltByteArray);
996 // Truncate the encryption password byte array to 256 bits (32 bytes).
997 byte[] truncatedHashedEncryptionPasswordWithSaltByteArray = Arrays.copyOf(hashedEncryptionPasswordWithSaltByteArray, 32);
999 // Create an AES secret key from the encryption password byte array.
1000 SecretKeySpec secretKey = new SecretKeySpec(truncatedHashedEncryptionPasswordWithSaltByteArray, "AES");
1002 // 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.
1003 Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
1005 // Set the GCM tag length to be 128 bits (the maximum) and apply the initialization vector.
1006 GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, initializationVector);
1008 // Initialize the cipher.
1009 cipher.init(Cipher.DECRYPT_MODE, secretKey, gcmParameterSpec);
1011 // Create a cipher input stream.
1012 CipherInputStream cipherInputStream = new CipherInputStream(encryptedImportFileInputStream, cipher);
1014 // 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.
1015 int numberOfBytesRead;
1016 byte[] decryptedBytes = new byte[16];
1018 // 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.
1019 while ((numberOfBytesRead = cipherInputStream.read(decryptedBytes)) != -1) {
1020 // Write the data to the unencrypted import file output stream.
1021 unencryptedImportFileOutputStream.write(decryptedBytes, 0, numberOfBytesRead);
1024 // Close the streams.
1025 unencryptedImportFileOutputStream.flush();
1026 unencryptedImportFileOutputStream.close();
1027 cipherInputStream.close();
1028 encryptedImportFileInputStream.close();
1030 // Wipe the encryption data from memory.
1031 //noinspection UnusedAssignment
1032 encryptionPasswordString = "";
1033 Arrays.fill(saltByteArray, (byte) 0);
1034 Arrays.fill(initializationVector, (byte) 0);
1035 Arrays.fill(encryptionPasswordByteArray, (byte) 0);
1036 Arrays.fill(encryptionPasswordWithSaltByteArray, (byte) 0);
1037 Arrays.fill(hashedEncryptionPasswordWithSaltByteArray, (byte) 0);
1038 Arrays.fill(truncatedHashedEncryptionPasswordWithSaltByteArray, (byte) 0);
1039 Arrays.fill(decryptedBytes, (byte) 0);
1041 // Import the unencrypted database from the private location.
1042 importStatus = importExportDatabaseHelper.importUnencrypted(temporaryUnencryptedImportFile, this);
1044 // Delete the temporary unencrypted import file.
1045 //noinspection ResultOfMethodCallIgnored
1046 temporaryUnencryptedImportFile.delete();
1047 } catch (Exception exception) {
1048 importStatus = exception.toString();
1052 case OPENPGP_ENCRYPTION:
1054 // Create an decryption intent for OpenKeychain.
1055 Intent openKeychainDecryptIntent = new Intent("org.sufficientlysecure.keychain.action.DECRYPT_DATA");
1057 // Include the URI to be decrypted.
1058 openKeychainDecryptIntent.setData(FileProvider.getUriForFile(this, getString(R.string.file_provider), importFile));
1060 // Allow OpenKeychain to read the file URI.
1061 openKeychainDecryptIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
1063 // Send the intent to the OpenKeychain package.
1064 openKeychainDecryptIntent.setPackage("org.sufficientlysecure.keychain");
1067 startActivity(openKeychainDecryptIntent);
1068 } catch (IllegalArgumentException exception) { // The file import location is not valid.
1069 // Display a snack bar with the import error.
1070 Snackbar.make(fileNameEditText, getString(R.string.import_failed) + " " + exception.toString(), Snackbar.LENGTH_INDEFINITE).show();
1075 // Respond to the import disposition.
1076 if (importStatus.equals(ImportExportDatabaseHelper.IMPORT_SUCCESSFUL)) { // The import was successful.
1077 // Create an intent to restart Privacy Browser.
1078 Intent restartIntent = getParentActivityIntent();
1080 // Assert that the intent is not null to remove the lint error below.
1081 assert restartIntent != null;
1083 // `Intent.FLAG_ACTIVITY_CLEAR_TASK` removes all activities from the stack. It requires `Intent.FLAG_ACTIVITY_NEW_TASK`.
1084 restartIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
1086 // Create a restart handler.
1087 Handler restartHandler = new Handler();
1089 // Create a restart runnable.
1090 Runnable restartRunnable = () -> {
1091 // Restart Privacy Browser.
1092 startActivity(restartIntent);
1094 // Kill this instance of Privacy Browser. Otherwise, the app exhibits sporadic behavior after the restart.
1098 // Restart Privacy Browser after 150 milliseconds to allow enough time for the preferences to be saved.
1099 restartHandler.postDelayed(restartRunnable, 150);
1101 } else if (!(encryptionSpinner.getSelectedItemPosition() == OPENPGP_ENCRYPTION)){ // The import was not successful.
1102 // Display a snack bar with the import error.
1103 Snackbar.make(fileNameEditText, getString(R.string.import_failed) + " " + importStatus, Snackbar.LENGTH_INDEFINITE).show();