2 * Copyright © 2018-2019 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.ImportExportDatabaseHelper;
66 import java.io.FileInputStream;
67 import java.io.FileOutputStream;
68 import java.nio.charset.StandardCharsets;
69 import java.security.MessageDigest;
70 import java.security.SecureRandom;
71 import java.util.Arrays;
73 import javax.crypto.Cipher;
74 import javax.crypto.CipherInputStream;
75 import javax.crypto.CipherOutputStream;
76 import javax.crypto.spec.GCMParameterSpec;
77 import javax.crypto.spec.SecretKeySpec;
79 public class ImportExportActivity extends AppCompatActivity implements StoragePermissionDialog.StoragePermissionDialogListener {
80 // Create the encryption constants.
81 private final int NO_ENCRYPTION = 0;
82 private final int PASSWORD_ENCRYPTION = 1;
83 private final int OPENPGP_ENCRYPTION = 2;
85 // Create the activity result constants.
86 private final int BROWSE_RESULT_CODE = 0;
87 private final int OPENPGP_EXPORT_RESULT_CODE = 1;
89 // `openKeychainInstalled` is accessed from an inner class.
90 private boolean openKeychainInstalled;
93 public void onCreate(Bundle savedInstanceState) {
94 // Get a handle for the shared preferences.
95 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
97 // Get the theme and screenshot preferences.
98 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
99 boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
101 // Disable screenshots if not allowed.
102 if (!allowScreenshots) {
103 getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
106 // Set the activity theme.
108 setTheme(R.style.PrivacyBrowserDark_SecondaryActivity);
110 setTheme(R.style.PrivacyBrowserLight_SecondaryActivity);
113 // Run the default commands.
114 super.onCreate(savedInstanceState);
116 // Set the content view.
117 setContentView(R.layout.import_export_coordinatorlayout);
119 // Use the `SupportActionBar` from `android.support.v7.app.ActionBar` until the minimum API is >= 21.
120 Toolbar toolbar = findViewById(R.id.import_export_toolbar);
121 setSupportActionBar(toolbar);
123 // Get a handle for the action bar.
124 ActionBar actionBar = getSupportActionBar();
126 // Remove the incorrect lint warning that the action bar might be null.
127 assert actionBar != null;
129 // Display the home arrow on the support action bar.
130 actionBar.setDisplayHomeAsUpEnabled(true);
132 // Find out if we are running KitKat
133 boolean runningKitKat = (Build.VERSION.SDK_INT == 19);
135 // Find out if OpenKeychain is installed.
137 openKeychainInstalled = !getPackageManager().getPackageInfo("org.sufficientlysecure.keychain", 0).versionName.isEmpty();
138 } catch (PackageManager.NameNotFoundException exception) {
139 openKeychainInstalled = false;
142 // Get handles for the views that need to be modified.
143 Spinner encryptionSpinner = findViewById(R.id.encryption_spinner);
144 TextInputLayout passwordEncryptionTextInputLayout = findViewById(R.id.password_encryption_textinputlayout);
145 EditText encryptionPasswordEditText = findViewById(R.id.password_encryption_edittext);
146 TextView kitKatPasswordEncryptionTextView = findViewById(R.id.kitkat_password_encryption_textview);
147 TextView openKeychainRequiredTextView = findViewById(R.id.openkeychain_required_textview);
148 CardView fileLocationCardView = findViewById(R.id.file_location_cardview);
149 RadioButton importRadioButton = findViewById(R.id.import_radiobutton);
150 RadioButton exportRadioButton = findViewById(R.id.export_radiobutton);
151 LinearLayout fileNameLinearLayout = findViewById(R.id.file_name_linearlayout);
152 EditText fileNameEditText = findViewById(R.id.file_name_edittext);
153 TextView openKeychainImportInstructionsTextView = findViewById(R.id.openkeychain_import_instructions_textview);
154 Button importExportButton = findViewById(R.id.import_export_button);
155 TextView storagePermissionTextView = findViewById(R.id.import_export_storage_permission_textview);
157 // Create an array adapter for the spinner.
158 ArrayAdapter<CharSequence> encryptionArrayAdapter = ArrayAdapter.createFromResource(this, R.array.encryption_type, R.layout.spinner_item);
160 // Set the drop down view resource on the spinner.
161 encryptionArrayAdapter.setDropDownViewResource(R.layout.spinner_dropdown_items);
163 // Set the array adapter for the spinner.
164 encryptionSpinner.setAdapter(encryptionArrayAdapter);
166 // Initially hide the unneeded views.
167 passwordEncryptionTextInputLayout.setVisibility(View.GONE);
168 kitKatPasswordEncryptionTextView.setVisibility(View.GONE);
169 openKeychainRequiredTextView.setVisibility(View.GONE);
170 fileNameLinearLayout.setVisibility(View.GONE);
171 openKeychainImportInstructionsTextView.setVisibility(View.GONE);
172 importExportButton.setVisibility(View.GONE);
174 // Create strings for the default file paths.
175 String defaultFilePath;
176 String defaultPasswordEncryptionFilePath;
178 // Set the default file paths according to the storage permission status.
179 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // The storage permission has been granted.
180 // Set the default file paths to use the external public directory.
181 defaultFilePath = Environment.getExternalStorageDirectory() + "/" + getString(R.string.settings_pbs);
182 defaultPasswordEncryptionFilePath = defaultFilePath + ".aes";
183 } else { // The storage permission has not been granted.
184 // Set the default file paths to use the external private directory.
185 defaultFilePath = getApplicationContext().getExternalFilesDir(null) + "/" + getString(R.string.settings_pbs);
186 defaultPasswordEncryptionFilePath = defaultFilePath + ".aes";
189 // Set the default file path.
190 fileNameEditText.setText(defaultFilePath);
192 // Display the encryption information when the spinner changes.
193 encryptionSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
195 public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
198 // Hide the unneeded layout items.
199 passwordEncryptionTextInputLayout.setVisibility(View.GONE);
200 kitKatPasswordEncryptionTextView.setVisibility(View.GONE);
201 openKeychainRequiredTextView.setVisibility(View.GONE);
202 openKeychainImportInstructionsTextView.setVisibility(View.GONE);
204 // Show the file location card.
205 fileLocationCardView.setVisibility(View.VISIBLE);
207 // Show the file name linear layout if either import or export is checked.
208 if (importRadioButton.isChecked() || exportRadioButton.isChecked()) {
209 fileNameLinearLayout.setVisibility(View.VISIBLE);
212 // Reset the text of the import button, which may have been changed to `Decrypt`.
213 if (importRadioButton.isChecked()) {
214 importExportButton.setText(R.string.import_button);
217 // Reset the default file path.
218 fileNameEditText.setText(defaultFilePath);
220 // Enable the import/export button if a file name exists.
221 importExportButton.setEnabled(!fileNameEditText.getText().toString().isEmpty());
224 case PASSWORD_ENCRYPTION:
226 // Show the KitKat password encryption message.
227 kitKatPasswordEncryptionTextView.setVisibility(View.VISIBLE);
229 // Hide the OpenPGP required text view and the file location card.
230 openKeychainRequiredTextView.setVisibility(View.GONE);
231 fileLocationCardView.setVisibility(View.GONE);
233 // Hide the OpenPGP layout items.
234 openKeychainRequiredTextView.setVisibility(View.GONE);
235 openKeychainImportInstructionsTextView.setVisibility(View.GONE);
237 // Show the password encryption layout items.
238 passwordEncryptionTextInputLayout.setVisibility(View.VISIBLE);
240 // Show the file location card.
241 fileLocationCardView.setVisibility(View.VISIBLE);
243 // Show the file name linear layout if either import or export is checked.
244 if (importRadioButton.isChecked() || exportRadioButton.isChecked()) {
245 fileNameLinearLayout.setVisibility(View.VISIBLE);
248 // Reset the text of the import button, which may have been changed to `Decrypt`.
249 if (importRadioButton.isChecked()) {
250 importExportButton.setText(R.string.import_button);
253 // Update the default file path.
254 fileNameEditText.setText(defaultPasswordEncryptionFilePath);
256 // Enable the import/export button if a password exists.
257 importExportButton.setEnabled(!encryptionPasswordEditText.getText().toString().isEmpty());
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 // Remove the default file path.
269 fileNameEditText.setText("");
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);
282 // Disable the import/export button. The user needs to select a file to import first.
283 importExportButton.setEnabled(false);
284 } else if (exportRadioButton.isChecked()) {
285 // Hide the file name linear layout and the OpenKeychain import instructions.
286 fileNameLinearLayout.setVisibility(View.GONE);
287 openKeychainImportInstructionsTextView.setVisibility(View.GONE);
289 // Enable the import/export button.
290 importExportButton.setEnabled(true);
292 } else { // OpenKeychain is not installed.
293 // Show the OpenPGP required layout item.
294 openKeychainRequiredTextView.setVisibility(View.VISIBLE);
296 // Hide the file location card.
297 fileLocationCardView.setVisibility(View.GONE);
304 public void onNothingSelected(AdapterView<?> parent) {
309 // Update the status of the import/export button when the password changes.
310 encryptionPasswordEditText.addTextChangedListener(new TextWatcher() {
312 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
317 public void onTextChanged(CharSequence s, int start, int before, int count) {
322 public void afterTextChanged(Editable s) {
323 // Enable the import/export button if a file name and password exists.
324 importExportButton.setEnabled(!fileNameEditText.getText().toString().isEmpty() && !encryptionPasswordEditText.getText().toString().isEmpty());
328 // Update the status of the import/export button when the file name EditText changes.
329 fileNameEditText.addTextChangedListener(new TextWatcher() {
331 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
336 public void onTextChanged(CharSequence s, int start, int before, int count) {
341 public void afterTextChanged(Editable s) {
342 // Adjust the export button according to the encryption spinner position.
343 switch (encryptionSpinner.getSelectedItemPosition()) {
345 // Enable the import/export button if a file name exists.
346 importExportButton.setEnabled(!fileNameEditText.getText().toString().isEmpty());
349 case PASSWORD_ENCRYPTION:
350 // Enable the import/export button if a file name and password exists.
351 importExportButton.setEnabled(!fileNameEditText.getText().toString().isEmpty() && !encryptionPasswordEditText.getText().toString().isEmpty());
354 case OPENPGP_ENCRYPTION:
355 // Enable the import/export button if OpenKeychain is installed and a file name exists.
356 importExportButton.setEnabled(openKeychainInstalled && !fileNameEditText.getText().toString().isEmpty());
362 // Hide the storage permissions text view on API < 23 as permissions on older devices are automatically granted.
363 if (Build.VERSION.SDK_INT < 23) {
364 storagePermissionTextView.setVisibility(View.GONE);
368 public void onClickRadioButton(View view) {
369 // Get handles for the views.
370 Spinner encryptionSpinner = findViewById(R.id.encryption_spinner);
371 LinearLayout fileNameLinearLayout = findViewById(R.id.file_name_linearlayout);
372 EditText fileNameEditText = findViewById(R.id.file_name_edittext);
373 TextView openKeychainImportInstructionTextView = findViewById(R.id.openkeychain_import_instructions_textview);
374 Button importExportButton = findViewById(R.id.import_export_button);
376 // Check to see if import or export was selected.
377 switch (view.getId()) {
378 case R.id.import_radiobutton:
379 // Check to see if OpenPGP encryption is selected.
380 if (encryptionSpinner.getSelectedItemPosition() == OPENPGP_ENCRYPTION) { // OpenPGP encryption selected.
381 // Show the OpenKeychain import instructions.
382 openKeychainImportInstructionTextView.setVisibility(View.VISIBLE);
384 // Set the text on the import/export button to be `Decrypt`.
385 importExportButton.setText(R.string.decrypt);
387 // Enable the decrypt button if there is a file name.
388 importExportButton.setEnabled(!fileNameEditText.getText().toString().isEmpty());
389 } else { // OpenPGP encryption not selected.
390 // Hide the OpenKeychain import instructions.
391 openKeychainImportInstructionTextView.setVisibility(View.GONE);
393 // Set the text on the import/export button to be `Import`.
394 importExportButton.setText(R.string.import_button);
397 // Display the file name views.
398 fileNameLinearLayout.setVisibility(View.VISIBLE);
399 importExportButton.setVisibility(View.VISIBLE);
402 case R.id.export_radiobutton:
403 // Hide the OpenKeychain import instructions.
404 openKeychainImportInstructionTextView.setVisibility(View.GONE);
406 // Set the text on the import/export button to be `Export`.
407 importExportButton.setText(R.string.export);
409 // Show the import/export button.
410 importExportButton.setVisibility(View.VISIBLE);
412 // Check to see if OpenPGP encryption is selected.
413 if (encryptionSpinner.getSelectedItemPosition() == OPENPGP_ENCRYPTION) { // OpenPGP encryption is selected.
414 // Hide the file name views.
415 fileNameLinearLayout.setVisibility(View.GONE);
417 // Enable the export button.
418 importExportButton.setEnabled(true);
419 } else { // OpenPGP encryption is not selected.
420 // Show the file name views.
421 fileNameLinearLayout.setVisibility(View.VISIBLE);
427 public void browse(View view) {
428 // Get a handle for the import radiobutton.
429 RadioButton importRadioButton = findViewById(R.id.import_radiobutton);
431 // Check to see if import or export is selected.
432 if (importRadioButton.isChecked()) { // Import is selected.
433 // Create the file picker intent.
434 Intent importBrowseIntent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
436 // Set the intent MIME type to include all files so that everything is visible.
437 importBrowseIntent.setType("*/*");
439 // Set the initial directory if the minimum API >= 26.
440 if (Build.VERSION.SDK_INT >= 26) {
441 importBrowseIntent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, Environment.getExternalStorageDirectory());
444 // Request a file that can be opened.
445 importBrowseIntent.addCategory(Intent.CATEGORY_OPENABLE);
447 // Launch the file picker.
448 startActivityForResult(importBrowseIntent, BROWSE_RESULT_CODE);
449 } else { // Export is selected
450 // Create the file picker intent.
451 Intent exportBrowseIntent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
453 // Set the intent MIME type to include all files so that everything is visible.
454 exportBrowseIntent.setType("*/*");
456 // Set the initial export file name.
457 exportBrowseIntent.putExtra(Intent.EXTRA_TITLE, getString(R.string.settings_pbs));
459 // Set the initial directory if the minimum API >= 26.
460 if (Build.VERSION.SDK_INT >= 26) {
461 exportBrowseIntent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, Environment.getExternalStorageDirectory());
464 // Request a file that can be opened.
465 exportBrowseIntent.addCategory(Intent.CATEGORY_OPENABLE);
467 // Launch the file picker.
468 startActivityForResult(exportBrowseIntent, BROWSE_RESULT_CODE);
472 public void importExport(View view) {
473 // Get a handle for the views.
474 Spinner encryptionSpinner = findViewById(R.id.encryption_spinner);
475 RadioButton importRadioButton = findViewById(R.id.import_radiobutton);
476 RadioButton exportRadioButton = findViewById(R.id.export_radiobutton);
478 // Check to see if the storage permission is needed.
479 if ((encryptionSpinner.getSelectedItemPosition() == OPENPGP_ENCRYPTION) && exportRadioButton.isChecked()) { // Permission not needed to export via OpenKeychain.
480 // Export the settings.
482 } else if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // The storage permission has been granted.
483 // Check to see if import or export is selected.
484 if (importRadioButton.isChecked()) { // Import is selected.
485 // Import the settings.
487 } else { // Export is selected.
488 // Export the settings.
491 } else { // The storage permission has not been granted.
492 // Get a handle for the file name EditText.
493 EditText fileNameEditText = findViewById(R.id.file_name_edittext);
495 // Get the file name string.
496 String fileNameString = fileNameEditText.getText().toString();
498 // Get the external private directory `File`.
499 File externalPrivateDirectoryFile = getExternalFilesDir(null);
501 // Remove the incorrect lint error below that the file might be null.
502 assert externalPrivateDirectoryFile != null;
504 // Get the external private directory string.
505 String externalPrivateDirectory = externalPrivateDirectoryFile.toString();
507 // Check to see if the file path is in the external private directory.
508 if (fileNameString.startsWith(externalPrivateDirectory)) { // The file path is in the external private directory.
509 // Check to see if import or export is selected.
510 if (importRadioButton.isChecked()) { // Import is selected.
511 // Import the settings.
513 } else { // Export is selected.
514 // Export the settings.
517 } else { // The file path is in a public directory.
518 // Check if the user has previously denied the storage permission.
519 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
520 // Instantiate the storage permission alert dialog.
521 DialogFragment storagePermissionDialogFragment = new StoragePermissionDialog();
523 // Show the storage permission alert dialog. The permission will be requested when the dialog is closed.
524 storagePermissionDialogFragment.show(getSupportFragmentManager(), getString(R.string.storage_permission));
525 } else { // Show the permission request directly.
526 // Request the storage permission. The export will be run when it finishes.
527 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
534 public void onCloseStoragePermissionDialog() {
535 // Request the write external storage permission. The import/export will be run when it finishes.
536 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
540 public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
541 // Get a handle for the import radiobutton.
542 RadioButton importRadioButton = findViewById(R.id.import_radiobutton);
544 // Check to see if the storage permission was granted. If the dialog was canceled the grant results will be empty.
545 if ((grantResults.length > 0) && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) { // The storage permission was granted.
546 // Run the import or export methods according to which radio button is selected.
547 if (importRadioButton.isChecked()) { // Import is selected.
548 // Import the settings.
550 } else { // Export is selected.
551 // Export the settings.
554 } else { // The storage permission was not granted.
555 // Display an error snackbar.
556 Snackbar.make(importRadioButton, getString(R.string.cannot_use_location), Snackbar.LENGTH_LONG).show();
561 public void onActivityResult(int requestCode, int resultCode, Intent data) {
562 switch (requestCode) {
563 case (BROWSE_RESULT_CODE):
564 // Don't do anything if the user pressed back from the file picker.
565 if (resultCode == Activity.RESULT_OK) {
566 // Get a handle for the file name edit text.
567 EditText fileNameEditText = findViewById(R.id.file_name_edittext);
569 // Get the file name URI.
570 Uri fileNameUri = data.getData();
572 // Remove the lint warning that the file name URI might be null.
573 assert fileNameUri != null;
575 // Get the raw file name path.
576 String rawFileNamePath = fileNameUri.getPath();
578 // Remove the incorrect lint warning that the file name path might be null.
579 assert rawFileNamePath != null;
581 // Check to see if the file name Path includes a valid storage location.
582 if (rawFileNamePath.contains(":")) { // The path is valid.
583 // Split the path into the initial content uri and the final path information.
584 String fileNameContentPath = rawFileNamePath.substring(0, rawFileNamePath.indexOf(":"));
585 String fileNameFinalPath = rawFileNamePath.substring(rawFileNamePath.indexOf(":") + 1);
587 // Create the file name path string.
590 // Construct the file name path.
591 switch (fileNameContentPath) {
592 // The documents home has a special content path.
593 case "/document/home":
594 fileNamePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS) + "/" + fileNameFinalPath;
597 // Everything else for the primary user should be in `/document/primary`.
598 case "/document/primary":
599 fileNamePath = Environment.getExternalStorageDirectory() + "/" + fileNameFinalPath;
602 // Just in case, catch everything else and place it in the external storage directory.
604 fileNamePath = Environment.getExternalStorageDirectory() + "/" + fileNameFinalPath;
608 // Set the file name path as the text of the file name EditText.
609 fileNameEditText.setText(fileNamePath);
610 } else { // The path is invalid.
611 Snackbar.make(fileNameEditText, rawFileNamePath + " " + getString(R.string.invalid_location), Snackbar.LENGTH_INDEFINITE).show();
616 case OPENPGP_EXPORT_RESULT_CODE:
617 // Get the temporary unencrypted export file.
618 File temporaryUnencryptedExportFile = new File(getApplicationContext().getCacheDir() + "/" + getString(R.string.settings_pbs));
620 // Delete the temporary unencrypted export file if it exists.
621 if (temporaryUnencryptedExportFile.exists()) {
622 //noinspection ResultOfMethodCallIgnored
623 temporaryUnencryptedExportFile.delete();
629 private void exportSettings() {
630 // Get a handle for the views.
631 Spinner encryptionSpinner = findViewById(R.id.encryption_spinner);
632 EditText fileNameEditText = findViewById(R.id.file_name_edittext);
634 // Instantiate the import export database helper.
635 ImportExportDatabaseHelper importExportDatabaseHelper = new ImportExportDatabaseHelper();
637 // Get the export file string.
638 String exportFileString = fileNameEditText.getText().toString();
640 // Get the export and temporary unencrypted export files.
641 File exportFile = new File(exportFileString);
642 File temporaryUnencryptedExportFile = new File(getApplicationContext().getCacheDir() + "/" + getString(R.string.settings_pbs));
644 // Create an export status string.
647 // Export according to the encryption type.
648 switch (encryptionSpinner.getSelectedItemPosition()) {
650 // Export the unencrypted file.
651 exportStatus = importExportDatabaseHelper.exportUnencrypted(exportFile, this);
653 // Show a disposition snackbar.
654 if (exportStatus.equals(ImportExportDatabaseHelper.EXPORT_SUCCESSFUL)) {
655 Snackbar.make(fileNameEditText, getString(R.string.export_successful), Snackbar.LENGTH_SHORT).show();
657 Snackbar.make(fileNameEditText, getString(R.string.export_failed) + " " + exportStatus, Snackbar.LENGTH_INDEFINITE).show();
661 case PASSWORD_ENCRYPTION:
662 // Create an unencrypted export in a private directory.
663 exportStatus = importExportDatabaseHelper.exportUnencrypted(temporaryUnencryptedExportFile, this);
666 // Create an unencrypted export file input stream.
667 FileInputStream unencryptedExportFileInputStream = new FileInputStream(temporaryUnencryptedExportFile);
669 // Delete the encrypted export file if it exists.
670 if (exportFile.exists()) {
671 //noinspection ResultOfMethodCallIgnored
675 // Create an encrypted export file output stream.
676 FileOutputStream encryptedExportFileOutputStream = new FileOutputStream(exportFile);
678 // Get a handle for the encryption password EditText.
679 EditText encryptionPasswordEditText = findViewById(R.id.password_encryption_edittext);
681 // Get the encryption password.
682 String encryptionPasswordString = encryptionPasswordEditText.getText().toString();
684 // Initialize a secure random number generator.
685 SecureRandom secureRandom = new SecureRandom();
687 // Get a 256 bit (32 byte) random salt.
688 byte[] saltByteArray = new byte[32];
689 secureRandom.nextBytes(saltByteArray);
691 // Convert the encryption password to a byte array.
692 byte[] encryptionPasswordByteArray = encryptionPasswordString.getBytes(StandardCharsets.UTF_8);
694 // Append the salt to the encryption password byte array. This protects against rainbow table attacks.
695 byte[] encryptionPasswordWithSaltByteArray = new byte[encryptionPasswordByteArray.length + saltByteArray.length];
696 System.arraycopy(encryptionPasswordByteArray, 0, encryptionPasswordWithSaltByteArray, 0, encryptionPasswordByteArray.length);
697 System.arraycopy(saltByteArray, 0, encryptionPasswordWithSaltByteArray, encryptionPasswordByteArray.length, saltByteArray.length);
699 // Get a SHA-512 message digest.
700 MessageDigest messageDigest = MessageDigest.getInstance("SHA-512");
702 // Hash the salted encryption password. Otherwise, any characters after the 32nd character in the password are ignored.
703 byte[] hashedEncryptionPasswordWithSaltByteArray = messageDigest.digest(encryptionPasswordWithSaltByteArray);
705 // Truncate the encryption password byte array to 256 bits (32 bytes).
706 byte[] truncatedHashedEncryptionPasswordWithSaltByteArray = Arrays.copyOf(hashedEncryptionPasswordWithSaltByteArray, 32);
708 // Create an AES secret key from the encryption password byte array.
709 SecretKeySpec secretKey = new SecretKeySpec(truncatedHashedEncryptionPasswordWithSaltByteArray, "AES");
711 // Generate a random 12 byte initialization vector. According to NIST, a 12 byte initialization vector is more secure than a 16 byte one.
712 byte[] initializationVector = new byte[12];
713 secureRandom.nextBytes(initializationVector);
715 // 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.
716 Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
718 // Set the GCM tag length to be 128 bits (the maximum) and apply the initialization vector.
719 GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, initializationVector);
721 // Initialize the cipher.
722 cipher.init(Cipher.ENCRYPT_MODE, secretKey, gcmParameterSpec);
724 // Add the salt and the initialization vector to the export file.
725 encryptedExportFileOutputStream.write(saltByteArray);
726 encryptedExportFileOutputStream.write(initializationVector);
728 // Create a cipher output stream.
729 CipherOutputStream cipherOutputStream = new CipherOutputStream(encryptedExportFileOutputStream, cipher);
731 // 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.
732 int numberOfBytesRead;
733 byte[] encryptedBytes = new byte[16];
735 // 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.
736 while ((numberOfBytesRead = unencryptedExportFileInputStream.read(encryptedBytes)) != -1) {
737 // Write the data to the cipher output stream.
738 cipherOutputStream.write(encryptedBytes, 0, numberOfBytesRead);
741 // Close the streams.
742 cipherOutputStream.flush();
743 cipherOutputStream.close();
744 encryptedExportFileOutputStream.close();
745 unencryptedExportFileInputStream.close();
747 // Wipe the encryption data from memory.
748 //noinspection UnusedAssignment
749 encryptionPasswordString = "";
750 Arrays.fill(saltByteArray, (byte) 0);
751 Arrays.fill(encryptionPasswordByteArray, (byte) 0);
752 Arrays.fill(encryptionPasswordWithSaltByteArray, (byte) 0);
753 Arrays.fill(hashedEncryptionPasswordWithSaltByteArray, (byte) 0);
754 Arrays.fill(truncatedHashedEncryptionPasswordWithSaltByteArray, (byte) 0);
755 Arrays.fill(initializationVector, (byte) 0);
756 Arrays.fill(encryptedBytes, (byte) 0);
758 // Delete the temporary unencrypted export file.
759 //noinspection ResultOfMethodCallIgnored
760 temporaryUnencryptedExportFile.delete();
761 } catch (Exception exception) {
762 exportStatus = exception.toString();
765 // Show a disposition snackbar.
766 if (exportStatus.equals(ImportExportDatabaseHelper.EXPORT_SUCCESSFUL)) {
767 Snackbar.make(fileNameEditText, getString(R.string.export_successful), Snackbar.LENGTH_SHORT).show();
769 Snackbar.make(fileNameEditText, getString(R.string.export_failed) + " " + exportStatus, Snackbar.LENGTH_INDEFINITE).show();
773 case OPENPGP_ENCRYPTION:
774 // Create an unencrypted export in the private location.
775 importExportDatabaseHelper.exportUnencrypted(temporaryUnencryptedExportFile, this);
777 // Create an encryption intent for OpenKeychain.
778 Intent openKeychainEncryptIntent = new Intent("org.sufficientlysecure.keychain.action.ENCRYPT_DATA");
780 // Include the temporary unencrypted export file URI.
781 openKeychainEncryptIntent.setData(FileProvider.getUriForFile(this, getString(R.string.file_provider), temporaryUnencryptedExportFile));
783 // Allow OpenKeychain to read the file URI.
784 openKeychainEncryptIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
786 // Send the intent to the OpenKeychain package.
787 openKeychainEncryptIntent.setPackage("org.sufficientlysecure.keychain");
790 startActivityForResult(openKeychainEncryptIntent, OPENPGP_EXPORT_RESULT_CODE);
794 // Add the file to the list of recent files. This doesn't currently work, but maybe it will someday.
795 MediaScannerConnection.scanFile(this, new String[] {exportFileString}, new String[] {"application/x-sqlite3"}, null);
798 private void importSettings() {
799 // Get a handle for the views.
800 Spinner encryptionSpinner = findViewById(R.id.encryption_spinner);
801 EditText fileNameEditText = findViewById(R.id.file_name_edittext);
803 // Instantiate the import export database helper.
804 ImportExportDatabaseHelper importExportDatabaseHelper = new ImportExportDatabaseHelper();
806 // Get the import file.
807 File importFile = new File(fileNameEditText.getText().toString());
809 // Initialize the import status string
810 String importStatus = "";
812 // Import according to the encryption type.
813 switch (encryptionSpinner.getSelectedItemPosition()) {
815 // Import the unencrypted file.
816 importStatus = importExportDatabaseHelper.importUnencrypted(importFile, this);
819 case PASSWORD_ENCRYPTION:
820 // Use a private temporary import location.
821 File temporaryUnencryptedImportFile = new File(getApplicationContext().getCacheDir() + "/" + getString(R.string.settings_pbs));
824 // Create an encrypted import file input stream.
825 FileInputStream encryptedImportFileInputStream = new FileInputStream(importFile);
827 // Delete the temporary import file if it exists.
828 if (temporaryUnencryptedImportFile.exists()) {
829 //noinspection ResultOfMethodCallIgnored
830 temporaryUnencryptedImportFile.delete();
833 // Create an unencrypted import file output stream.
834 FileOutputStream unencryptedImportFileOutputStream = new FileOutputStream(temporaryUnencryptedImportFile);
836 // Get a handle for the encryption password EditText.
837 EditText encryptionPasswordEditText = findViewById(R.id.password_encryption_edittext);
839 // Get the encryption password.
840 String encryptionPasswordString = encryptionPasswordEditText.getText().toString();
842 // Get the salt from the beginning of the import file.
843 byte[] saltByteArray = new byte[32];
844 //noinspection ResultOfMethodCallIgnored
845 encryptedImportFileInputStream.read(saltByteArray);
847 // Get the initialization vector from the import file.
848 byte[] initializationVector = new byte[12];
849 //noinspection ResultOfMethodCallIgnored
850 encryptedImportFileInputStream.read(initializationVector);
852 // Convert the encryption password to a byte array.
853 byte[] encryptionPasswordByteArray = encryptionPasswordString.getBytes(StandardCharsets.UTF_8);
855 // Append the salt to the encryption password byte array. This protects against rainbow table attacks.
856 byte[] encryptionPasswordWithSaltByteArray = new byte[encryptionPasswordByteArray.length + saltByteArray.length];
857 System.arraycopy(encryptionPasswordByteArray, 0, encryptionPasswordWithSaltByteArray, 0, encryptionPasswordByteArray.length);
858 System.arraycopy(saltByteArray, 0, encryptionPasswordWithSaltByteArray, encryptionPasswordByteArray.length, saltByteArray.length);
860 // Get a SHA-512 message digest.
861 MessageDigest messageDigest = MessageDigest.getInstance("SHA-512");
863 // Hash the salted encryption password. Otherwise, any characters after the 32nd character in the password are ignored.
864 byte[] hashedEncryptionPasswordWithSaltByteArray = messageDigest.digest(encryptionPasswordWithSaltByteArray);
866 // Truncate the encryption password byte array to 256 bits (32 bytes).
867 byte[] truncatedHashedEncryptionPasswordWithSaltByteArray = Arrays.copyOf(hashedEncryptionPasswordWithSaltByteArray, 32);
869 // Create an AES secret key from the encryption password byte array.
870 SecretKeySpec secretKey = new SecretKeySpec(truncatedHashedEncryptionPasswordWithSaltByteArray, "AES");
872 // 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.
873 Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
875 // Set the GCM tag length to be 128 bits (the maximum) and apply the initialization vector.
876 GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, initializationVector);
878 // Initialize the cipher.
879 cipher.init(Cipher.DECRYPT_MODE, secretKey, gcmParameterSpec);
881 // Create a cipher input stream.
882 CipherInputStream cipherInputStream = new CipherInputStream(encryptedImportFileInputStream, cipher);
884 // 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.
885 int numberOfBytesRead;
886 byte[] decryptedBytes = new byte[16];
888 // 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.
889 while ((numberOfBytesRead = cipherInputStream.read(decryptedBytes)) != -1) {
890 // Write the data to the unencrypted import file output stream.
891 unencryptedImportFileOutputStream.write(decryptedBytes, 0, numberOfBytesRead);
894 // Close the streams.
895 unencryptedImportFileOutputStream.flush();
896 unencryptedImportFileOutputStream.close();
897 cipherInputStream.close();
898 encryptedImportFileInputStream.close();
900 // Wipe the encryption data from memory.
901 //noinspection UnusedAssignment
902 encryptionPasswordString = "";
903 Arrays.fill(saltByteArray, (byte) 0);
904 Arrays.fill(initializationVector, (byte) 0);
905 Arrays.fill(encryptionPasswordByteArray, (byte) 0);
906 Arrays.fill(encryptionPasswordWithSaltByteArray, (byte) 0);
907 Arrays.fill(hashedEncryptionPasswordWithSaltByteArray, (byte) 0);
908 Arrays.fill(truncatedHashedEncryptionPasswordWithSaltByteArray, (byte) 0);
909 Arrays.fill(decryptedBytes, (byte) 0);
911 // Import the unencrypted database from the private location.
912 importStatus = importExportDatabaseHelper.importUnencrypted(temporaryUnencryptedImportFile, this);
914 // Delete the temporary unencrypted import file.
915 //noinspection ResultOfMethodCallIgnored
916 temporaryUnencryptedImportFile.delete();
917 } catch (Exception exception) {
918 importStatus = exception.toString();
922 case OPENPGP_ENCRYPTION:
924 // Create an decryption intent for OpenKeychain.
925 Intent openKeychainDecryptIntent = new Intent("org.sufficientlysecure.keychain.action.DECRYPT_DATA");
927 // Include the URI to be decrypted.
928 openKeychainDecryptIntent.setData(FileProvider.getUriForFile(this, getString(R.string.file_provider), importFile));
930 // Allow OpenKeychain to read the file URI.
931 openKeychainDecryptIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
933 // Send the intent to the OpenKeychain package.
934 openKeychainDecryptIntent.setPackage("org.sufficientlysecure.keychain");
937 startActivity(openKeychainDecryptIntent);
938 } catch (IllegalArgumentException exception) { // The file import location is not valid.
939 // Display a snack bar with the import error.
940 Snackbar.make(fileNameEditText, getString(R.string.import_failed) + " " + exception.toString(), Snackbar.LENGTH_INDEFINITE).show();
945 // Respond to the import disposition.
946 if (importStatus.equals(ImportExportDatabaseHelper.IMPORT_SUCCESSFUL)) { // The import was successful.
947 // Create an intent to restart Privacy Browser.
948 Intent restartIntent = getParentActivityIntent();
950 // Assert that the intent is not null to remove the lint error below.
951 assert restartIntent != null;
953 // `Intent.FLAG_ACTIVITY_CLEAR_TASK` removes all activities from the stack. It requires `Intent.FLAG_ACTIVITY_NEW_TASK`.
954 restartIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
956 // Create a restart handler.
957 Handler restartHandler = new Handler();
959 // Create a restart runnable.
960 Runnable restartRunnable = () -> {
961 // Restart Privacy Browser.
962 startActivity(restartIntent);
964 // Kill this instance of Privacy Browser. Otherwise, the app exhibits sporadic behavior after the restart.
968 // Restart Privacy Browser after 100 milliseconds to allow enough time for the preferences to be saved.
969 restartHandler.postDelayed(restartRunnable, 100);
971 } else if (!(encryptionSpinner.getSelectedItemPosition() == OPENPGP_ENCRYPTION)){ // The import was not successful.
972 // Display a snack bar with the import error.
973 Snackbar.make(fileNameEditText, getString(R.string.import_failed) + " " + importStatus, Snackbar.LENGTH_INDEFINITE).show();