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 // Check to see if the current file name final patch is a complete, valid path
591 if (fileNameFinalPath.startsWith("/storage/emulated/")) { // The existing file name final path is a complete, valid path.
592 // Use the provided file name path as is.
593 fileNamePath = fileNameFinalPath;
594 } else { // The existing file name final path is not a complete, valid path.
595 // Construct the file name path.
596 switch (fileNameContentPath) {
597 // The documents home has a special content path.
598 case "/document/home":
599 fileNamePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS) + "/" + fileNameFinalPath;
602 // Everything else for the primary user should be in `/document/primary`.
603 case "/document/primary":
604 fileNamePath = Environment.getExternalStorageDirectory() + "/" + fileNameFinalPath;
607 // Just in case, catch everything else and place it in the external storage directory.
609 fileNamePath = Environment.getExternalStorageDirectory() + "/" + fileNameFinalPath;
614 // Set the file name path as the text of the file name edit text.
615 fileNameEditText.setText(fileNamePath);
616 } else { // The path is invalid.
617 Snackbar.make(fileNameEditText, rawFileNamePath + " " + getString(R.string.invalid_location), Snackbar.LENGTH_INDEFINITE).show();
622 case OPENPGP_EXPORT_RESULT_CODE:
623 // Get the temporary unencrypted export file.
624 File temporaryUnencryptedExportFile = new File(getApplicationContext().getCacheDir() + "/" + getString(R.string.settings_pbs));
626 // Delete the temporary unencrypted export file if it exists.
627 if (temporaryUnencryptedExportFile.exists()) {
628 //noinspection ResultOfMethodCallIgnored
629 temporaryUnencryptedExportFile.delete();
635 private void exportSettings() {
636 // Get a handle for the views.
637 Spinner encryptionSpinner = findViewById(R.id.encryption_spinner);
638 EditText fileNameEditText = findViewById(R.id.file_name_edittext);
640 // Instantiate the import export database helper.
641 ImportExportDatabaseHelper importExportDatabaseHelper = new ImportExportDatabaseHelper();
643 // Get the export file string.
644 String exportFileString = fileNameEditText.getText().toString();
646 // Get the export and temporary unencrypted export files.
647 File exportFile = new File(exportFileString);
648 File temporaryUnencryptedExportFile = new File(getApplicationContext().getCacheDir() + "/" + getString(R.string.settings_pbs));
650 // Create an export status string.
653 // Export according to the encryption type.
654 switch (encryptionSpinner.getSelectedItemPosition()) {
656 // Export the unencrypted file.
657 exportStatus = importExportDatabaseHelper.exportUnencrypted(exportFile, this);
659 // Show a disposition snackbar.
660 if (exportStatus.equals(ImportExportDatabaseHelper.EXPORT_SUCCESSFUL)) {
661 Snackbar.make(fileNameEditText, getString(R.string.export_successful), Snackbar.LENGTH_SHORT).show();
663 Snackbar.make(fileNameEditText, getString(R.string.export_failed) + " " + exportStatus, Snackbar.LENGTH_INDEFINITE).show();
667 case PASSWORD_ENCRYPTION:
668 // Create an unencrypted export in a private directory.
669 exportStatus = importExportDatabaseHelper.exportUnencrypted(temporaryUnencryptedExportFile, this);
672 // Create an unencrypted export file input stream.
673 FileInputStream unencryptedExportFileInputStream = new FileInputStream(temporaryUnencryptedExportFile);
675 // Delete the encrypted export file if it exists.
676 if (exportFile.exists()) {
677 //noinspection ResultOfMethodCallIgnored
681 // Create an encrypted export file output stream.
682 FileOutputStream encryptedExportFileOutputStream = new FileOutputStream(exportFile);
684 // Get a handle for the encryption password EditText.
685 EditText encryptionPasswordEditText = findViewById(R.id.password_encryption_edittext);
687 // Get the encryption password.
688 String encryptionPasswordString = encryptionPasswordEditText.getText().toString();
690 // Initialize a secure random number generator.
691 SecureRandom secureRandom = new SecureRandom();
693 // Get a 256 bit (32 byte) random salt.
694 byte[] saltByteArray = new byte[32];
695 secureRandom.nextBytes(saltByteArray);
697 // Convert the encryption password to a byte array.
698 byte[] encryptionPasswordByteArray = encryptionPasswordString.getBytes(StandardCharsets.UTF_8);
700 // Append the salt to the encryption password byte array. This protects against rainbow table attacks.
701 byte[] encryptionPasswordWithSaltByteArray = new byte[encryptionPasswordByteArray.length + saltByteArray.length];
702 System.arraycopy(encryptionPasswordByteArray, 0, encryptionPasswordWithSaltByteArray, 0, encryptionPasswordByteArray.length);
703 System.arraycopy(saltByteArray, 0, encryptionPasswordWithSaltByteArray, encryptionPasswordByteArray.length, saltByteArray.length);
705 // Get a SHA-512 message digest.
706 MessageDigest messageDigest = MessageDigest.getInstance("SHA-512");
708 // Hash the salted encryption password. Otherwise, any characters after the 32nd character in the password are ignored.
709 byte[] hashedEncryptionPasswordWithSaltByteArray = messageDigest.digest(encryptionPasswordWithSaltByteArray);
711 // Truncate the encryption password byte array to 256 bits (32 bytes).
712 byte[] truncatedHashedEncryptionPasswordWithSaltByteArray = Arrays.copyOf(hashedEncryptionPasswordWithSaltByteArray, 32);
714 // Create an AES secret key from the encryption password byte array.
715 SecretKeySpec secretKey = new SecretKeySpec(truncatedHashedEncryptionPasswordWithSaltByteArray, "AES");
717 // Generate a random 12 byte initialization vector. According to NIST, a 12 byte initialization vector is more secure than a 16 byte one.
718 byte[] initializationVector = new byte[12];
719 secureRandom.nextBytes(initializationVector);
721 // 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.
722 Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
724 // Set the GCM tag length to be 128 bits (the maximum) and apply the initialization vector.
725 GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, initializationVector);
727 // Initialize the cipher.
728 cipher.init(Cipher.ENCRYPT_MODE, secretKey, gcmParameterSpec);
730 // Add the salt and the initialization vector to the export file.
731 encryptedExportFileOutputStream.write(saltByteArray);
732 encryptedExportFileOutputStream.write(initializationVector);
734 // Create a cipher output stream.
735 CipherOutputStream cipherOutputStream = new CipherOutputStream(encryptedExportFileOutputStream, cipher);
737 // 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.
738 int numberOfBytesRead;
739 byte[] encryptedBytes = new byte[16];
741 // 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.
742 while ((numberOfBytesRead = unencryptedExportFileInputStream.read(encryptedBytes)) != -1) {
743 // Write the data to the cipher output stream.
744 cipherOutputStream.write(encryptedBytes, 0, numberOfBytesRead);
747 // Close the streams.
748 cipherOutputStream.flush();
749 cipherOutputStream.close();
750 encryptedExportFileOutputStream.close();
751 unencryptedExportFileInputStream.close();
753 // Wipe the encryption data from memory.
754 //noinspection UnusedAssignment
755 encryptionPasswordString = "";
756 Arrays.fill(saltByteArray, (byte) 0);
757 Arrays.fill(encryptionPasswordByteArray, (byte) 0);
758 Arrays.fill(encryptionPasswordWithSaltByteArray, (byte) 0);
759 Arrays.fill(hashedEncryptionPasswordWithSaltByteArray, (byte) 0);
760 Arrays.fill(truncatedHashedEncryptionPasswordWithSaltByteArray, (byte) 0);
761 Arrays.fill(initializationVector, (byte) 0);
762 Arrays.fill(encryptedBytes, (byte) 0);
764 // Delete the temporary unencrypted export file.
765 //noinspection ResultOfMethodCallIgnored
766 temporaryUnencryptedExportFile.delete();
767 } catch (Exception exception) {
768 exportStatus = exception.toString();
771 // Show a disposition snackbar.
772 if (exportStatus.equals(ImportExportDatabaseHelper.EXPORT_SUCCESSFUL)) {
773 Snackbar.make(fileNameEditText, getString(R.string.export_successful), Snackbar.LENGTH_SHORT).show();
775 Snackbar.make(fileNameEditText, getString(R.string.export_failed) + " " + exportStatus, Snackbar.LENGTH_INDEFINITE).show();
779 case OPENPGP_ENCRYPTION:
780 // Create an unencrypted export in the private location.
781 importExportDatabaseHelper.exportUnencrypted(temporaryUnencryptedExportFile, this);
783 // Create an encryption intent for OpenKeychain.
784 Intent openKeychainEncryptIntent = new Intent("org.sufficientlysecure.keychain.action.ENCRYPT_DATA");
786 // Include the temporary unencrypted export file URI.
787 openKeychainEncryptIntent.setData(FileProvider.getUriForFile(this, getString(R.string.file_provider), temporaryUnencryptedExportFile));
789 // Allow OpenKeychain to read the file URI.
790 openKeychainEncryptIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
792 // Send the intent to the OpenKeychain package.
793 openKeychainEncryptIntent.setPackage("org.sufficientlysecure.keychain");
796 startActivityForResult(openKeychainEncryptIntent, OPENPGP_EXPORT_RESULT_CODE);
800 // Add the file to the list of recent files. This doesn't currently work, but maybe it will someday.
801 MediaScannerConnection.scanFile(this, new String[] {exportFileString}, new String[] {"application/x-sqlite3"}, null);
804 private void importSettings() {
805 // Get a handle for the views.
806 Spinner encryptionSpinner = findViewById(R.id.encryption_spinner);
807 EditText fileNameEditText = findViewById(R.id.file_name_edittext);
809 // Instantiate the import export database helper.
810 ImportExportDatabaseHelper importExportDatabaseHelper = new ImportExportDatabaseHelper();
812 // Get the import file.
813 File importFile = new File(fileNameEditText.getText().toString());
815 // Initialize the import status string
816 String importStatus = "";
818 // Import according to the encryption type.
819 switch (encryptionSpinner.getSelectedItemPosition()) {
821 // Import the unencrypted file.
822 importStatus = importExportDatabaseHelper.importUnencrypted(importFile, this);
825 case PASSWORD_ENCRYPTION:
826 // Use a private temporary import location.
827 File temporaryUnencryptedImportFile = new File(getApplicationContext().getCacheDir() + "/" + getString(R.string.settings_pbs));
830 // Create an encrypted import file input stream.
831 FileInputStream encryptedImportFileInputStream = new FileInputStream(importFile);
833 // Delete the temporary import file if it exists.
834 if (temporaryUnencryptedImportFile.exists()) {
835 //noinspection ResultOfMethodCallIgnored
836 temporaryUnencryptedImportFile.delete();
839 // Create an unencrypted import file output stream.
840 FileOutputStream unencryptedImportFileOutputStream = new FileOutputStream(temporaryUnencryptedImportFile);
842 // Get a handle for the encryption password EditText.
843 EditText encryptionPasswordEditText = findViewById(R.id.password_encryption_edittext);
845 // Get the encryption password.
846 String encryptionPasswordString = encryptionPasswordEditText.getText().toString();
848 // Get the salt from the beginning of the import file.
849 byte[] saltByteArray = new byte[32];
850 //noinspection ResultOfMethodCallIgnored
851 encryptedImportFileInputStream.read(saltByteArray);
853 // Get the initialization vector from the import file.
854 byte[] initializationVector = new byte[12];
855 //noinspection ResultOfMethodCallIgnored
856 encryptedImportFileInputStream.read(initializationVector);
858 // Convert the encryption password to a byte array.
859 byte[] encryptionPasswordByteArray = encryptionPasswordString.getBytes(StandardCharsets.UTF_8);
861 // Append the salt to the encryption password byte array. This protects against rainbow table attacks.
862 byte[] encryptionPasswordWithSaltByteArray = new byte[encryptionPasswordByteArray.length + saltByteArray.length];
863 System.arraycopy(encryptionPasswordByteArray, 0, encryptionPasswordWithSaltByteArray, 0, encryptionPasswordByteArray.length);
864 System.arraycopy(saltByteArray, 0, encryptionPasswordWithSaltByteArray, encryptionPasswordByteArray.length, saltByteArray.length);
866 // Get a SHA-512 message digest.
867 MessageDigest messageDigest = MessageDigest.getInstance("SHA-512");
869 // Hash the salted encryption password. Otherwise, any characters after the 32nd character in the password are ignored.
870 byte[] hashedEncryptionPasswordWithSaltByteArray = messageDigest.digest(encryptionPasswordWithSaltByteArray);
872 // Truncate the encryption password byte array to 256 bits (32 bytes).
873 byte[] truncatedHashedEncryptionPasswordWithSaltByteArray = Arrays.copyOf(hashedEncryptionPasswordWithSaltByteArray, 32);
875 // Create an AES secret key from the encryption password byte array.
876 SecretKeySpec secretKey = new SecretKeySpec(truncatedHashedEncryptionPasswordWithSaltByteArray, "AES");
878 // 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.
879 Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
881 // Set the GCM tag length to be 128 bits (the maximum) and apply the initialization vector.
882 GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, initializationVector);
884 // Initialize the cipher.
885 cipher.init(Cipher.DECRYPT_MODE, secretKey, gcmParameterSpec);
887 // Create a cipher input stream.
888 CipherInputStream cipherInputStream = new CipherInputStream(encryptedImportFileInputStream, cipher);
890 // 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.
891 int numberOfBytesRead;
892 byte[] decryptedBytes = new byte[16];
894 // 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.
895 while ((numberOfBytesRead = cipherInputStream.read(decryptedBytes)) != -1) {
896 // Write the data to the unencrypted import file output stream.
897 unencryptedImportFileOutputStream.write(decryptedBytes, 0, numberOfBytesRead);
900 // Close the streams.
901 unencryptedImportFileOutputStream.flush();
902 unencryptedImportFileOutputStream.close();
903 cipherInputStream.close();
904 encryptedImportFileInputStream.close();
906 // Wipe the encryption data from memory.
907 //noinspection UnusedAssignment
908 encryptionPasswordString = "";
909 Arrays.fill(saltByteArray, (byte) 0);
910 Arrays.fill(initializationVector, (byte) 0);
911 Arrays.fill(encryptionPasswordByteArray, (byte) 0);
912 Arrays.fill(encryptionPasswordWithSaltByteArray, (byte) 0);
913 Arrays.fill(hashedEncryptionPasswordWithSaltByteArray, (byte) 0);
914 Arrays.fill(truncatedHashedEncryptionPasswordWithSaltByteArray, (byte) 0);
915 Arrays.fill(decryptedBytes, (byte) 0);
917 // Import the unencrypted database from the private location.
918 importStatus = importExportDatabaseHelper.importUnencrypted(temporaryUnencryptedImportFile, this);
920 // Delete the temporary unencrypted import file.
921 //noinspection ResultOfMethodCallIgnored
922 temporaryUnencryptedImportFile.delete();
923 } catch (Exception exception) {
924 importStatus = exception.toString();
928 case OPENPGP_ENCRYPTION:
930 // Create an decryption intent for OpenKeychain.
931 Intent openKeychainDecryptIntent = new Intent("org.sufficientlysecure.keychain.action.DECRYPT_DATA");
933 // Include the URI to be decrypted.
934 openKeychainDecryptIntent.setData(FileProvider.getUriForFile(this, getString(R.string.file_provider), importFile));
936 // Allow OpenKeychain to read the file URI.
937 openKeychainDecryptIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
939 // Send the intent to the OpenKeychain package.
940 openKeychainDecryptIntent.setPackage("org.sufficientlysecure.keychain");
943 startActivity(openKeychainDecryptIntent);
944 } catch (IllegalArgumentException exception) { // The file import location is not valid.
945 // Display a snack bar with the import error.
946 Snackbar.make(fileNameEditText, getString(R.string.import_failed) + " " + exception.toString(), Snackbar.LENGTH_INDEFINITE).show();
951 // Respond to the import disposition.
952 if (importStatus.equals(ImportExportDatabaseHelper.IMPORT_SUCCESSFUL)) { // The import was successful.
953 // Create an intent to restart Privacy Browser.
954 Intent restartIntent = getParentActivityIntent();
956 // Assert that the intent is not null to remove the lint error below.
957 assert restartIntent != null;
959 // `Intent.FLAG_ACTIVITY_CLEAR_TASK` removes all activities from the stack. It requires `Intent.FLAG_ACTIVITY_NEW_TASK`.
960 restartIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
962 // Create a restart handler.
963 Handler restartHandler = new Handler();
965 // Create a restart runnable.
966 Runnable restartRunnable = () -> {
967 // Restart Privacy Browser.
968 startActivity(restartIntent);
970 // Kill this instance of Privacy Browser. Otherwise, the app exhibits sporadic behavior after the restart.
974 // Restart Privacy Browser after 100 milliseconds to allow enough time for the preferences to be saved.
975 restartHandler.postDelayed(restartRunnable, 100);
977 } else if (!(encryptionSpinner.getSelectedItemPosition() == OPENPGP_ENCRYPTION)){ // The import was not successful.
978 // Display a snack bar with the import error.
979 Snackbar.make(fileNameEditText, getString(R.string.import_failed) + " " + importStatus, Snackbar.LENGTH_INDEFINITE).show();