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.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.ImportExportDatabaseHelper;
65 import java.io.FileInputStream;
66 import java.io.FileOutputStream;
67 import java.nio.charset.StandardCharsets;
68 import java.security.MessageDigest;
69 import java.security.SecureRandom;
70 import java.util.Arrays;
72 import javax.crypto.Cipher;
73 import javax.crypto.CipherInputStream;
74 import javax.crypto.CipherOutputStream;
75 import javax.crypto.spec.GCMParameterSpec;
76 import javax.crypto.spec.SecretKeySpec;
78 public class ImportExportActivity extends AppCompatActivity implements StoragePermissionDialog.StoragePermissionDialogListener {
79 // Create the encryption constants.
80 private final int NO_ENCRYPTION = 0;
81 private final int PASSWORD_ENCRYPTION = 1;
82 private final int OPENPGP_ENCRYPTION = 2;
84 // Create the activity result constants.
85 private final int BROWSE_RESULT_CODE = 0;
86 private final int OPENPGP_EXPORT_RESULT_CODE = 1;
88 // `openKeychainInstalled` is accessed from an inner class.
89 private boolean openKeychainInstalled;
92 public void onCreate(Bundle savedInstanceState) {
93 // Get a handle for the shared preferences.
94 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
96 // Get the theme and screenshot preferences.
97 boolean darkTheme = sharedPreferences.getBoolean("dark_theme", false);
98 boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
100 // Disable screenshots if not allowed.
101 if (!allowScreenshots) {
102 getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
105 // Set the activity theme.
107 setTheme(R.style.PrivacyBrowserDark_SecondaryActivity);
109 setTheme(R.style.PrivacyBrowserLight_SecondaryActivity);
112 // Run the default commands.
113 super.onCreate(savedInstanceState);
115 // Set the content view.
116 setContentView(R.layout.import_export_coordinatorlayout);
118 // Use the `SupportActionBar` from `android.support.v7.app.ActionBar` until the minimum API is >= 21.
119 Toolbar toolbar = findViewById(R.id.import_export_toolbar);
120 setSupportActionBar(toolbar);
122 // Get a handle for the action bar.
123 ActionBar actionBar = getSupportActionBar();
125 // Remove the incorrect lint warning that the action bar might be null.
126 assert actionBar != null;
128 // Display the home arrow on the support action bar.
129 actionBar.setDisplayHomeAsUpEnabled(true);
131 // Find out if we are running KitKat
132 boolean runningKitKat = (Build.VERSION.SDK_INT == 19);
134 // Find out if OpenKeychain is installed.
136 openKeychainInstalled = !getPackageManager().getPackageInfo("org.sufficientlysecure.keychain", 0).versionName.isEmpty();
137 } catch (PackageManager.NameNotFoundException exception) {
138 openKeychainInstalled = false;
141 // Get handles for the views that need to be modified.
142 Spinner encryptionSpinner = findViewById(R.id.encryption_spinner);
143 TextInputLayout passwordEncryptionTextInputLayout = findViewById(R.id.password_encryption_textinputlayout);
144 EditText encryptionPasswordEditText = findViewById(R.id.password_encryption_edittext);
145 TextView kitKatPasswordEncryptionTextView = findViewById(R.id.kitkat_password_encryption_textview);
146 TextView openKeychainRequiredTextView = findViewById(R.id.openkeychain_required_textview);
147 CardView fileLocationCardView = findViewById(R.id.file_location_cardview);
148 RadioButton importRadioButton = findViewById(R.id.import_radiobutton);
149 RadioButton exportRadioButton = findViewById(R.id.export_radiobutton);
150 LinearLayout fileNameLinearLayout = findViewById(R.id.file_name_linearlayout);
151 EditText fileNameEditText = findViewById(R.id.file_name_edittext);
152 TextView openKeychainImportInstructionsTextView = findViewById(R.id.openkeychain_import_instructions_textview);
153 Button importExportButton = findViewById(R.id.import_export_button);
154 TextView storagePermissionTextView = findViewById(R.id.import_export_storage_permission_textview);
156 // Create an array adapter for the spinner.
157 ArrayAdapter<CharSequence> encryptionArrayAdapter = ArrayAdapter.createFromResource(this, R.array.encryption_type, R.layout.spinner_item);
159 // Set the drop down view resource on the spinner.
160 encryptionArrayAdapter.setDropDownViewResource(R.layout.spinner_dropdown_items);
162 // Set the array adapter for the spinner.
163 encryptionSpinner.setAdapter(encryptionArrayAdapter);
165 // Initially hide the unneeded views.
166 passwordEncryptionTextInputLayout.setVisibility(View.GONE);
167 kitKatPasswordEncryptionTextView.setVisibility(View.GONE);
168 openKeychainRequiredTextView.setVisibility(View.GONE);
169 fileNameLinearLayout.setVisibility(View.GONE);
170 openKeychainImportInstructionsTextView.setVisibility(View.GONE);
171 importExportButton.setVisibility(View.GONE);
173 // Create strings for the default file paths.
174 String defaultFilePath;
175 String defaultPasswordEncryptionFilePath;
177 // Set the default file paths according to the storage permission status.
178 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // The storage permission has been granted.
179 // Set the default file paths to use the external public directory.
180 defaultFilePath = Environment.getExternalStorageDirectory() + "/" + getString(R.string.settings_pbs);
181 defaultPasswordEncryptionFilePath = defaultFilePath + ".aes";
182 } else { // The storage permission has not been granted.
183 // Set the default file paths to use the external private directory.
184 defaultFilePath = getApplicationContext().getExternalFilesDir(null) + "/" + getString(R.string.settings_pbs);
185 defaultPasswordEncryptionFilePath = defaultFilePath + ".aes";
188 // Set the default file path.
189 fileNameEditText.setText(defaultFilePath);
191 // Display the encryption information when the spinner changes.
192 encryptionSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
194 public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
197 // Hide the unneeded layout items.
198 passwordEncryptionTextInputLayout.setVisibility(View.GONE);
199 kitKatPasswordEncryptionTextView.setVisibility(View.GONE);
200 openKeychainRequiredTextView.setVisibility(View.GONE);
201 openKeychainImportInstructionsTextView.setVisibility(View.GONE);
203 // Show the file location card.
204 fileLocationCardView.setVisibility(View.VISIBLE);
206 // Show the file name linear layout if either import or export is checked.
207 if (importRadioButton.isChecked() || exportRadioButton.isChecked()) {
208 fileNameLinearLayout.setVisibility(View.VISIBLE);
211 // Reset the text of the import button, which may have been changed to `Decrypt`.
212 if (importRadioButton.isChecked()) {
213 importExportButton.setText(R.string.import_button);
216 // Reset the default file path.
217 fileNameEditText.setText(defaultFilePath);
219 // Enable the import/export button if a file name exists.
220 importExportButton.setEnabled(!fileNameEditText.getText().toString().isEmpty());
223 case PASSWORD_ENCRYPTION:
225 // Show the KitKat password encryption message.
226 kitKatPasswordEncryptionTextView.setVisibility(View.VISIBLE);
228 // Hide the OpenPGP required text view and the file location card.
229 openKeychainRequiredTextView.setVisibility(View.GONE);
230 fileLocationCardView.setVisibility(View.GONE);
232 // Hide the OpenPGP layout items.
233 openKeychainRequiredTextView.setVisibility(View.GONE);
234 openKeychainImportInstructionsTextView.setVisibility(View.GONE);
236 // Show the password encryption layout items.
237 passwordEncryptionTextInputLayout.setVisibility(View.VISIBLE);
239 // Show the file location card.
240 fileLocationCardView.setVisibility(View.VISIBLE);
242 // Show the file name linear layout if either import or export is checked.
243 if (importRadioButton.isChecked() || exportRadioButton.isChecked()) {
244 fileNameLinearLayout.setVisibility(View.VISIBLE);
247 // Reset the text of the import button, which may have been changed to `Decrypt`.
248 if (importRadioButton.isChecked()) {
249 importExportButton.setText(R.string.import_button);
252 // Update the default file path.
253 fileNameEditText.setText(defaultPasswordEncryptionFilePath);
255 // Enable the import/export button if a password exists.
256 importExportButton.setEnabled(!encryptionPasswordEditText.getText().toString().isEmpty());
260 case OPENPGP_ENCRYPTION:
261 // Hide the password encryption layout items.
262 passwordEncryptionTextInputLayout.setVisibility(View.GONE);
263 kitKatPasswordEncryptionTextView.setVisibility(View.GONE);
265 // Updated items based on the installation status of OpenKeychain.
266 if (openKeychainInstalled) { // OpenKeychain is installed.
267 // Remove the default file path.
268 fileNameEditText.setText("");
270 // Show the file location card.
271 fileLocationCardView.setVisibility(View.VISIBLE);
273 if (importRadioButton.isChecked()) {
274 // Show the file name linear layout and the OpenKeychain import instructions.
275 fileNameLinearLayout.setVisibility(View.VISIBLE);
276 openKeychainImportInstructionsTextView.setVisibility(View.VISIBLE);
278 // Set the text of the import button to be `Decrypt`.
279 importExportButton.setText(R.string.decrypt);
281 // Disable the import/export button. The user needs to select a file to import first.
282 importExportButton.setEnabled(false);
283 } else if (exportRadioButton.isChecked()) {
284 // Hide the file name linear layout and the OpenKeychain import instructions.
285 fileNameLinearLayout.setVisibility(View.GONE);
286 openKeychainImportInstructionsTextView.setVisibility(View.GONE);
288 // Enable the import/export button.
289 importExportButton.setEnabled(true);
291 } else { // OpenKeychain is not installed.
292 // Show the OpenPGP required layout item.
293 openKeychainRequiredTextView.setVisibility(View.VISIBLE);
295 // Hide the file location card.
296 fileLocationCardView.setVisibility(View.GONE);
303 public void onNothingSelected(AdapterView<?> parent) {
308 // Update the status of the import/export button when the password changes.
309 encryptionPasswordEditText.addTextChangedListener(new TextWatcher() {
311 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
316 public void onTextChanged(CharSequence s, int start, int before, int count) {
321 public void afterTextChanged(Editable s) {
322 // Enable the import/export button if a file name and password exists.
323 importExportButton.setEnabled(!fileNameEditText.getText().toString().isEmpty() && !encryptionPasswordEditText.getText().toString().isEmpty());
327 // Update the status of the import/export button when the file name EditText changes.
328 fileNameEditText.addTextChangedListener(new TextWatcher() {
330 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
335 public void onTextChanged(CharSequence s, int start, int before, int count) {
340 public void afterTextChanged(Editable s) {
341 // Adjust the export button according to the encryption spinner position.
342 switch (encryptionSpinner.getSelectedItemPosition()) {
344 // Enable the import/export button if a file name exists.
345 importExportButton.setEnabled(!fileNameEditText.getText().toString().isEmpty());
348 case PASSWORD_ENCRYPTION:
349 // Enable the import/export button if a file name and password exists.
350 importExportButton.setEnabled(!fileNameEditText.getText().toString().isEmpty() && !encryptionPasswordEditText.getText().toString().isEmpty());
353 case OPENPGP_ENCRYPTION:
354 // Enable the import/export button if OpenKeychain is installed and a file name exists.
355 importExportButton.setEnabled(openKeychainInstalled && !fileNameEditText.getText().toString().isEmpty());
361 // Hide the storage permissions text view on API < 23 as permissions on older devices are automatically granted.
362 if (Build.VERSION.SDK_INT < 23) {
363 storagePermissionTextView.setVisibility(View.GONE);
367 public void onClickRadioButton(View view) {
368 // Get handles for the views.
369 Spinner encryptionSpinner = findViewById(R.id.encryption_spinner);
370 LinearLayout fileNameLinearLayout = findViewById(R.id.file_name_linearlayout);
371 EditText fileNameEditText = findViewById(R.id.file_name_edittext);
372 TextView openKeychainImportInstructionTextView = findViewById(R.id.openkeychain_import_instructions_textview);
373 Button importExportButton = findViewById(R.id.import_export_button);
375 // Check to see if import or export was selected.
376 switch (view.getId()) {
377 case R.id.import_radiobutton:
378 // Check to see if OpenPGP encryption is selected.
379 if (encryptionSpinner.getSelectedItemPosition() == OPENPGP_ENCRYPTION) { // OpenPGP encryption selected.
380 // Show the OpenKeychain import instructions.
381 openKeychainImportInstructionTextView.setVisibility(View.VISIBLE);
383 // Set the text on the import/export button to be `Decrypt`.
384 importExportButton.setText(R.string.decrypt);
386 // Enable the decrypt button if there is a file name.
387 importExportButton.setEnabled(!fileNameEditText.getText().toString().isEmpty());
388 } else { // OpenPGP encryption not selected.
389 // Hide the OpenKeychain import instructions.
390 openKeychainImportInstructionTextView.setVisibility(View.GONE);
392 // Set the text on the import/export button to be `Import`.
393 importExportButton.setText(R.string.import_button);
396 // Display the file name views.
397 fileNameLinearLayout.setVisibility(View.VISIBLE);
398 importExportButton.setVisibility(View.VISIBLE);
401 case R.id.export_radiobutton:
402 // Hide the OpenKeychain import instructions.
403 openKeychainImportInstructionTextView.setVisibility(View.GONE);
405 // Set the text on the import/export button to be `Export`.
406 importExportButton.setText(R.string.export);
408 // Show the import/export button.
409 importExportButton.setVisibility(View.VISIBLE);
411 // Check to see if OpenPGP encryption is selected.
412 if (encryptionSpinner.getSelectedItemPosition() == OPENPGP_ENCRYPTION) { // OpenPGP encryption is selected.
413 // Hide the file name views.
414 fileNameLinearLayout.setVisibility(View.GONE);
416 // Enable the export button.
417 importExportButton.setEnabled(true);
418 } else { // OpenPGP encryption is not selected.
419 // Show the file name views.
420 fileNameLinearLayout.setVisibility(View.VISIBLE);
426 public void browse(View view) {
427 // Get a handle for the import radiobutton.
428 RadioButton importRadioButton = findViewById(R.id.import_radiobutton);
430 // Check to see if import or export is selected.
431 if (importRadioButton.isChecked()) { // Import is selected.
432 // Create the file picker intent.
433 Intent importBrowseIntent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
435 // Set the intent MIME type to include all files so that everything is visible.
436 importBrowseIntent.setType("*/*");
438 // Set the initial directory if the minimum API >= 26.
439 if (Build.VERSION.SDK_INT >= 26) {
440 importBrowseIntent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, Environment.getExternalStorageDirectory());
443 // Request a file that can be opened.
444 importBrowseIntent.addCategory(Intent.CATEGORY_OPENABLE);
446 // Launch the file picker.
447 startActivityForResult(importBrowseIntent, BROWSE_RESULT_CODE);
448 } else { // Export is selected
449 // Create the file picker intent.
450 Intent exportBrowseIntent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
452 // Set the intent MIME type to include all files so that everything is visible.
453 exportBrowseIntent.setType("*/*");
455 // Set the initial export file name.
456 exportBrowseIntent.putExtra(Intent.EXTRA_TITLE, getString(R.string.settings_pbs));
458 // Set the initial directory if the minimum API >= 26.
459 if (Build.VERSION.SDK_INT >= 26) {
460 exportBrowseIntent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, Environment.getExternalStorageDirectory());
463 // Request a file that can be opened.
464 exportBrowseIntent.addCategory(Intent.CATEGORY_OPENABLE);
466 // Launch the file picker.
467 startActivityForResult(exportBrowseIntent, BROWSE_RESULT_CODE);
471 public void importExport(View view) {
472 // Get a handle for the views.
473 Spinner encryptionSpinner = findViewById(R.id.encryption_spinner);
474 RadioButton importRadioButton = findViewById(R.id.import_radiobutton);
475 RadioButton exportRadioButton = findViewById(R.id.export_radiobutton);
477 // Check to see if the storage permission is needed.
478 if ((encryptionSpinner.getSelectedItemPosition() == OPENPGP_ENCRYPTION) && exportRadioButton.isChecked()) { // Permission not needed to export via OpenKeychain.
479 // Export the settings.
481 } else if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // The storage permission has been granted.
482 // Check to see if import or export is selected.
483 if (importRadioButton.isChecked()) { // Import is selected.
484 // Import the settings.
486 } else { // Export is selected.
487 // Export the settings.
490 } else { // The storage permission has not been granted.
491 // Get a handle for the file name EditText.
492 EditText fileNameEditText = findViewById(R.id.file_name_edittext);
494 // Get the file name string.
495 String fileNameString = fileNameEditText.getText().toString();
497 // Get the external private directory `File`.
498 File externalPrivateDirectoryFile = getExternalFilesDir(null);
500 // Remove the incorrect lint error below that the file might be null.
501 assert externalPrivateDirectoryFile != null;
503 // Get the external private directory string.
504 String externalPrivateDirectory = externalPrivateDirectoryFile.toString();
506 // Check to see if the file path is in the external private directory.
507 if (fileNameString.startsWith(externalPrivateDirectory)) { // The file path is in the external private directory.
508 // Check to see if import or export is selected.
509 if (importRadioButton.isChecked()) { // Import is selected.
510 // Import the settings.
512 } else { // Export is selected.
513 // Export the settings.
516 } else { // The file path is in a public directory.
517 // Check if the user has previously denied the storage permission.
518 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
519 // Instantiate the storage permission alert dialog.
520 DialogFragment storagePermissionDialogFragment = new StoragePermissionDialog();
522 // Show the storage permission alert dialog. The permission will be requested when the dialog is closed.
523 storagePermissionDialogFragment.show(getSupportFragmentManager(), getString(R.string.storage_permission));
524 } else { // Show the permission request directly.
525 // Request the storage permission. The export will be run when it finishes.
526 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
533 public void onCloseStoragePermissionDialog() {
534 // Request the write external storage permission. The import/export will be run when it finishes.
535 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
539 public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
540 // Get a handle for the import radiobutton.
541 RadioButton importRadioButton = findViewById(R.id.import_radiobutton);
543 // Check to see if the storage permission was granted. If the dialog was canceled the grant results will be empty.
544 if ((grantResults.length > 0) && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) { // The storage permission was granted.
545 // Run the import or export methods according to which radio button is selected.
546 if (importRadioButton.isChecked()) { // Import is selected.
547 // Import the settings.
549 } else { // Export is selected.
550 // Export the settings.
553 } else { // The storage permission was not granted.
554 // Display an error snackbar.
555 Snackbar.make(importRadioButton, getString(R.string.cannot_use_location), Snackbar.LENGTH_LONG).show();
560 public void onActivityResult(int requestCode, int resultCode, Intent data) {
561 switch (requestCode) {
562 case (BROWSE_RESULT_CODE):
563 // Don't do anything if the user pressed back from the file picker.
564 if (resultCode == Activity.RESULT_OK) {
565 // Get a handle for the file name edit text.
566 EditText fileNameEditText = findViewById(R.id.file_name_edittext);
568 // Get the file name URI.
569 Uri fileNameUri = data.getData();
571 // Remove the lint warning that the file name URI might be null.
572 assert fileNameUri != null;
574 // Get the raw file name path.
575 String rawFileNamePath = fileNameUri.getPath();
577 // Remove the incorrect lint warning that the file name path might be null.
578 assert rawFileNamePath != null;
580 // Check to see if the file name Path includes a valid storage location.
581 if (rawFileNamePath.contains(":")) { // The path is valid.
582 // Split the path into the initial content uri and the final path information.
583 String fileNameContentPath = rawFileNamePath.substring(0, rawFileNamePath.indexOf(":"));
584 String fileNameFinalPath = rawFileNamePath.substring(rawFileNamePath.indexOf(":") + 1);
586 // Create the file name path string.
589 // Construct the file name path.
590 switch (fileNameContentPath) {
591 // The documents home has a special content path.
592 case "/document/home":
593 fileNamePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS) + "/" + fileNameFinalPath;
596 // Everything else for the primary user should be in `/document/primary`.
597 case "/document/primary":
598 fileNamePath = Environment.getExternalStorageDirectory() + "/" + fileNameFinalPath;
601 // Just in case, catch everything else and place it in the external storage directory.
603 fileNamePath = Environment.getExternalStorageDirectory() + "/" + fileNameFinalPath;
607 // Set the file name path as the text of the file name EditText.
608 fileNameEditText.setText(fileNamePath);
609 } else { // The path is invalid.
610 Snackbar.make(fileNameEditText, rawFileNamePath + " " + getString(R.string.invalid_location), Snackbar.LENGTH_INDEFINITE).show();
615 case OPENPGP_EXPORT_RESULT_CODE:
616 // Get the temporary unencrypted export file.
617 File temporaryUnencryptedExportFile = new File(getApplicationContext().getCacheDir() + "/" + getString(R.string.settings_pbs));
619 // Delete the temporary unencrypted export file if it exists.
620 if (temporaryUnencryptedExportFile.exists()) {
621 //noinspection ResultOfMethodCallIgnored
622 temporaryUnencryptedExportFile.delete();
628 private void exportSettings() {
629 // Get a handle for the views.
630 Spinner encryptionSpinner = findViewById(R.id.encryption_spinner);
631 EditText fileNameEditText = findViewById(R.id.file_name_edittext);
633 // Instantiate the import export database helper.
634 ImportExportDatabaseHelper importExportDatabaseHelper = new ImportExportDatabaseHelper();
636 // Get the export file string.
637 String exportFileString = fileNameEditText.getText().toString();
639 // Get the export and temporary unencrypted export files.
640 File exportFile = new File(exportFileString);
641 File temporaryUnencryptedExportFile = new File(getApplicationContext().getCacheDir() + "/" + getString(R.string.settings_pbs));
643 // Create an export status string.
646 // Export according to the encryption type.
647 switch (encryptionSpinner.getSelectedItemPosition()) {
649 // Export the unencrypted file.
650 exportStatus = importExportDatabaseHelper.exportUnencrypted(exportFile, this);
652 // Show a disposition snackbar.
653 if (exportStatus.equals(ImportExportDatabaseHelper.EXPORT_SUCCESSFUL)) {
654 Snackbar.make(fileNameEditText, getString(R.string.export_successful), Snackbar.LENGTH_SHORT).show();
656 Snackbar.make(fileNameEditText, getString(R.string.export_failed) + " " + exportStatus, Snackbar.LENGTH_INDEFINITE).show();
660 case PASSWORD_ENCRYPTION:
661 // Create an unencrypted export in a private directory.
662 exportStatus = importExportDatabaseHelper.exportUnencrypted(temporaryUnencryptedExportFile, this);
665 // Create an unencrypted export file input stream.
666 FileInputStream unencryptedExportFileInputStream = new FileInputStream(temporaryUnencryptedExportFile);
668 // Delete the encrypted export file if it exists.
669 if (exportFile.exists()) {
670 //noinspection ResultOfMethodCallIgnored
674 // Create an encrypted export file output stream.
675 FileOutputStream encryptedExportFileOutputStream = new FileOutputStream(exportFile);
677 // Get a handle for the encryption password EditText.
678 EditText encryptionPasswordEditText = findViewById(R.id.password_encryption_edittext);
680 // Get the encryption password.
681 String encryptionPasswordString = encryptionPasswordEditText.getText().toString();
683 // Initialize a secure random number generator.
684 SecureRandom secureRandom = new SecureRandom();
686 // Get a 256 bit (32 byte) random salt.
687 byte[] saltByteArray = new byte[32];
688 secureRandom.nextBytes(saltByteArray);
690 // Convert the encryption password to a byte array.
691 byte[] encryptionPasswordByteArray = encryptionPasswordString.getBytes(StandardCharsets.UTF_8);
693 // Append the salt to the encryption password byte array. This protects against rainbow table attacks.
694 byte[] encryptionPasswordWithSaltByteArray = new byte[encryptionPasswordByteArray.length + saltByteArray.length];
695 System.arraycopy(encryptionPasswordByteArray, 0, encryptionPasswordWithSaltByteArray, 0, encryptionPasswordByteArray.length);
696 System.arraycopy(saltByteArray, 0, encryptionPasswordWithSaltByteArray, encryptionPasswordByteArray.length, saltByteArray.length);
698 // Get a SHA-512 message digest.
699 MessageDigest messageDigest = MessageDigest.getInstance("SHA-512");
701 // Hash the salted encryption password. Otherwise, any characters after the 32nd character in the password are ignored.
702 byte[] hashedEncryptionPasswordWithSaltByteArray = messageDigest.digest(encryptionPasswordWithSaltByteArray);
704 // Truncate the encryption password byte array to 256 bits (32 bytes).
705 byte[] truncatedHashedEncryptionPasswordWithSaltByteArray = Arrays.copyOf(hashedEncryptionPasswordWithSaltByteArray, 32);
707 // Create an AES secret key from the encryption password byte array.
708 SecretKeySpec secretKey = new SecretKeySpec(truncatedHashedEncryptionPasswordWithSaltByteArray, "AES");
710 // Generate a random 12 byte initialization vector. According to NIST, a 12 byte initialization vector is more secure than a 16 byte one.
711 byte[] initializationVector = new byte[12];
712 secureRandom.nextBytes(initializationVector);
714 // 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.
715 Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
717 // Set the GCM tag length to be 128 bits (the maximum) and apply the initialization vector.
718 GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, initializationVector);
720 // Initialize the cipher.
721 cipher.init(Cipher.ENCRYPT_MODE, secretKey, gcmParameterSpec);
723 // Add the salt and the initialization vector to the export file.
724 encryptedExportFileOutputStream.write(saltByteArray);
725 encryptedExportFileOutputStream.write(initializationVector);
727 // Create a cipher output stream.
728 CipherOutputStream cipherOutputStream = new CipherOutputStream(encryptedExportFileOutputStream, cipher);
730 // 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.
731 int numberOfBytesRead;
732 byte[] encryptedBytes = new byte[16];
734 // 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.
735 while ((numberOfBytesRead = unencryptedExportFileInputStream.read(encryptedBytes)) != -1) {
736 // Write the data to the cipher output stream.
737 cipherOutputStream.write(encryptedBytes, 0, numberOfBytesRead);
740 // Close the streams.
741 cipherOutputStream.flush();
742 cipherOutputStream.close();
743 encryptedExportFileOutputStream.close();
744 unencryptedExportFileInputStream.close();
746 // Wipe the encryption data from memory.
747 //noinspection UnusedAssignment
748 encryptionPasswordString = "";
749 Arrays.fill(saltByteArray, (byte) 0);
750 Arrays.fill(encryptionPasswordByteArray, (byte) 0);
751 Arrays.fill(encryptionPasswordWithSaltByteArray, (byte) 0);
752 Arrays.fill(hashedEncryptionPasswordWithSaltByteArray, (byte) 0);
753 Arrays.fill(truncatedHashedEncryptionPasswordWithSaltByteArray, (byte) 0);
754 Arrays.fill(initializationVector, (byte) 0);
755 Arrays.fill(encryptedBytes, (byte) 0);
757 // Delete the temporary unencrypted export file.
758 //noinspection ResultOfMethodCallIgnored
759 temporaryUnencryptedExportFile.delete();
760 } catch (Exception exception) {
761 exportStatus = exception.toString();
764 // Show a disposition snackbar.
765 if (exportStatus.equals(ImportExportDatabaseHelper.EXPORT_SUCCESSFUL)) {
766 Snackbar.make(fileNameEditText, getString(R.string.export_successful), Snackbar.LENGTH_SHORT).show();
768 Snackbar.make(fileNameEditText, getString(R.string.export_failed) + " " + exportStatus, Snackbar.LENGTH_INDEFINITE).show();
772 case OPENPGP_ENCRYPTION:
773 // Create an unencrypted export in the private location.
774 importExportDatabaseHelper.exportUnencrypted(temporaryUnencryptedExportFile, this);
776 // Create an encryption intent for OpenKeychain.
777 Intent openKeychainEncryptIntent = new Intent("org.sufficientlysecure.keychain.action.ENCRYPT_DATA");
779 // Include the temporary unencrypted export file URI.
780 openKeychainEncryptIntent.setData(FileProvider.getUriForFile(this, getString(R.string.file_provider), temporaryUnencryptedExportFile));
782 // Allow OpenKeychain to read the file URI.
783 openKeychainEncryptIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
785 // Send the intent to the OpenKeychain package.
786 openKeychainEncryptIntent.setPackage("org.sufficientlysecure.keychain");
789 startActivityForResult(openKeychainEncryptIntent, OPENPGP_EXPORT_RESULT_CODE);
793 // Add the file to the list of recent files. This doesn't currently work, but maybe it will someday.
794 MediaScannerConnection.scanFile(this, new String[] {exportFileString}, new String[] {"application/x-sqlite3"}, null);
797 private void importSettings() {
798 // Get a handle for the views.
799 Spinner encryptionSpinner = findViewById(R.id.encryption_spinner);
800 EditText fileNameEditText = findViewById(R.id.file_name_edittext);
802 // Instantiate the import export database helper.
803 ImportExportDatabaseHelper importExportDatabaseHelper = new ImportExportDatabaseHelper();
805 // Get the import file.
806 File importFile = new File(fileNameEditText.getText().toString());
808 // Initialize the import status string
809 String importStatus = "";
811 // Import according to the encryption type.
812 switch (encryptionSpinner.getSelectedItemPosition()) {
814 // Import the unencrypted file.
815 importStatus = importExportDatabaseHelper.importUnencrypted(importFile, this);
818 case PASSWORD_ENCRYPTION:
819 // Use a private temporary import location.
820 File temporaryUnencryptedImportFile = new File(getApplicationContext().getCacheDir() + "/" + getString(R.string.settings_pbs));
823 // Create an encrypted import file input stream.
824 FileInputStream encryptedImportFileInputStream = new FileInputStream(importFile);
826 // Delete the temporary import file if it exists.
827 if (temporaryUnencryptedImportFile.exists()) {
828 //noinspection ResultOfMethodCallIgnored
829 temporaryUnencryptedImportFile.delete();
832 // Create an unencrypted import file output stream.
833 FileOutputStream unencryptedImportFileOutputStream = new FileOutputStream(temporaryUnencryptedImportFile);
835 // Get a handle for the encryption password EditText.
836 EditText encryptionPasswordEditText = findViewById(R.id.password_encryption_edittext);
838 // Get the encryption password.
839 String encryptionPasswordString = encryptionPasswordEditText.getText().toString();
841 // Get the salt from the beginning of the import file.
842 byte[] saltByteArray = new byte[32];
843 //noinspection ResultOfMethodCallIgnored
844 encryptedImportFileInputStream.read(saltByteArray);
846 // Get the initialization vector from the import file.
847 byte[] initializationVector = new byte[12];
848 //noinspection ResultOfMethodCallIgnored
849 encryptedImportFileInputStream.read(initializationVector);
851 // Convert the encryption password to a byte array.
852 byte[] encryptionPasswordByteArray = encryptionPasswordString.getBytes(StandardCharsets.UTF_8);
854 // Append the salt to the encryption password byte array. This protects against rainbow table attacks.
855 byte[] encryptionPasswordWithSaltByteArray = new byte[encryptionPasswordByteArray.length + saltByteArray.length];
856 System.arraycopy(encryptionPasswordByteArray, 0, encryptionPasswordWithSaltByteArray, 0, encryptionPasswordByteArray.length);
857 System.arraycopy(saltByteArray, 0, encryptionPasswordWithSaltByteArray, encryptionPasswordByteArray.length, saltByteArray.length);
859 // Get a SHA-512 message digest.
860 MessageDigest messageDigest = MessageDigest.getInstance("SHA-512");
862 // Hash the salted encryption password. Otherwise, any characters after the 32nd character in the password are ignored.
863 byte[] hashedEncryptionPasswordWithSaltByteArray = messageDigest.digest(encryptionPasswordWithSaltByteArray);
865 // Truncate the encryption password byte array to 256 bits (32 bytes).
866 byte[] truncatedHashedEncryptionPasswordWithSaltByteArray = Arrays.copyOf(hashedEncryptionPasswordWithSaltByteArray, 32);
868 // Create an AES secret key from the encryption password byte array.
869 SecretKeySpec secretKey = new SecretKeySpec(truncatedHashedEncryptionPasswordWithSaltByteArray, "AES");
871 // 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.
872 Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
874 // Set the GCM tag length to be 128 bits (the maximum) and apply the initialization vector.
875 GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, initializationVector);
877 // Initialize the cipher.
878 cipher.init(Cipher.DECRYPT_MODE, secretKey, gcmParameterSpec);
880 // Create a cipher input stream.
881 CipherInputStream cipherInputStream = new CipherInputStream(encryptedImportFileInputStream, cipher);
883 // 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.
884 int numberOfBytesRead;
885 byte[] decryptedBytes = new byte[16];
887 // 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.
888 while ((numberOfBytesRead = cipherInputStream.read(decryptedBytes)) != -1) {
889 // Write the data to the unencrypted import file output stream.
890 unencryptedImportFileOutputStream.write(decryptedBytes, 0, numberOfBytesRead);
893 // Close the streams.
894 unencryptedImportFileOutputStream.flush();
895 unencryptedImportFileOutputStream.close();
896 cipherInputStream.close();
897 encryptedImportFileInputStream.close();
899 // Wipe the encryption data from memory.
900 //noinspection UnusedAssignment
901 encryptionPasswordString = "";
902 Arrays.fill(saltByteArray, (byte) 0);
903 Arrays.fill(initializationVector, (byte) 0);
904 Arrays.fill(encryptionPasswordByteArray, (byte) 0);
905 Arrays.fill(encryptionPasswordWithSaltByteArray, (byte) 0);
906 Arrays.fill(hashedEncryptionPasswordWithSaltByteArray, (byte) 0);
907 Arrays.fill(truncatedHashedEncryptionPasswordWithSaltByteArray, (byte) 0);
908 Arrays.fill(decryptedBytes, (byte) 0);
910 // Import the unencrypted database from the private location.
911 importStatus = importExportDatabaseHelper.importUnencrypted(temporaryUnencryptedImportFile, this);
913 // Delete the temporary unencrypted import file.
914 //noinspection ResultOfMethodCallIgnored
915 temporaryUnencryptedImportFile.delete();
916 } catch (Exception exception) {
917 importStatus = exception.toString();
921 case OPENPGP_ENCRYPTION:
923 // Create an decryption intent for OpenKeychain.
924 Intent openKeychainDecryptIntent = new Intent("org.sufficientlysecure.keychain.action.DECRYPT_DATA");
926 // Include the URI to be decrypted.
927 openKeychainDecryptIntent.setData(FileProvider.getUriForFile(this, getString(R.string.file_provider), importFile));
929 // Allow OpenKeychain to read the file URI.
930 openKeychainDecryptIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
932 // Send the intent to the OpenKeychain package.
933 openKeychainDecryptIntent.setPackage("org.sufficientlysecure.keychain");
936 startActivity(openKeychainDecryptIntent);
937 } catch (IllegalArgumentException exception) { // The file import location is not valid.
938 // Display a snack bar with the import error.
939 Snackbar.make(fileNameEditText, getString(R.string.import_failed) + " " + exception.toString(), Snackbar.LENGTH_INDEFINITE).show();
944 // Respond to the import disposition.
945 if (importStatus.equals(ImportExportDatabaseHelper.IMPORT_SUCCESSFUL)) { // The import was successful.
946 // Create an intent to restart Privacy Browser.
947 Intent restartIntent = getParentActivityIntent();
949 // Assert that the intent is not null to remove the lint error below.
950 assert restartIntent != null;
952 // `Intent.FLAG_ACTIVITY_CLEAR_TASK` removes all activities from the stack. It requires `Intent.FLAG_ACTIVITY_NEW_TASK`.
953 restartIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
956 startActivity(restartIntent);
957 } else if (!(encryptionSpinner.getSelectedItemPosition() == OPENPGP_ENCRYPTION)){ // The import was not successful.
958 // Display a snack bar with the import error.
959 Snackbar.make(fileNameEditText, getString(R.string.import_failed) + " " + importStatus, Snackbar.LENGTH_INDEFINITE).show();