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 theme and screenshot preferences.
100 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
101 boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
103 // Disable screenshots if not allowed.
104 if (!allowScreenshots) {
105 getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
108 // Set the activity theme.
110 setTheme(R.style.PrivacyBrowserDark_SecondaryActivity);
112 setTheme(R.style.PrivacyBrowserLight_SecondaryActivity);
115 // Run the default commands.
116 super.onCreate(savedInstanceState);
118 // Set the content view.
119 setContentView(R.layout.import_export_coordinatorlayout);
121 // Set the support action bar.
122 Toolbar toolbar = findViewById(R.id.import_export_toolbar);
123 setSupportActionBar(toolbar);
125 // Get a handle for the action bar.
126 ActionBar actionBar = getSupportActionBar();
128 // Remove the incorrect lint warning that the action bar might be null.
129 assert actionBar != null;
131 // Display the home arrow on the support action bar.
132 actionBar.setDisplayHomeAsUpEnabled(true);
134 // Find out if the system is running KitKat
135 boolean runningKitKat = (Build.VERSION.SDK_INT == 19);
137 // Find out if OpenKeychain is installed.
139 openKeychainInstalled = !getPackageManager().getPackageInfo("org.sufficientlysecure.keychain", 0).versionName.isEmpty();
140 } catch (PackageManager.NameNotFoundException exception) {
141 openKeychainInstalled = false;
144 // Get handles for the views that need to be modified.
145 Spinner encryptionSpinner = findViewById(R.id.encryption_spinner);
146 TextInputLayout passwordEncryptionTextInputLayout = findViewById(R.id.password_encryption_textinputlayout);
147 EditText encryptionPasswordEditText = findViewById(R.id.password_encryption_edittext);
148 TextView kitKatPasswordEncryptionTextView = findViewById(R.id.kitkat_password_encryption_textview);
149 TextView openKeychainRequiredTextView = findViewById(R.id.openkeychain_required_textview);
150 CardView fileLocationCardView = findViewById(R.id.file_location_cardview);
151 RadioButton importRadioButton = findViewById(R.id.import_radiobutton);
152 RadioButton exportRadioButton = findViewById(R.id.export_radiobutton);
153 LinearLayout fileNameLinearLayout = findViewById(R.id.file_name_linearlayout);
154 EditText fileNameEditText = findViewById(R.id.file_name_edittext);
155 TextView fileDoesNotExistTextView = findViewById(R.id.file_does_not_exist_textview);
156 TextView fileExistsWarningTextView = findViewById(R.id.file_exists_warning_textview);
157 TextView openKeychainImportInstructionsTextView = findViewById(R.id.openkeychain_import_instructions_textview);
158 Button importExportButton = findViewById(R.id.import_export_button);
159 TextView storagePermissionTextView = findViewById(R.id.import_export_storage_permission_textview);
161 // Create an array adapter for the spinner.
162 ArrayAdapter<CharSequence> encryptionArrayAdapter = ArrayAdapter.createFromResource(this, R.array.encryption_type, R.layout.spinner_item);
164 // Set the drop down view resource on the spinner.
165 encryptionArrayAdapter.setDropDownViewResource(R.layout.spinner_dropdown_items);
167 // Set the array adapter for the spinner.
168 encryptionSpinner.setAdapter(encryptionArrayAdapter);
170 // Initially hide the unneeded views.
171 passwordEncryptionTextInputLayout.setVisibility(View.GONE);
172 kitKatPasswordEncryptionTextView.setVisibility(View.GONE);
173 openKeychainRequiredTextView.setVisibility(View.GONE);
174 fileNameLinearLayout.setVisibility(View.GONE);
175 fileDoesNotExistTextView.setVisibility(View.GONE);
176 fileExistsWarningTextView.setVisibility(View.GONE);
177 openKeychainImportInstructionsTextView.setVisibility(View.GONE);
178 importExportButton.setVisibility(View.GONE);
180 // Instantiate the download location helper.
181 DownloadLocationHelper downloadLocationHelper = new DownloadLocationHelper();
183 // Get the default file path.
184 String defaultFilePath = downloadLocationHelper.getDownloadLocation(this) + "/" + getString(R.string.settings_pbs);
186 // Set the other default file paths.
187 String defaultPasswordEncryptionFilePath = defaultFilePath + ".aes";
188 String defaultPgpFilePath = defaultFilePath + ".pgp";
190 // Set the default file path.
191 fileNameEditText.setText(defaultFilePath);
193 // Hide the storage permission text view if the permission has already been granted.
194 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
195 storagePermissionTextView.setVisibility(View.GONE);
198 // Update the UI when the spinner changes.
199 encryptionSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
201 public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
204 // Hide the unneeded layout items.
205 passwordEncryptionTextInputLayout.setVisibility(View.GONE);
206 kitKatPasswordEncryptionTextView.setVisibility(View.GONE);
207 openKeychainRequiredTextView.setVisibility(View.GONE);
208 openKeychainImportInstructionsTextView.setVisibility(View.GONE);
210 // Show the file location card.
211 fileLocationCardView.setVisibility(View.VISIBLE);
213 // Show the file name linear layout if either import or export is checked.
214 if (importRadioButton.isChecked() || exportRadioButton.isChecked()) {
215 fileNameLinearLayout.setVisibility(View.VISIBLE);
218 // Reset the text of the import button, which may have been changed to `Decrypt`.
219 if (importRadioButton.isChecked()) {
220 importExportButton.setText(R.string.import_button);
223 // Reset the default file path.
224 fileNameEditText.setText(defaultFilePath);
227 case PASSWORD_ENCRYPTION:
229 // Show the KitKat password encryption message.
230 kitKatPasswordEncryptionTextView.setVisibility(View.VISIBLE);
232 // Hide the OpenPGP required text view and the file location card.
233 openKeychainRequiredTextView.setVisibility(View.GONE);
234 fileLocationCardView.setVisibility(View.GONE);
236 // Hide the OpenPGP layout items.
237 openKeychainRequiredTextView.setVisibility(View.GONE);
238 openKeychainImportInstructionsTextView.setVisibility(View.GONE);
240 // Show the password encryption layout items.
241 passwordEncryptionTextInputLayout.setVisibility(View.VISIBLE);
243 // Show the file location card.
244 fileLocationCardView.setVisibility(View.VISIBLE);
246 // Show the file name linear layout if either import or export is checked.
247 if (importRadioButton.isChecked() || exportRadioButton.isChecked()) {
248 fileNameLinearLayout.setVisibility(View.VISIBLE);
251 // Reset the text of the import button, which may have been changed to `Decrypt`.
252 if (importRadioButton.isChecked()) {
253 importExportButton.setText(R.string.import_button);
256 // Update the default file path.
257 fileNameEditText.setText(defaultPasswordEncryptionFilePath);
261 case OPENPGP_ENCRYPTION:
262 // Hide the password encryption layout items.
263 passwordEncryptionTextInputLayout.setVisibility(View.GONE);
264 kitKatPasswordEncryptionTextView.setVisibility(View.GONE);
266 // Updated items based on the installation status of OpenKeychain.
267 if (openKeychainInstalled) { // OpenKeychain is installed.
268 // Update the default file path.
269 fileNameEditText.setText(defaultPgpFilePath);
271 // Show the file location card.
272 fileLocationCardView.setVisibility(View.VISIBLE);
274 if (importRadioButton.isChecked()) {
275 // Show the file name linear layout and the OpenKeychain import instructions.
276 fileNameLinearLayout.setVisibility(View.VISIBLE);
277 openKeychainImportInstructionsTextView.setVisibility(View.VISIBLE);
279 // Set the text of the import button to be `Decrypt`.
280 importExportButton.setText(R.string.decrypt);
281 } else if (exportRadioButton.isChecked()) {
282 // Hide the file name linear layout and the OpenKeychain import instructions.
283 fileNameLinearLayout.setVisibility(View.GONE);
284 openKeychainImportInstructionsTextView.setVisibility(View.GONE);
286 } else { // OpenKeychain is not installed.
287 // Show the OpenPGP required layout item.
288 openKeychainRequiredTextView.setVisibility(View.VISIBLE);
290 // Hide the file location card.
291 fileLocationCardView.setVisibility(View.GONE);
298 public void onNothingSelected(AdapterView<?> parent) {
303 // Update the status of the import/export button when the password changes.
304 encryptionPasswordEditText.addTextChangedListener(new TextWatcher() {
306 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
311 public void onTextChanged(CharSequence s, int start, int before, int count) {
316 public void afterTextChanged(Editable s) {
317 // Get the current file name.
318 String fileNameString = fileNameEditText.getText().toString();
320 // Convert the file name string to a file.
321 File file = new File(fileNameString);
323 // Update the import/export button.
324 if (importRadioButton.isChecked()) { // The import radio button is checked.
325 // Enable the import button if the file and the password exists.
326 importExportButton.setEnabled(file.exists() && !encryptionPasswordEditText.getText().toString().isEmpty());
327 } else if (exportRadioButton.isChecked()) { // The export radio button is checked.
328 // Enable the export button if the file string and the password exists.
329 importExportButton.setEnabled(!fileNameString.isEmpty() && !encryptionPasswordEditText.getText().toString().isEmpty());
334 // Update the UI when the file name EditText changes.
335 fileNameEditText.addTextChangedListener(new TextWatcher() {
337 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
342 public void onTextChanged(CharSequence s, int start, int before, int count) {
347 public void afterTextChanged(Editable s) {
348 // Get the current file name.
349 String fileNameString = fileNameEditText.getText().toString();
351 // Convert the file name string to a file.
352 File file = new File(fileNameString);
354 // Adjust the UI according to the encryption spinner position.
355 switch (encryptionSpinner.getSelectedItemPosition()) {
357 // Determine if import or export is checked.
358 if (exportRadioButton.isChecked()) { // The export radio button is checked.
359 // Hide the file does not exist text view.
360 fileDoesNotExistTextView.setVisibility(View.GONE);
362 // Display a warning if the file already exists.
364 fileExistsWarningTextView.setVisibility(View.VISIBLE);
366 fileExistsWarningTextView.setVisibility(View.GONE);
369 // Enable the export button if the file name is populated.
370 importExportButton.setEnabled(!fileNameString.isEmpty());
371 } else if (importRadioButton.isChecked()) { // The import radio button is checked.
372 // Hide the file exists warning text view.
373 fileExistsWarningTextView.setVisibility(View.GONE);
375 // Check if the file exists.
376 if (file.exists()) { // The file exists.
377 // Hide the notification that the file does not exist.
378 fileDoesNotExistTextView.setVisibility(View.GONE);
380 // Enable the import button.
381 importExportButton.setEnabled(true);
382 } else { // The file does not exist.
383 // Show a notification that the file does not exist.
384 fileDoesNotExistTextView.setVisibility(View.VISIBLE);
386 // Disable the import button.
387 importExportButton.setEnabled(false);
389 } else { // Neither radio button is checked.
390 // Hide the file notification text views.
391 fileExistsWarningTextView.setVisibility(View.GONE);
392 fileDoesNotExistTextView.setVisibility(View.GONE);
396 case PASSWORD_ENCRYPTION:
397 // Determine if import or export is checked.
398 if (exportRadioButton.isChecked()) { // The export radio button is checked.
399 // Hide the notification that the file does not exist.
400 fileDoesNotExistTextView.setVisibility(View.GONE);
402 // Display a warning if the file already exists.
404 fileExistsWarningTextView.setVisibility(View.VISIBLE);
406 fileExistsWarningTextView.setVisibility(View.GONE);
409 // Enable the export button if the file name and the password are populated.
410 importExportButton.setEnabled(!fileNameString.isEmpty() && !encryptionPasswordEditText.getText().toString().isEmpty());
411 } else if (importRadioButton.isChecked()) { // The import radio button is checked.
412 // Hide the file exists warning text view.
413 fileExistsWarningTextView.setVisibility(View.GONE);
415 // Check if the file exists.
416 if (file.exists()) { // The file exists.
417 // Hide the notification that the file does not exist.
418 fileDoesNotExistTextView.setVisibility(View.GONE);
420 // Enable the import button if the password is populated.
421 importExportButton.setEnabled(!encryptionPasswordEditText.getText().toString().isEmpty());
422 } else { // The file does not exist.
423 // Show a notification that the file does not exist.
424 fileDoesNotExistTextView.setVisibility(View.VISIBLE);
426 // Disable the import button.
427 importExportButton.setEnabled(false);
429 } else { // Neither radio button is checked.
430 // Hide the file notification text views.
431 fileExistsWarningTextView.setVisibility(View.GONE);
432 fileDoesNotExistTextView.setVisibility(View.GONE);
436 case OPENPGP_ENCRYPTION:
437 // Hide the file exists warning text view.
438 fileExistsWarningTextView.setVisibility(View.GONE);
440 if (importRadioButton.isChecked()) { // The import radio button is checked.
441 if (file.exists()) { // The file exists.
442 // Hide the notification that the file does not exist.
443 fileDoesNotExistTextView.setVisibility(View.GONE);
445 // Enable the import button if OpenKeychain is installed.
446 importExportButton.setEnabled(openKeychainInstalled);
447 } else { // The file does not exist.
448 // Show the notification that the file does not exist.
449 fileDoesNotExistTextView.setVisibility(View.VISIBLE);
451 // Disable the import button.
452 importExportButton.setEnabled(false);
454 } else if (exportRadioButton.isChecked()){ // The export radio button is checked.
455 // Hide the notification that the file does not exist.
456 fileDoesNotExistTextView.setVisibility(View.GONE);
458 // Enable the export button.
459 importExportButton.setEnabled(true);
460 } else { // Neither radio button is checked.
461 // Hide the notification that the file does not exist.
462 fileDoesNotExistTextView.setVisibility(View.GONE);
470 public void onClickRadioButton(View view) {
471 // Get handles for the views.
472 Spinner encryptionSpinner = findViewById(R.id.encryption_spinner);
473 LinearLayout fileNameLinearLayout = findViewById(R.id.file_name_linearlayout);
474 EditText passwordEncryptionEditText = findViewById(R.id.password_encryption_edittext);
475 EditText fileNameEditText = findViewById(R.id.file_name_edittext);
476 TextView fileDoesNotExistTextView = findViewById(R.id.file_does_not_exist_textview);
477 TextView fileExistsWarningTextView = findViewById(R.id.file_exists_warning_textview);
478 TextView openKeychainImportInstructionTextView = findViewById(R.id.openkeychain_import_instructions_textview);
479 Button importExportButton = findViewById(R.id.import_export_button);
481 // Get the current file name.
482 String fileNameString = fileNameEditText.getText().toString();
484 // Convert the file name string to a file.
485 File file = new File(fileNameString);
487 // Check to see if import or export was selected.
488 switch (view.getId()) {
489 case R.id.import_radiobutton:
490 // Check to see if OpenPGP encryption is selected.
491 if (encryptionSpinner.getSelectedItemPosition() == OPENPGP_ENCRYPTION) { // OpenPGP encryption selected.
492 // Show the OpenKeychain import instructions.
493 openKeychainImportInstructionTextView.setVisibility(View.VISIBLE);
495 // Set the text on the import/export button to be `Decrypt`.
496 importExportButton.setText(R.string.decrypt);
497 } else { // OpenPGP encryption not selected.
498 // Hide the OpenKeychain import instructions.
499 openKeychainImportInstructionTextView.setVisibility(View.GONE);
501 // Set the text on the import/export button to be `Import`.
502 importExportButton.setText(R.string.import_button);
505 // Hide the file exists warning text view.
506 fileExistsWarningTextView.setVisibility(View.GONE);
508 // Display the file name views.
509 fileNameLinearLayout.setVisibility(View.VISIBLE);
510 importExportButton.setVisibility(View.VISIBLE);
512 // Check to see if the file exists.
513 if (file.exists()) { // The file exists.
514 // Hide the notification that the file does not exist.
515 fileDoesNotExistTextView.setVisibility(View.GONE);
517 // Check to see if password encryption is selected.
518 if (encryptionSpinner.getSelectedItemPosition() == PASSWORD_ENCRYPTION) { // Password encryption is selected.
519 // Enable the import button if the encryption password is populated.
520 importExportButton.setEnabled(!passwordEncryptionEditText.getText().toString().isEmpty());
521 } else { // Password encryption is not selected.
522 // Enable the import/decrypt button.
523 importExportButton.setEnabled(true);
525 } else { // The file does not exist.
526 // Show the notification that the file does not exist.
527 fileDoesNotExistTextView.setVisibility(View.VISIBLE);
529 // Disable the import/decrypt button.
530 importExportButton.setEnabled(false);
534 case R.id.export_radiobutton:
535 // Hide the OpenKeychain import instructions.
536 openKeychainImportInstructionTextView.setVisibility(View.GONE);
538 // Set the text on the import/export button to be `Export`.
539 importExportButton.setText(R.string.export);
541 // Show the import/export button.
542 importExportButton.setVisibility(View.VISIBLE);
544 // Check to see if OpenPGP encryption is selected.
545 if (encryptionSpinner.getSelectedItemPosition() == OPENPGP_ENCRYPTION) { // OpenPGP encryption is selected.
546 // Hide the file name views.
547 fileNameLinearLayout.setVisibility(View.GONE);
548 fileDoesNotExistTextView.setVisibility(View.GONE);
549 fileExistsWarningTextView.setVisibility(View.GONE);
551 // Enable the export button.
552 importExportButton.setEnabled(true);
553 } else { // OpenPGP encryption is not selected.
554 // Show the file name view.
555 fileNameLinearLayout.setVisibility(View.VISIBLE);
557 // Hide the notification that the file name does not exist.
558 fileDoesNotExistTextView.setVisibility(View.GONE);
560 // Display a warning if the file already exists.
562 fileExistsWarningTextView.setVisibility(View.VISIBLE);
564 fileExistsWarningTextView.setVisibility(View.GONE);
567 // Check the encryption type.
568 if (encryptionSpinner.getSelectedItemPosition() == NO_ENCRYPTION) { // No encryption is selected.
569 // Enable the export button if the file name is populated.
570 importExportButton.setEnabled(!fileNameString.isEmpty());
571 } else { // Password encryption is selected.
572 // Enable the export button if the file name and the password are populated.
573 importExportButton.setEnabled(!fileNameString.isEmpty() && !passwordEncryptionEditText.getText().toString().isEmpty());
580 public void browse(View view) {
581 // Get a handle for the views.
582 Spinner encryptionSpinner = findViewById(R.id.encryption_spinner);
583 RadioButton importRadioButton = findViewById(R.id.import_radiobutton);
585 // Check to see if import or export is selected.
586 if (importRadioButton.isChecked()) { // Import is selected.
587 // Create the file picker intent.
588 Intent importBrowseIntent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
590 // Set the intent MIME type to include all files so that everything is visible.
591 importBrowseIntent.setType("*/*");
593 // Set the initial directory if the minimum API >= 26.
594 if (Build.VERSION.SDK_INT >= 26) {
595 importBrowseIntent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, Environment.getExternalStorageDirectory());
598 // Request a file that can be opened.
599 importBrowseIntent.addCategory(Intent.CATEGORY_OPENABLE);
601 // Launch the file picker.
602 startActivityForResult(importBrowseIntent, BROWSE_RESULT_CODE);
603 } else { // Export is selected
604 // Create the file picker intent.
605 Intent exportBrowseIntent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
607 // Set the intent MIME type to include all files so that everything is visible.
608 exportBrowseIntent.setType("*/*");
610 // Set the initial export file name according to the encryption type.
611 if (encryptionSpinner.getSelectedItemPosition() == NO_ENCRYPTION) { // No encryption is selected.
612 exportBrowseIntent.putExtra(Intent.EXTRA_TITLE, getString(R.string.settings_pbs));
613 } else { // Password encryption is selected.
614 exportBrowseIntent.putExtra(Intent.EXTRA_TITLE, getString(R.string.settings_pbs) + ".aes");
617 // Set the initial directory if the minimum API >= 26.
618 if (Build.VERSION.SDK_INT >= 26) {
619 exportBrowseIntent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, Environment.getExternalStorageDirectory());
622 // Request a file that can be opened.
623 exportBrowseIntent.addCategory(Intent.CATEGORY_OPENABLE);
625 // Launch the file picker.
626 startActivityForResult(exportBrowseIntent, BROWSE_RESULT_CODE);
630 public void importExport(View view) {
631 // Get a handle for the views.
632 Spinner encryptionSpinner = findViewById(R.id.encryption_spinner);
633 RadioButton importRadioButton = findViewById(R.id.import_radiobutton);
634 RadioButton exportRadioButton = findViewById(R.id.export_radiobutton);
636 // Check to see if the storage permission is needed.
637 if ((encryptionSpinner.getSelectedItemPosition() == OPENPGP_ENCRYPTION) && exportRadioButton.isChecked()) { // Permission not needed to export via OpenKeychain.
638 // Export the settings.
640 } else if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // The storage permission has been granted.
641 // Check to see if import or export is selected.
642 if (importRadioButton.isChecked()) { // Import is selected.
643 // Import the settings.
645 } else { // Export is selected.
646 // Export the settings.
649 } else { // The storage permission has not been granted.
650 // Get a handle for the file name EditText.
651 EditText fileNameEditText = findViewById(R.id.file_name_edittext);
653 // Get the file name string.
654 String fileNameString = fileNameEditText.getText().toString();
656 // Get the external private directory `File`.
657 File externalPrivateDirectoryFile = getExternalFilesDir(null);
659 // Remove the incorrect lint error below that the file might be null.
660 assert externalPrivateDirectoryFile != null;
662 // Get the external private directory string.
663 String externalPrivateDirectory = externalPrivateDirectoryFile.toString();
665 // Check to see if the file path is in the external private directory.
666 if (fileNameString.startsWith(externalPrivateDirectory)) { // The file path is in the external private directory.
667 // Check to see if import or export is selected.
668 if (importRadioButton.isChecked()) { // Import is selected.
669 // Import the settings.
671 } else { // Export is selected.
672 // Export the settings.
675 } else { // The file path is in a public directory.
676 // Check if the user has previously denied the storage permission.
677 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
678 // Instantiate the storage permission alert dialog.
679 DialogFragment storagePermissionDialogFragment = StoragePermissionDialog.displayDialog(0);
681 // Show the storage permission alert dialog. The permission will be requested when the dialog is closed.
682 storagePermissionDialogFragment.show(getSupportFragmentManager(), getString(R.string.storage_permission));
683 } else { // Show the permission request directly.
684 // Request the storage permission. The export will be run when it finishes.
685 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
692 public void onCloseStoragePermissionDialog(int type) {
693 // Request the write external storage permission. The import/export will be run when it finishes.
694 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
698 public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
699 // Get a handle for the import radiobutton.
700 RadioButton importRadioButton = findViewById(R.id.import_radiobutton);
702 // Check to see if the storage permission was granted. If the dialog was canceled the grant results will be empty.
703 if ((grantResults.length > 0) && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) { // The storage permission was granted.
704 // Run the import or export methods according to which radio button is selected.
705 if (importRadioButton.isChecked()) { // Import is selected.
706 // Import the settings.
708 } else { // Export is selected.
709 // Export the settings.
712 } else { // The storage permission was not granted.
713 // Display an error snackbar.
714 Snackbar.make(importRadioButton, getString(R.string.cannot_use_location), Snackbar.LENGTH_LONG).show();
719 public void onActivityResult(int requestCode, int resultCode, Intent intent) {
720 // Run the default commands.
721 super.onActivityResult(requestCode, resultCode, intent);
723 switch (requestCode) {
724 case (BROWSE_RESULT_CODE):
725 // Don't do anything if the user pressed back from the file picker.
726 if (resultCode == Activity.RESULT_OK) {
727 // Get a handle for the views.
728 EditText fileNameEditText = findViewById(R.id.file_name_edittext);
729 TextView fileExistsWarningTextView = findViewById(R.id.file_exists_warning_textview);
731 // Instantiate the file name helper.
732 FileNameHelper fileNameHelper = new FileNameHelper();
734 // Get the file path URI from the intent.
735 Uri filePathUri = intent.getData();
737 // Use the file path from the intent if it exists.
738 if (filePathUri != null) {
739 // Convert the file name URI to a file name path.
740 String fileNamePath = fileNameHelper.convertUriToFileNamePath(filePathUri);
742 // Set the file name path as the text of the file name edit text.
743 fileNameEditText.setText(fileNamePath);
745 // Hide the file exists warning text view, because the file picker will have just created a file if export was selected.
746 fileExistsWarningTextView.setVisibility(View.GONE);
751 case OPENPGP_EXPORT_RESULT_CODE:
752 // Get the temporary unencrypted export file.
753 File temporaryUnencryptedExportFile = new File(getApplicationContext().getCacheDir() + "/" + getString(R.string.settings_pbs));
755 // Delete the temporary unencrypted export file if it exists.
756 if (temporaryUnencryptedExportFile.exists()) {
757 //noinspection ResultOfMethodCallIgnored
758 temporaryUnencryptedExportFile.delete();
764 private void exportSettings() {
765 // Get a handle for the views.
766 Spinner encryptionSpinner = findViewById(R.id.encryption_spinner);
767 EditText fileNameEditText = findViewById(R.id.file_name_edittext);
769 // Instantiate the import export database helper.
770 ImportExportDatabaseHelper importExportDatabaseHelper = new ImportExportDatabaseHelper();
772 // Get the export file string.
773 String exportFileString = fileNameEditText.getText().toString();
775 // Get the export and temporary unencrypted export files.
776 File exportFile = new File(exportFileString);
777 File temporaryUnencryptedExportFile = new File(getApplicationContext().getCacheDir() + "/" + getString(R.string.settings_pbs));
779 // Create an export status string.
782 // Export according to the encryption type.
783 switch (encryptionSpinner.getSelectedItemPosition()) {
785 // Export the unencrypted file.
786 exportStatus = importExportDatabaseHelper.exportUnencrypted(exportFile, this);
788 // Show a disposition snackbar.
789 if (exportStatus.equals(ImportExportDatabaseHelper.EXPORT_SUCCESSFUL)) {
790 Snackbar.make(fileNameEditText, getString(R.string.export_successful), Snackbar.LENGTH_SHORT).show();
792 Snackbar.make(fileNameEditText, getString(R.string.export_failed) + " " + exportStatus, Snackbar.LENGTH_INDEFINITE).show();
796 case PASSWORD_ENCRYPTION:
797 // Create an unencrypted export in a private directory.
798 exportStatus = importExportDatabaseHelper.exportUnencrypted(temporaryUnencryptedExportFile, this);
801 // Create an unencrypted export file input stream.
802 FileInputStream unencryptedExportFileInputStream = new FileInputStream(temporaryUnencryptedExportFile);
804 // Delete the encrypted export file if it exists.
805 if (exportFile.exists()) {
806 //noinspection ResultOfMethodCallIgnored
810 // Create an encrypted export file output stream.
811 FileOutputStream encryptedExportFileOutputStream = new FileOutputStream(exportFile);
813 // Get a handle for the encryption password EditText.
814 EditText encryptionPasswordEditText = findViewById(R.id.password_encryption_edittext);
816 // Get the encryption password.
817 String encryptionPasswordString = encryptionPasswordEditText.getText().toString();
819 // Initialize a secure random number generator.
820 SecureRandom secureRandom = new SecureRandom();
822 // Get a 256 bit (32 byte) random salt.
823 byte[] saltByteArray = new byte[32];
824 secureRandom.nextBytes(saltByteArray);
826 // Convert the encryption password to a byte array.
827 byte[] encryptionPasswordByteArray = encryptionPasswordString.getBytes(StandardCharsets.UTF_8);
829 // Append the salt to the encryption password byte array. This protects against rainbow table attacks.
830 byte[] encryptionPasswordWithSaltByteArray = new byte[encryptionPasswordByteArray.length + saltByteArray.length];
831 System.arraycopy(encryptionPasswordByteArray, 0, encryptionPasswordWithSaltByteArray, 0, encryptionPasswordByteArray.length);
832 System.arraycopy(saltByteArray, 0, encryptionPasswordWithSaltByteArray, encryptionPasswordByteArray.length, saltByteArray.length);
834 // Get a SHA-512 message digest.
835 MessageDigest messageDigest = MessageDigest.getInstance("SHA-512");
837 // Hash the salted encryption password. Otherwise, any characters after the 32nd character in the password are ignored.
838 byte[] hashedEncryptionPasswordWithSaltByteArray = messageDigest.digest(encryptionPasswordWithSaltByteArray);
840 // Truncate the encryption password byte array to 256 bits (32 bytes).
841 byte[] truncatedHashedEncryptionPasswordWithSaltByteArray = Arrays.copyOf(hashedEncryptionPasswordWithSaltByteArray, 32);
843 // Create an AES secret key from the encryption password byte array.
844 SecretKeySpec secretKey = new SecretKeySpec(truncatedHashedEncryptionPasswordWithSaltByteArray, "AES");
846 // Generate a random 12 byte initialization vector. According to NIST, a 12 byte initialization vector is more secure than a 16 byte one.
847 byte[] initializationVector = new byte[12];
848 secureRandom.nextBytes(initializationVector);
850 // 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.
851 Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
853 // Set the GCM tag length to be 128 bits (the maximum) and apply the initialization vector.
854 GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, initializationVector);
856 // Initialize the cipher.
857 cipher.init(Cipher.ENCRYPT_MODE, secretKey, gcmParameterSpec);
859 // Add the salt and the initialization vector to the export file.
860 encryptedExportFileOutputStream.write(saltByteArray);
861 encryptedExportFileOutputStream.write(initializationVector);
863 // Create a cipher output stream.
864 CipherOutputStream cipherOutputStream = new CipherOutputStream(encryptedExportFileOutputStream, cipher);
866 // 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.
867 int numberOfBytesRead;
868 byte[] encryptedBytes = new byte[16];
870 // 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.
871 while ((numberOfBytesRead = unencryptedExportFileInputStream.read(encryptedBytes)) != -1) {
872 // Write the data to the cipher output stream.
873 cipherOutputStream.write(encryptedBytes, 0, numberOfBytesRead);
876 // Close the streams.
877 cipherOutputStream.flush();
878 cipherOutputStream.close();
879 encryptedExportFileOutputStream.close();
880 unencryptedExportFileInputStream.close();
882 // Wipe the encryption data from memory.
883 //noinspection UnusedAssignment
884 encryptionPasswordString = "";
885 Arrays.fill(saltByteArray, (byte) 0);
886 Arrays.fill(encryptionPasswordByteArray, (byte) 0);
887 Arrays.fill(encryptionPasswordWithSaltByteArray, (byte) 0);
888 Arrays.fill(hashedEncryptionPasswordWithSaltByteArray, (byte) 0);
889 Arrays.fill(truncatedHashedEncryptionPasswordWithSaltByteArray, (byte) 0);
890 Arrays.fill(initializationVector, (byte) 0);
891 Arrays.fill(encryptedBytes, (byte) 0);
893 // Delete the temporary unencrypted export file.
894 //noinspection ResultOfMethodCallIgnored
895 temporaryUnencryptedExportFile.delete();
896 } catch (Exception exception) {
897 exportStatus = exception.toString();
900 // Show a disposition snackbar.
901 if (exportStatus.equals(ImportExportDatabaseHelper.EXPORT_SUCCESSFUL)) {
902 Snackbar.make(fileNameEditText, getString(R.string.export_successful), Snackbar.LENGTH_SHORT).show();
904 Snackbar.make(fileNameEditText, getString(R.string.export_failed) + " " + exportStatus, Snackbar.LENGTH_INDEFINITE).show();
908 case OPENPGP_ENCRYPTION:
909 // Create an unencrypted export in the private location.
910 importExportDatabaseHelper.exportUnencrypted(temporaryUnencryptedExportFile, this);
912 // Create an encryption intent for OpenKeychain.
913 Intent openKeychainEncryptIntent = new Intent("org.sufficientlysecure.keychain.action.ENCRYPT_DATA");
915 // Include the temporary unencrypted export file URI.
916 openKeychainEncryptIntent.setData(FileProvider.getUriForFile(this, getString(R.string.file_provider), temporaryUnencryptedExportFile));
918 // Allow OpenKeychain to read the file URI.
919 openKeychainEncryptIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
921 // Send the intent to the OpenKeychain package.
922 openKeychainEncryptIntent.setPackage("org.sufficientlysecure.keychain");
925 startActivityForResult(openKeychainEncryptIntent, OPENPGP_EXPORT_RESULT_CODE);
929 // Add the file to the list of recent files. This doesn't currently work, but maybe it will someday.
930 MediaScannerConnection.scanFile(this, new String[] {exportFileString}, new String[] {"application/x-sqlite3"}, null);
933 private void importSettings() {
934 // Get a handle for the views.
935 Spinner encryptionSpinner = findViewById(R.id.encryption_spinner);
936 EditText fileNameEditText = findViewById(R.id.file_name_edittext);
938 // Instantiate the import export database helper.
939 ImportExportDatabaseHelper importExportDatabaseHelper = new ImportExportDatabaseHelper();
941 // Get the import file.
942 File importFile = new File(fileNameEditText.getText().toString());
944 // Initialize the import status string
945 String importStatus = "";
947 // Import according to the encryption type.
948 switch (encryptionSpinner.getSelectedItemPosition()) {
950 // Import the unencrypted file.
951 importStatus = importExportDatabaseHelper.importUnencrypted(importFile, this);
954 case PASSWORD_ENCRYPTION:
955 // Use a private temporary import location.
956 File temporaryUnencryptedImportFile = new File(getApplicationContext().getCacheDir() + "/" + getString(R.string.settings_pbs));
959 // Create an encrypted import file input stream.
960 FileInputStream encryptedImportFileInputStream = new FileInputStream(importFile);
962 // Delete the temporary import file if it exists.
963 if (temporaryUnencryptedImportFile.exists()) {
964 //noinspection ResultOfMethodCallIgnored
965 temporaryUnencryptedImportFile.delete();
968 // Create an unencrypted import file output stream.
969 FileOutputStream unencryptedImportFileOutputStream = new FileOutputStream(temporaryUnencryptedImportFile);
971 // Get a handle for the encryption password EditText.
972 EditText encryptionPasswordEditText = findViewById(R.id.password_encryption_edittext);
974 // Get the encryption password.
975 String encryptionPasswordString = encryptionPasswordEditText.getText().toString();
977 // Get the salt from the beginning of the import file.
978 byte[] saltByteArray = new byte[32];
979 //noinspection ResultOfMethodCallIgnored
980 encryptedImportFileInputStream.read(saltByteArray);
982 // Get the initialization vector from the import file.
983 byte[] initializationVector = new byte[12];
984 //noinspection ResultOfMethodCallIgnored
985 encryptedImportFileInputStream.read(initializationVector);
987 // Convert the encryption password to a byte array.
988 byte[] encryptionPasswordByteArray = encryptionPasswordString.getBytes(StandardCharsets.UTF_8);
990 // Append the salt to the encryption password byte array. This protects against rainbow table attacks.
991 byte[] encryptionPasswordWithSaltByteArray = new byte[encryptionPasswordByteArray.length + saltByteArray.length];
992 System.arraycopy(encryptionPasswordByteArray, 0, encryptionPasswordWithSaltByteArray, 0, encryptionPasswordByteArray.length);
993 System.arraycopy(saltByteArray, 0, encryptionPasswordWithSaltByteArray, encryptionPasswordByteArray.length, saltByteArray.length);
995 // Get a SHA-512 message digest.
996 MessageDigest messageDigest = MessageDigest.getInstance("SHA-512");
998 // Hash the salted encryption password. Otherwise, any characters after the 32nd character in the password are ignored.
999 byte[] hashedEncryptionPasswordWithSaltByteArray = messageDigest.digest(encryptionPasswordWithSaltByteArray);
1001 // Truncate the encryption password byte array to 256 bits (32 bytes).
1002 byte[] truncatedHashedEncryptionPasswordWithSaltByteArray = Arrays.copyOf(hashedEncryptionPasswordWithSaltByteArray, 32);
1004 // Create an AES secret key from the encryption password byte array.
1005 SecretKeySpec secretKey = new SecretKeySpec(truncatedHashedEncryptionPasswordWithSaltByteArray, "AES");
1007 // 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.
1008 Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
1010 // Set the GCM tag length to be 128 bits (the maximum) and apply the initialization vector.
1011 GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, initializationVector);
1013 // Initialize the cipher.
1014 cipher.init(Cipher.DECRYPT_MODE, secretKey, gcmParameterSpec);
1016 // Create a cipher input stream.
1017 CipherInputStream cipherInputStream = new CipherInputStream(encryptedImportFileInputStream, cipher);
1019 // 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.
1020 int numberOfBytesRead;
1021 byte[] decryptedBytes = new byte[16];
1023 // 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.
1024 while ((numberOfBytesRead = cipherInputStream.read(decryptedBytes)) != -1) {
1025 // Write the data to the unencrypted import file output stream.
1026 unencryptedImportFileOutputStream.write(decryptedBytes, 0, numberOfBytesRead);
1029 // Close the streams.
1030 unencryptedImportFileOutputStream.flush();
1031 unencryptedImportFileOutputStream.close();
1032 cipherInputStream.close();
1033 encryptedImportFileInputStream.close();
1035 // Wipe the encryption data from memory.
1036 //noinspection UnusedAssignment
1037 encryptionPasswordString = "";
1038 Arrays.fill(saltByteArray, (byte) 0);
1039 Arrays.fill(initializationVector, (byte) 0);
1040 Arrays.fill(encryptionPasswordByteArray, (byte) 0);
1041 Arrays.fill(encryptionPasswordWithSaltByteArray, (byte) 0);
1042 Arrays.fill(hashedEncryptionPasswordWithSaltByteArray, (byte) 0);
1043 Arrays.fill(truncatedHashedEncryptionPasswordWithSaltByteArray, (byte) 0);
1044 Arrays.fill(decryptedBytes, (byte) 0);
1046 // Import the unencrypted database from the private location.
1047 importStatus = importExportDatabaseHelper.importUnencrypted(temporaryUnencryptedImportFile, this);
1049 // Delete the temporary unencrypted import file.
1050 //noinspection ResultOfMethodCallIgnored
1051 temporaryUnencryptedImportFile.delete();
1052 } catch (Exception exception) {
1053 importStatus = exception.toString();
1057 case OPENPGP_ENCRYPTION:
1059 // Create an decryption intent for OpenKeychain.
1060 Intent openKeychainDecryptIntent = new Intent("org.sufficientlysecure.keychain.action.DECRYPT_DATA");
1062 // Include the URI to be decrypted.
1063 openKeychainDecryptIntent.setData(FileProvider.getUriForFile(this, getString(R.string.file_provider), importFile));
1065 // Allow OpenKeychain to read the file URI.
1066 openKeychainDecryptIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
1068 // Send the intent to the OpenKeychain package.
1069 openKeychainDecryptIntent.setPackage("org.sufficientlysecure.keychain");
1072 startActivity(openKeychainDecryptIntent);
1073 } catch (IllegalArgumentException exception) { // The file import location is not valid.
1074 // Display a snack bar with the import error.
1075 Snackbar.make(fileNameEditText, getString(R.string.import_failed) + " " + exception.toString(), Snackbar.LENGTH_INDEFINITE).show();
1080 // Respond to the import disposition.
1081 if (importStatus.equals(ImportExportDatabaseHelper.IMPORT_SUCCESSFUL)) { // The import was successful.
1082 // Create an intent to restart Privacy Browser.
1083 Intent restartIntent = getParentActivityIntent();
1085 // Assert that the intent is not null to remove the lint error below.
1086 assert restartIntent != null;
1088 // `Intent.FLAG_ACTIVITY_CLEAR_TASK` removes all activities from the stack. It requires `Intent.FLAG_ACTIVITY_NEW_TASK`.
1089 restartIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
1091 // Create a restart handler.
1092 Handler restartHandler = new Handler();
1094 // Create a restart runnable.
1095 Runnable restartRunnable = () -> {
1096 // Restart Privacy Browser.
1097 startActivity(restartIntent);
1099 // Kill this instance of Privacy Browser. Otherwise, the app exhibits sporadic behavior after the restart.
1103 // Restart Privacy Browser after 150 milliseconds to allow enough time for the preferences to be saved.
1104 restartHandler.postDelayed(restartRunnable, 150);
1106 } else if (!(encryptionSpinner.getSelectedItemPosition() == OPENPGP_ENCRYPTION)){ // The import was not successful.
1107 // Display a snack bar with the import error.
1108 Snackbar.make(fileNameEditText, getString(R.string.import_failed) + " " + importStatus, Snackbar.LENGTH_INDEFINITE).show();