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.os.Build;
29 import android.os.Bundle;
30 import android.os.Environment;
31 import android.os.Handler;
32 import android.preference.PreferenceManager;
33 import android.provider.DocumentsContract;
34 import android.text.Editable;
35 import android.text.TextWatcher;
36 import android.view.View;
37 import android.view.WindowManager;
38 import android.widget.AdapterView;
39 import android.widget.ArrayAdapter;
40 import android.widget.Button;
41 import android.widget.EditText;
42 import android.widget.LinearLayout;
43 import android.widget.RadioButton;
44 import android.widget.Spinner;
45 import android.widget.TextView;
47 import androidx.annotation.NonNull;
48 import androidx.appcompat.app.ActionBar;
49 import androidx.appcompat.app.AppCompatActivity;
50 import androidx.appcompat.widget.Toolbar;
51 import androidx.cardview.widget.CardView;
52 import androidx.core.app.ActivityCompat;
53 import androidx.core.content.ContextCompat;
54 import androidx.core.content.FileProvider;
55 import androidx.fragment.app.DialogFragment;
57 import com.google.android.material.snackbar.Snackbar;
58 import com.google.android.material.textfield.TextInputLayout;
60 import com.stoutner.privacybrowser.R;
61 import com.stoutner.privacybrowser.dialogs.StoragePermissionDialog;
62 import com.stoutner.privacybrowser.helpers.FileNameHelper;
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 // Instantiate the file name helper.
570 FileNameHelper fileNameHelper = new FileNameHelper();
572 // Convert the file name URI to a file name path.
573 String fileNamePath = fileNameHelper.convertUriToFileNamePath(data.getData());
575 // Set the file name path as the text of the file name edit text.
576 fileNameEditText.setText(fileNamePath);
580 case OPENPGP_EXPORT_RESULT_CODE:
581 // Get the temporary unencrypted export file.
582 File temporaryUnencryptedExportFile = new File(getApplicationContext().getCacheDir() + "/" + getString(R.string.settings_pbs));
584 // Delete the temporary unencrypted export file if it exists.
585 if (temporaryUnencryptedExportFile.exists()) {
586 //noinspection ResultOfMethodCallIgnored
587 temporaryUnencryptedExportFile.delete();
593 private void exportSettings() {
594 // Get a handle for the views.
595 Spinner encryptionSpinner = findViewById(R.id.encryption_spinner);
596 EditText fileNameEditText = findViewById(R.id.file_name_edittext);
598 // Instantiate the import export database helper.
599 ImportExportDatabaseHelper importExportDatabaseHelper = new ImportExportDatabaseHelper();
601 // Get the export file string.
602 String exportFileString = fileNameEditText.getText().toString();
604 // Get the export and temporary unencrypted export files.
605 File exportFile = new File(exportFileString);
606 File temporaryUnencryptedExportFile = new File(getApplicationContext().getCacheDir() + "/" + getString(R.string.settings_pbs));
608 // Create an export status string.
611 // Export according to the encryption type.
612 switch (encryptionSpinner.getSelectedItemPosition()) {
614 // Export the unencrypted file.
615 exportStatus = importExportDatabaseHelper.exportUnencrypted(exportFile, this);
617 // Show a disposition snackbar.
618 if (exportStatus.equals(ImportExportDatabaseHelper.EXPORT_SUCCESSFUL)) {
619 Snackbar.make(fileNameEditText, getString(R.string.export_successful), Snackbar.LENGTH_SHORT).show();
621 Snackbar.make(fileNameEditText, getString(R.string.export_failed) + " " + exportStatus, Snackbar.LENGTH_INDEFINITE).show();
625 case PASSWORD_ENCRYPTION:
626 // Create an unencrypted export in a private directory.
627 exportStatus = importExportDatabaseHelper.exportUnencrypted(temporaryUnencryptedExportFile, this);
630 // Create an unencrypted export file input stream.
631 FileInputStream unencryptedExportFileInputStream = new FileInputStream(temporaryUnencryptedExportFile);
633 // Delete the encrypted export file if it exists.
634 if (exportFile.exists()) {
635 //noinspection ResultOfMethodCallIgnored
639 // Create an encrypted export file output stream.
640 FileOutputStream encryptedExportFileOutputStream = new FileOutputStream(exportFile);
642 // Get a handle for the encryption password EditText.
643 EditText encryptionPasswordEditText = findViewById(R.id.password_encryption_edittext);
645 // Get the encryption password.
646 String encryptionPasswordString = encryptionPasswordEditText.getText().toString();
648 // Initialize a secure random number generator.
649 SecureRandom secureRandom = new SecureRandom();
651 // Get a 256 bit (32 byte) random salt.
652 byte[] saltByteArray = new byte[32];
653 secureRandom.nextBytes(saltByteArray);
655 // Convert the encryption password to a byte array.
656 byte[] encryptionPasswordByteArray = encryptionPasswordString.getBytes(StandardCharsets.UTF_8);
658 // Append the salt to the encryption password byte array. This protects against rainbow table attacks.
659 byte[] encryptionPasswordWithSaltByteArray = new byte[encryptionPasswordByteArray.length + saltByteArray.length];
660 System.arraycopy(encryptionPasswordByteArray, 0, encryptionPasswordWithSaltByteArray, 0, encryptionPasswordByteArray.length);
661 System.arraycopy(saltByteArray, 0, encryptionPasswordWithSaltByteArray, encryptionPasswordByteArray.length, saltByteArray.length);
663 // Get a SHA-512 message digest.
664 MessageDigest messageDigest = MessageDigest.getInstance("SHA-512");
666 // Hash the salted encryption password. Otherwise, any characters after the 32nd character in the password are ignored.
667 byte[] hashedEncryptionPasswordWithSaltByteArray = messageDigest.digest(encryptionPasswordWithSaltByteArray);
669 // Truncate the encryption password byte array to 256 bits (32 bytes).
670 byte[] truncatedHashedEncryptionPasswordWithSaltByteArray = Arrays.copyOf(hashedEncryptionPasswordWithSaltByteArray, 32);
672 // Create an AES secret key from the encryption password byte array.
673 SecretKeySpec secretKey = new SecretKeySpec(truncatedHashedEncryptionPasswordWithSaltByteArray, "AES");
675 // Generate a random 12 byte initialization vector. According to NIST, a 12 byte initialization vector is more secure than a 16 byte one.
676 byte[] initializationVector = new byte[12];
677 secureRandom.nextBytes(initializationVector);
679 // 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.
680 Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
682 // Set the GCM tag length to be 128 bits (the maximum) and apply the initialization vector.
683 GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, initializationVector);
685 // Initialize the cipher.
686 cipher.init(Cipher.ENCRYPT_MODE, secretKey, gcmParameterSpec);
688 // Add the salt and the initialization vector to the export file.
689 encryptedExportFileOutputStream.write(saltByteArray);
690 encryptedExportFileOutputStream.write(initializationVector);
692 // Create a cipher output stream.
693 CipherOutputStream cipherOutputStream = new CipherOutputStream(encryptedExportFileOutputStream, cipher);
695 // 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.
696 int numberOfBytesRead;
697 byte[] encryptedBytes = new byte[16];
699 // 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.
700 while ((numberOfBytesRead = unencryptedExportFileInputStream.read(encryptedBytes)) != -1) {
701 // Write the data to the cipher output stream.
702 cipherOutputStream.write(encryptedBytes, 0, numberOfBytesRead);
705 // Close the streams.
706 cipherOutputStream.flush();
707 cipherOutputStream.close();
708 encryptedExportFileOutputStream.close();
709 unencryptedExportFileInputStream.close();
711 // Wipe the encryption data from memory.
712 //noinspection UnusedAssignment
713 encryptionPasswordString = "";
714 Arrays.fill(saltByteArray, (byte) 0);
715 Arrays.fill(encryptionPasswordByteArray, (byte) 0);
716 Arrays.fill(encryptionPasswordWithSaltByteArray, (byte) 0);
717 Arrays.fill(hashedEncryptionPasswordWithSaltByteArray, (byte) 0);
718 Arrays.fill(truncatedHashedEncryptionPasswordWithSaltByteArray, (byte) 0);
719 Arrays.fill(initializationVector, (byte) 0);
720 Arrays.fill(encryptedBytes, (byte) 0);
722 // Delete the temporary unencrypted export file.
723 //noinspection ResultOfMethodCallIgnored
724 temporaryUnencryptedExportFile.delete();
725 } catch (Exception exception) {
726 exportStatus = exception.toString();
729 // Show a disposition snackbar.
730 if (exportStatus.equals(ImportExportDatabaseHelper.EXPORT_SUCCESSFUL)) {
731 Snackbar.make(fileNameEditText, getString(R.string.export_successful), Snackbar.LENGTH_SHORT).show();
733 Snackbar.make(fileNameEditText, getString(R.string.export_failed) + " " + exportStatus, Snackbar.LENGTH_INDEFINITE).show();
737 case OPENPGP_ENCRYPTION:
738 // Create an unencrypted export in the private location.
739 importExportDatabaseHelper.exportUnencrypted(temporaryUnencryptedExportFile, this);
741 // Create an encryption intent for OpenKeychain.
742 Intent openKeychainEncryptIntent = new Intent("org.sufficientlysecure.keychain.action.ENCRYPT_DATA");
744 // Include the temporary unencrypted export file URI.
745 openKeychainEncryptIntent.setData(FileProvider.getUriForFile(this, getString(R.string.file_provider), temporaryUnencryptedExportFile));
747 // Allow OpenKeychain to read the file URI.
748 openKeychainEncryptIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
750 // Send the intent to the OpenKeychain package.
751 openKeychainEncryptIntent.setPackage("org.sufficientlysecure.keychain");
754 startActivityForResult(openKeychainEncryptIntent, OPENPGP_EXPORT_RESULT_CODE);
758 // Add the file to the list of recent files. This doesn't currently work, but maybe it will someday.
759 MediaScannerConnection.scanFile(this, new String[] {exportFileString}, new String[] {"application/x-sqlite3"}, null);
762 private void importSettings() {
763 // Get a handle for the views.
764 Spinner encryptionSpinner = findViewById(R.id.encryption_spinner);
765 EditText fileNameEditText = findViewById(R.id.file_name_edittext);
767 // Instantiate the import export database helper.
768 ImportExportDatabaseHelper importExportDatabaseHelper = new ImportExportDatabaseHelper();
770 // Get the import file.
771 File importFile = new File(fileNameEditText.getText().toString());
773 // Initialize the import status string
774 String importStatus = "";
776 // Import according to the encryption type.
777 switch (encryptionSpinner.getSelectedItemPosition()) {
779 // Import the unencrypted file.
780 importStatus = importExportDatabaseHelper.importUnencrypted(importFile, this);
783 case PASSWORD_ENCRYPTION:
784 // Use a private temporary import location.
785 File temporaryUnencryptedImportFile = new File(getApplicationContext().getCacheDir() + "/" + getString(R.string.settings_pbs));
788 // Create an encrypted import file input stream.
789 FileInputStream encryptedImportFileInputStream = new FileInputStream(importFile);
791 // Delete the temporary import file if it exists.
792 if (temporaryUnencryptedImportFile.exists()) {
793 //noinspection ResultOfMethodCallIgnored
794 temporaryUnencryptedImportFile.delete();
797 // Create an unencrypted import file output stream.
798 FileOutputStream unencryptedImportFileOutputStream = new FileOutputStream(temporaryUnencryptedImportFile);
800 // Get a handle for the encryption password EditText.
801 EditText encryptionPasswordEditText = findViewById(R.id.password_encryption_edittext);
803 // Get the encryption password.
804 String encryptionPasswordString = encryptionPasswordEditText.getText().toString();
806 // Get the salt from the beginning of the import file.
807 byte[] saltByteArray = new byte[32];
808 //noinspection ResultOfMethodCallIgnored
809 encryptedImportFileInputStream.read(saltByteArray);
811 // Get the initialization vector from the import file.
812 byte[] initializationVector = new byte[12];
813 //noinspection ResultOfMethodCallIgnored
814 encryptedImportFileInputStream.read(initializationVector);
816 // Convert the encryption password to a byte array.
817 byte[] encryptionPasswordByteArray = encryptionPasswordString.getBytes(StandardCharsets.UTF_8);
819 // Append the salt to the encryption password byte array. This protects against rainbow table attacks.
820 byte[] encryptionPasswordWithSaltByteArray = new byte[encryptionPasswordByteArray.length + saltByteArray.length];
821 System.arraycopy(encryptionPasswordByteArray, 0, encryptionPasswordWithSaltByteArray, 0, encryptionPasswordByteArray.length);
822 System.arraycopy(saltByteArray, 0, encryptionPasswordWithSaltByteArray, encryptionPasswordByteArray.length, saltByteArray.length);
824 // Get a SHA-512 message digest.
825 MessageDigest messageDigest = MessageDigest.getInstance("SHA-512");
827 // Hash the salted encryption password. Otherwise, any characters after the 32nd character in the password are ignored.
828 byte[] hashedEncryptionPasswordWithSaltByteArray = messageDigest.digest(encryptionPasswordWithSaltByteArray);
830 // Truncate the encryption password byte array to 256 bits (32 bytes).
831 byte[] truncatedHashedEncryptionPasswordWithSaltByteArray = Arrays.copyOf(hashedEncryptionPasswordWithSaltByteArray, 32);
833 // Create an AES secret key from the encryption password byte array.
834 SecretKeySpec secretKey = new SecretKeySpec(truncatedHashedEncryptionPasswordWithSaltByteArray, "AES");
836 // 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.
837 Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
839 // Set the GCM tag length to be 128 bits (the maximum) and apply the initialization vector.
840 GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, initializationVector);
842 // Initialize the cipher.
843 cipher.init(Cipher.DECRYPT_MODE, secretKey, gcmParameterSpec);
845 // Create a cipher input stream.
846 CipherInputStream cipherInputStream = new CipherInputStream(encryptedImportFileInputStream, cipher);
848 // 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.
849 int numberOfBytesRead;
850 byte[] decryptedBytes = new byte[16];
852 // 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.
853 while ((numberOfBytesRead = cipherInputStream.read(decryptedBytes)) != -1) {
854 // Write the data to the unencrypted import file output stream.
855 unencryptedImportFileOutputStream.write(decryptedBytes, 0, numberOfBytesRead);
858 // Close the streams.
859 unencryptedImportFileOutputStream.flush();
860 unencryptedImportFileOutputStream.close();
861 cipherInputStream.close();
862 encryptedImportFileInputStream.close();
864 // Wipe the encryption data from memory.
865 //noinspection UnusedAssignment
866 encryptionPasswordString = "";
867 Arrays.fill(saltByteArray, (byte) 0);
868 Arrays.fill(initializationVector, (byte) 0);
869 Arrays.fill(encryptionPasswordByteArray, (byte) 0);
870 Arrays.fill(encryptionPasswordWithSaltByteArray, (byte) 0);
871 Arrays.fill(hashedEncryptionPasswordWithSaltByteArray, (byte) 0);
872 Arrays.fill(truncatedHashedEncryptionPasswordWithSaltByteArray, (byte) 0);
873 Arrays.fill(decryptedBytes, (byte) 0);
875 // Import the unencrypted database from the private location.
876 importStatus = importExportDatabaseHelper.importUnencrypted(temporaryUnencryptedImportFile, this);
878 // Delete the temporary unencrypted import file.
879 //noinspection ResultOfMethodCallIgnored
880 temporaryUnencryptedImportFile.delete();
881 } catch (Exception exception) {
882 importStatus = exception.toString();
886 case OPENPGP_ENCRYPTION:
888 // Create an decryption intent for OpenKeychain.
889 Intent openKeychainDecryptIntent = new Intent("org.sufficientlysecure.keychain.action.DECRYPT_DATA");
891 // Include the URI to be decrypted.
892 openKeychainDecryptIntent.setData(FileProvider.getUriForFile(this, getString(R.string.file_provider), importFile));
894 // Allow OpenKeychain to read the file URI.
895 openKeychainDecryptIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
897 // Send the intent to the OpenKeychain package.
898 openKeychainDecryptIntent.setPackage("org.sufficientlysecure.keychain");
901 startActivity(openKeychainDecryptIntent);
902 } catch (IllegalArgumentException exception) { // The file import location is not valid.
903 // Display a snack bar with the import error.
904 Snackbar.make(fileNameEditText, getString(R.string.import_failed) + " " + exception.toString(), Snackbar.LENGTH_INDEFINITE).show();
909 // Respond to the import disposition.
910 if (importStatus.equals(ImportExportDatabaseHelper.IMPORT_SUCCESSFUL)) { // The import was successful.
911 // Create an intent to restart Privacy Browser.
912 Intent restartIntent = getParentActivityIntent();
914 // Assert that the intent is not null to remove the lint error below.
915 assert restartIntent != null;
917 // `Intent.FLAG_ACTIVITY_CLEAR_TASK` removes all activities from the stack. It requires `Intent.FLAG_ACTIVITY_NEW_TASK`.
918 restartIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
920 // Create a restart handler.
921 Handler restartHandler = new Handler();
923 // Create a restart runnable.
924 Runnable restartRunnable = () -> {
925 // Restart Privacy Browser.
926 startActivity(restartIntent);
928 // Kill this instance of Privacy Browser. Otherwise, the app exhibits sporadic behavior after the restart.
932 // Restart Privacy Browser after 150 milliseconds to allow enough time for the preferences to be saved.
933 restartHandler.postDelayed(restartRunnable, 150);
935 } else if (!(encryptionSpinner.getSelectedItemPosition() == OPENPGP_ENCRYPTION)){ // The import was not successful.
936 // Display a snack bar with the import error.
937 Snackbar.make(fileNameEditText, getString(R.string.import_failed) + " " + importStatus, Snackbar.LENGTH_INDEFINITE).show();