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.pm.PackageManager;
26 import android.media.MediaScannerConnection;
27 import android.net.Uri;
28 import android.os.Build;
29 import android.os.Bundle;
30 import android.os.Environment;
31 import android.provider.DocumentsContract;
32 import android.text.Editable;
33 import android.text.TextWatcher;
34 import android.view.View;
35 import android.view.WindowManager;
36 import android.widget.AdapterView;
37 import android.widget.ArrayAdapter;
38 import android.widget.Button;
39 import android.widget.EditText;
40 import android.widget.LinearLayout;
41 import android.widget.RadioButton;
42 import android.widget.Spinner;
43 import android.widget.TextView;
45 import androidx.annotation.NonNull;
46 import androidx.appcompat.app.ActionBar;
47 import androidx.appcompat.app.AppCompatActivity;
48 import androidx.appcompat.widget.Toolbar;
49 import androidx.cardview.widget.CardView;
50 import androidx.core.app.ActivityCompat;
51 import androidx.core.content.ContextCompat;
52 import androidx.core.content.FileProvider;
53 import androidx.fragment.app.DialogFragment;
55 import com.google.android.material.snackbar.Snackbar;
56 import com.google.android.material.textfield.TextInputLayout;
58 import com.stoutner.privacybrowser.R;
59 import com.stoutner.privacybrowser.dialogs.StoragePermissionDialog;
60 import com.stoutner.privacybrowser.helpers.ImportExportDatabaseHelper;
63 import java.io.FileInputStream;
64 import java.io.FileOutputStream;
65 import java.nio.charset.StandardCharsets;
66 import java.security.MessageDigest;
67 import java.security.SecureRandom;
68 import java.util.Arrays;
70 import javax.crypto.Cipher;
71 import javax.crypto.CipherInputStream;
72 import javax.crypto.CipherOutputStream;
73 import javax.crypto.spec.GCMParameterSpec;
74 import javax.crypto.spec.SecretKeySpec;
76 public class ImportExportActivity extends AppCompatActivity implements StoragePermissionDialog.StoragePermissionDialogListener {
77 // Create the encryption constants.
78 private final int NO_ENCRYPTION = 0;
79 private final int PASSWORD_ENCRYPTION = 1;
80 private final int OPENPGP_ENCRYPTION = 2;
82 // Create the activity result constants.
83 private final int BROWSE_RESULT_CODE = 0;
84 private final int OPENPGP_EXPORT_RESULT_CODE = 1;
86 // `openKeychainInstalled` is accessed from an inner class.
87 private boolean openKeychainInstalled;
90 public void onCreate(Bundle savedInstanceState) {
91 // Disable screenshots if not allowed.
92 if (!MainWebViewActivity.allowScreenshots) {
93 getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
96 // Set the activity theme.
97 if (MainWebViewActivity.darkTheme) {
98 setTheme(R.style.PrivacyBrowserDark_SecondaryActivity);
100 setTheme(R.style.PrivacyBrowserLight_SecondaryActivity);
103 // Run the default commands.
104 super.onCreate(savedInstanceState);
106 // Set the content view.
107 setContentView(R.layout.import_export_coordinatorlayout);
109 // Use the `SupportActionBar` from `android.support.v7.app.ActionBar` until the minimum API is >= 21.
110 Toolbar toolbar = findViewById(R.id.import_export_toolbar);
111 setSupportActionBar(toolbar);
113 // Get a handle for the action bar.
114 ActionBar actionBar = getSupportActionBar();
116 // Remove the incorrect lint warning that the action bar might be null.
117 assert actionBar != null;
119 // Display the home arrow on the support action bar.
120 actionBar.setDisplayHomeAsUpEnabled(true);
122 // Find out if we are running KitKat
123 boolean runningKitKat = (Build.VERSION.SDK_INT == 19);
125 // Find out if OpenKeychain is installed.
127 openKeychainInstalled = !getPackageManager().getPackageInfo("org.sufficientlysecure.keychain", 0).versionName.isEmpty();
128 } catch (PackageManager.NameNotFoundException exception) {
129 openKeychainInstalled = false;
132 // Get handles for the views that need to be modified.
133 Spinner encryptionSpinner = findViewById(R.id.encryption_spinner);
134 TextInputLayout passwordEncryptionTextInputLayout = findViewById(R.id.password_encryption_textinputlayout);
135 EditText encryptionPasswordEditText = findViewById(R.id.password_encryption_edittext);
136 TextView kitKatPasswordEncryptionTextView = findViewById(R.id.kitkat_password_encryption_textview);
137 TextView openKeychainRequiredTextView = findViewById(R.id.openkeychain_required_textview);
138 CardView fileLocationCardView = findViewById(R.id.file_location_cardview);
139 RadioButton importRadioButton = findViewById(R.id.import_radiobutton);
140 RadioButton exportRadioButton = findViewById(R.id.export_radiobutton);
141 LinearLayout fileNameLinearLayout = findViewById(R.id.file_name_linearlayout);
142 EditText fileNameEditText = findViewById(R.id.file_name_edittext);
143 TextView openKeychainImportInstructionsTextView = findViewById(R.id.openkeychain_import_instructions_textview);
144 Button importExportButton = findViewById(R.id.import_export_button);
145 TextView storagePermissionTextView = findViewById(R.id.import_export_storage_permission_textview);
147 // Create an array adapter for the spinner.
148 ArrayAdapter<CharSequence> encryptionArrayAdapter = ArrayAdapter.createFromResource(this, R.array.encryption_type, R.layout.spinner_item);
150 // Set the drop down view resource on the spinner.
151 encryptionArrayAdapter.setDropDownViewResource(R.layout.spinner_dropdown_items);
153 // Set the array adapter for the spinner.
154 encryptionSpinner.setAdapter(encryptionArrayAdapter);
156 // Initially hide the unneeded views.
157 passwordEncryptionTextInputLayout.setVisibility(View.GONE);
158 kitKatPasswordEncryptionTextView.setVisibility(View.GONE);
159 openKeychainRequiredTextView.setVisibility(View.GONE);
160 fileNameLinearLayout.setVisibility(View.GONE);
161 openKeychainImportInstructionsTextView.setVisibility(View.GONE);
162 importExportButton.setVisibility(View.GONE);
164 // Create strings for the default file paths.
165 String defaultFilePath;
166 String defaultPasswordEncryptionFilePath;
168 // Set the default file paths according to the storage permission status.
169 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // The storage permission has been granted.
170 // Set the default file paths to use the external public directory.
171 defaultFilePath = Environment.getExternalStorageDirectory() + "/" + getString(R.string.settings_pbs);
172 defaultPasswordEncryptionFilePath = defaultFilePath + ".aes";
173 } else { // The storage permission has not been granted.
174 // Set the default file paths to use the external private directory.
175 defaultFilePath = getApplicationContext().getExternalFilesDir(null) + "/" + getString(R.string.settings_pbs);
176 defaultPasswordEncryptionFilePath = defaultFilePath + ".aes";
179 // Set the default file path.
180 fileNameEditText.setText(defaultFilePath);
182 // Display the encryption information when the spinner changes.
183 encryptionSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
185 public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
188 // Hide the unneeded layout items.
189 passwordEncryptionTextInputLayout.setVisibility(View.GONE);
190 kitKatPasswordEncryptionTextView.setVisibility(View.GONE);
191 openKeychainRequiredTextView.setVisibility(View.GONE);
192 openKeychainImportInstructionsTextView.setVisibility(View.GONE);
194 // Show the file location card.
195 fileLocationCardView.setVisibility(View.VISIBLE);
197 // Show the file name linear layout if either import or export is checked.
198 if (importRadioButton.isChecked() || exportRadioButton.isChecked()) {
199 fileNameLinearLayout.setVisibility(View.VISIBLE);
202 // Reset the text of the import button, which may have been changed to `Decrypt`.
203 if (importRadioButton.isChecked()) {
204 importExportButton.setText(R.string.import_button);
207 // Reset the default file path.
208 fileNameEditText.setText(defaultFilePath);
210 // Enable the import/export button if a file name exists.
211 importExportButton.setEnabled(!fileNameEditText.getText().toString().isEmpty());
214 case PASSWORD_ENCRYPTION:
216 // Show the KitKat password encryption message.
217 kitKatPasswordEncryptionTextView.setVisibility(View.VISIBLE);
219 // Hide the OpenPGP required text view and the file location card.
220 openKeychainRequiredTextView.setVisibility(View.GONE);
221 fileLocationCardView.setVisibility(View.GONE);
223 // Hide the OpenPGP layout items.
224 openKeychainRequiredTextView.setVisibility(View.GONE);
225 openKeychainImportInstructionsTextView.setVisibility(View.GONE);
227 // Show the password encryption layout items.
228 passwordEncryptionTextInputLayout.setVisibility(View.VISIBLE);
230 // Show the file location card.
231 fileLocationCardView.setVisibility(View.VISIBLE);
233 // Show the file name linear layout if either import or export is checked.
234 if (importRadioButton.isChecked() || exportRadioButton.isChecked()) {
235 fileNameLinearLayout.setVisibility(View.VISIBLE);
238 // Reset the text of the import button, which may have been changed to `Decrypt`.
239 if (importRadioButton.isChecked()) {
240 importExportButton.setText(R.string.import_button);
243 // Update the default file path.
244 fileNameEditText.setText(defaultPasswordEncryptionFilePath);
246 // Enable the import/export button if a password exists.
247 importExportButton.setEnabled(!encryptionPasswordEditText.getText().toString().isEmpty());
251 case OPENPGP_ENCRYPTION:
252 // Hide the password encryption layout items.
253 passwordEncryptionTextInputLayout.setVisibility(View.GONE);
254 kitKatPasswordEncryptionTextView.setVisibility(View.GONE);
256 // Updated items based on the installation status of OpenKeychain.
257 if (openKeychainInstalled) { // OpenKeychain is installed.
258 // Remove the default file path.
259 fileNameEditText.setText("");
261 // Show the file location card.
262 fileLocationCardView.setVisibility(View.VISIBLE);
264 if (importRadioButton.isChecked()) {
265 // Show the file name linear layout and the OpenKeychain import instructions.
266 fileNameLinearLayout.setVisibility(View.VISIBLE);
267 openKeychainImportInstructionsTextView.setVisibility(View.VISIBLE);
269 // Set the text of the import button to be `Decrypt`.
270 importExportButton.setText(R.string.decrypt);
272 // Disable the import/export button. The user needs to select a file to import first.
273 importExportButton.setEnabled(false);
274 } else if (exportRadioButton.isChecked()) {
275 // Hide the file name linear layout and the OpenKeychain import instructions.
276 fileNameLinearLayout.setVisibility(View.GONE);
277 openKeychainImportInstructionsTextView.setVisibility(View.GONE);
279 // Enable the import/export button.
280 importExportButton.setEnabled(true);
282 } else { // OpenKeychain is not installed.
283 // Show the OpenPGP required layout item.
284 openKeychainRequiredTextView.setVisibility(View.VISIBLE);
286 // Hide the file location card.
287 fileLocationCardView.setVisibility(View.GONE);
294 public void onNothingSelected(AdapterView<?> parent) {
299 // Update the status of the import/export button when the password changes.
300 encryptionPasswordEditText.addTextChangedListener(new TextWatcher() {
302 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
307 public void onTextChanged(CharSequence s, int start, int before, int count) {
312 public void afterTextChanged(Editable s) {
313 // Enable the import/export button if a file name and password exists.
314 importExportButton.setEnabled(!fileNameEditText.getText().toString().isEmpty() && !encryptionPasswordEditText.getText().toString().isEmpty());
318 // Update the status of the import/export button when the file name EditText changes.
319 fileNameEditText.addTextChangedListener(new TextWatcher() {
321 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
326 public void onTextChanged(CharSequence s, int start, int before, int count) {
331 public void afterTextChanged(Editable s) {
332 // Adjust the export button according to the encryption spinner position.
333 switch (encryptionSpinner.getSelectedItemPosition()) {
335 // Enable the import/export button if a file name exists.
336 importExportButton.setEnabled(!fileNameEditText.getText().toString().isEmpty());
339 case PASSWORD_ENCRYPTION:
340 // Enable the import/export button if a file name and password exists.
341 importExportButton.setEnabled(!fileNameEditText.getText().toString().isEmpty() && !encryptionPasswordEditText.getText().toString().isEmpty());
344 case OPENPGP_ENCRYPTION:
345 // Enable the import/export button if OpenKeychain is installed and a file name exists.
346 importExportButton.setEnabled(openKeychainInstalled && !fileNameEditText.getText().toString().isEmpty());
352 // Hide the storage permissions text view on API < 23 as permissions on older devices are automatically granted.
353 if (Build.VERSION.SDK_INT < 23) {
354 storagePermissionTextView.setVisibility(View.GONE);
358 public void onClickRadioButton(View view) {
359 // Get handles for the views.
360 Spinner encryptionSpinner = findViewById(R.id.encryption_spinner);
361 LinearLayout fileNameLinearLayout = findViewById(R.id.file_name_linearlayout);
362 EditText fileNameEditText = findViewById(R.id.file_name_edittext);
363 TextView openKeychainImportInstructionTextView = findViewById(R.id.openkeychain_import_instructions_textview);
364 Button importExportButton = findViewById(R.id.import_export_button);
366 // Check to see if import or export was selected.
367 switch (view.getId()) {
368 case R.id.import_radiobutton:
369 // Check to see if OpenPGP encryption is selected.
370 if (encryptionSpinner.getSelectedItemPosition() == OPENPGP_ENCRYPTION) { // OpenPGP encryption selected.
371 // Show the OpenKeychain import instructions.
372 openKeychainImportInstructionTextView.setVisibility(View.VISIBLE);
374 // Set the text on the import/export button to be `Decrypt`.
375 importExportButton.setText(R.string.decrypt);
377 // Enable the decrypt button if there is a file name.
378 importExportButton.setEnabled(!fileNameEditText.getText().toString().isEmpty());
379 } else { // OpenPGP encryption not selected.
380 // Hide the OpenKeychain import instructions.
381 openKeychainImportInstructionTextView.setVisibility(View.GONE);
383 // Set the text on the import/export button to be `Import`.
384 importExportButton.setText(R.string.import_button);
387 // Display the file name views.
388 fileNameLinearLayout.setVisibility(View.VISIBLE);
389 importExportButton.setVisibility(View.VISIBLE);
392 case R.id.export_radiobutton:
393 // Hide the OpenKeychain import instructions.
394 openKeychainImportInstructionTextView.setVisibility(View.GONE);
396 // Set the text on the import/export button to be `Export`.
397 importExportButton.setText(R.string.export);
399 // Show the import/export button.
400 importExportButton.setVisibility(View.VISIBLE);
402 // Check to see if OpenPGP encryption is selected.
403 if (encryptionSpinner.getSelectedItemPosition() == OPENPGP_ENCRYPTION) { // OpenPGP encryption is selected.
404 // Hide the file name views.
405 fileNameLinearLayout.setVisibility(View.GONE);
407 // Enable the export button.
408 importExportButton.setEnabled(true);
409 } else { // OpenPGP encryption is not selected.
410 // Show the file name views.
411 fileNameLinearLayout.setVisibility(View.VISIBLE);
417 public void browse(View view) {
418 // Get a handle for the import radiobutton.
419 RadioButton importRadioButton = findViewById(R.id.import_radiobutton);
421 // Check to see if import or export is selected.
422 if (importRadioButton.isChecked()) { // Import is selected.
423 // Create the file picker intent.
424 Intent importBrowseIntent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
426 // Set the intent MIME type to include all files so that everything is visible.
427 importBrowseIntent.setType("*/*");
429 // Set the initial directory if the minimum API >= 26.
430 if (Build.VERSION.SDK_INT >= 26) {
431 importBrowseIntent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, Environment.getExternalStorageDirectory());
434 // Request a file that can be opened.
435 importBrowseIntent.addCategory(Intent.CATEGORY_OPENABLE);
437 // Launch the file picker.
438 startActivityForResult(importBrowseIntent, BROWSE_RESULT_CODE);
439 } else { // Export is selected
440 // Create the file picker intent.
441 Intent exportBrowseIntent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
443 // Set the intent MIME type to include all files so that everything is visible.
444 exportBrowseIntent.setType("*/*");
446 // Set the initial export file name.
447 exportBrowseIntent.putExtra(Intent.EXTRA_TITLE, getString(R.string.settings_pbs));
449 // Set the initial directory if the minimum API >= 26.
450 if (Build.VERSION.SDK_INT >= 26) {
451 exportBrowseIntent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, Environment.getExternalStorageDirectory());
454 // Request a file that can be opened.
455 exportBrowseIntent.addCategory(Intent.CATEGORY_OPENABLE);
457 // Launch the file picker.
458 startActivityForResult(exportBrowseIntent, BROWSE_RESULT_CODE);
462 public void importExport(View view) {
463 // Get a handle for the views.
464 Spinner encryptionSpinner = findViewById(R.id.encryption_spinner);
465 RadioButton importRadioButton = findViewById(R.id.import_radiobutton);
466 RadioButton exportRadioButton = findViewById(R.id.export_radiobutton);
468 // Check to see if the storage permission is needed.
469 if ((encryptionSpinner.getSelectedItemPosition() == OPENPGP_ENCRYPTION) && exportRadioButton.isChecked()) { // Permission not needed to export via OpenKeychain.
470 // Export the settings.
472 } else if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // The storage permission has been granted.
473 // Check to see if import or export is selected.
474 if (importRadioButton.isChecked()) { // Import is selected.
475 // Import the settings.
477 } else { // Export is selected.
478 // Export the settings.
481 } else { // The storage permission has not been granted.
482 // Get a handle for the file name EditText.
483 EditText fileNameEditText = findViewById(R.id.file_name_edittext);
485 // Get the file name string.
486 String fileNameString = fileNameEditText.getText().toString();
488 // Get the external private directory `File`.
489 File externalPrivateDirectoryFile = getExternalFilesDir(null);
491 // Remove the incorrect lint error below that the file might be null.
492 assert externalPrivateDirectoryFile != null;
494 // Get the external private directory string.
495 String externalPrivateDirectory = externalPrivateDirectoryFile.toString();
497 // Check to see if the file path is in the external private directory.
498 if (fileNameString.startsWith(externalPrivateDirectory)) { // The file path is in the external private directory.
499 // Check to see if import or export is selected.
500 if (importRadioButton.isChecked()) { // Import is selected.
501 // Import the settings.
503 } else { // Export is selected.
504 // Export the settings.
507 } else { // The file path is in a public directory.
508 // Check if the user has previously denied the storage permission.
509 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
510 // Instantiate the storage permission alert dialog.
511 DialogFragment storagePermissionDialogFragment = new StoragePermissionDialog();
513 // Show the storage permission alert dialog. The permission will be requested when the dialog is closed.
514 storagePermissionDialogFragment.show(getSupportFragmentManager(), getString(R.string.storage_permission));
515 } else { // Show the permission request directly.
516 // Request the storage permission. The export will be run when it finishes.
517 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
524 public void onCloseStoragePermissionDialog() {
525 // Request the write external storage permission. The import/export will be run when it finishes.
526 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
530 public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
531 // Get a handle for the import radiobutton.
532 RadioButton importRadioButton = findViewById(R.id.import_radiobutton);
534 // Check to see if the storage permission was granted. If the dialog was canceled the grant results will be empty.
535 if ((grantResults.length > 0) && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) { // The storage permission was granted.
536 // Run the import or export methods according to which radio button is selected.
537 if (importRadioButton.isChecked()) { // Import is selected.
538 // Import the settings.
540 } else { // Export is selected.
541 // Export the settings.
544 } else { // The storage permission was not granted.
545 // Display an error snackbar.
546 Snackbar.make(importRadioButton, getString(R.string.cannot_use_location), Snackbar.LENGTH_LONG).show();
551 public void onActivityResult(int requestCode, int resultCode, Intent data) {
552 switch (requestCode) {
553 case (BROWSE_RESULT_CODE):
554 // Don't do anything if the user pressed back from the file picker.
555 if (resultCode == Activity.RESULT_OK) {
556 // Get a handle for the file name edit text.
557 EditText fileNameEditText = findViewById(R.id.file_name_edittext);
559 // Get the file name URI.
560 Uri fileNameUri = data.getData();
562 // Remove the lint warning that the file name URI might be null.
563 assert fileNameUri != null;
565 // Get the raw file name path.
566 String rawFileNamePath = fileNameUri.getPath();
568 // Remove the incorrect lint warning that the file name path might be null.
569 assert rawFileNamePath != null;
571 // Check to see if the file name Path includes a valid storage location.
572 if (rawFileNamePath.contains(":")) { // The path is valid.
573 // Split the path into the initial content uri and the final path information.
574 String fileNameContentPath = rawFileNamePath.substring(0, rawFileNamePath.indexOf(":"));
575 String fileNameFinalPath = rawFileNamePath.substring(rawFileNamePath.indexOf(":") + 1);
577 // Create the file name path string.
580 // Construct the file name path.
581 switch (fileNameContentPath) {
582 // The documents home has a special content path.
583 case "/document/home":
584 fileNamePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS) + "/" + fileNameFinalPath;
587 // Everything else for the primary user should be in `/document/primary`.
588 case "/document/primary":
589 fileNamePath = Environment.getExternalStorageDirectory() + "/" + fileNameFinalPath;
592 // Just in case, catch everything else and place it in the external storage directory.
594 fileNamePath = Environment.getExternalStorageDirectory() + "/" + fileNameFinalPath;
598 // Set the file name path as the text of the file name EditText.
599 fileNameEditText.setText(fileNamePath);
600 } else { // The path is invalid.
601 Snackbar.make(fileNameEditText, rawFileNamePath + " " + getString(R.string.invalid_location), Snackbar.LENGTH_INDEFINITE).show();
606 case OPENPGP_EXPORT_RESULT_CODE:
607 // Get the temporary unencrypted export file.
608 File temporaryUnencryptedExportFile = new File(getApplicationContext().getCacheDir() + "/" + getString(R.string.settings_pbs));
610 // Delete the temporary unencrypted export file if it exists.
611 if (temporaryUnencryptedExportFile.exists()) {
612 //noinspection ResultOfMethodCallIgnored
613 temporaryUnencryptedExportFile.delete();
619 private void exportSettings() {
620 // Get a handle for the views.
621 Spinner encryptionSpinner = findViewById(R.id.encryption_spinner);
622 EditText fileNameEditText = findViewById(R.id.file_name_edittext);
624 // Instantiate the import export database helper.
625 ImportExportDatabaseHelper importExportDatabaseHelper = new ImportExportDatabaseHelper();
627 // Get the export file string.
628 String exportFileString = fileNameEditText.getText().toString();
630 // Get the export and temporary unencrypted export files.
631 File exportFile = new File(exportFileString);
632 File temporaryUnencryptedExportFile = new File(getApplicationContext().getCacheDir() + "/" + getString(R.string.settings_pbs));
634 // Create an export status string.
637 // Export according to the encryption type.
638 switch (encryptionSpinner.getSelectedItemPosition()) {
640 // Export the unencrypted file.
641 exportStatus = importExportDatabaseHelper.exportUnencrypted(exportFile, this);
643 // Show a disposition snackbar.
644 if (exportStatus.equals(ImportExportDatabaseHelper.EXPORT_SUCCESSFUL)) {
645 Snackbar.make(fileNameEditText, getString(R.string.export_successful), Snackbar.LENGTH_SHORT).show();
647 Snackbar.make(fileNameEditText, getString(R.string.export_failed) + " " + exportStatus, Snackbar.LENGTH_INDEFINITE).show();
651 case PASSWORD_ENCRYPTION:
652 // Create an unencrypted export in a private directory.
653 exportStatus = importExportDatabaseHelper.exportUnencrypted(temporaryUnencryptedExportFile, this);
656 // Create an unencrypted export file input stream.
657 FileInputStream unencryptedExportFileInputStream = new FileInputStream(temporaryUnencryptedExportFile);
659 // Delete the encrypted export file if it exists.
660 if (exportFile.exists()) {
661 //noinspection ResultOfMethodCallIgnored
665 // Create an encrypted export file output stream.
666 FileOutputStream encryptedExportFileOutputStream = new FileOutputStream(exportFile);
668 // Get a handle for the encryption password EditText.
669 EditText encryptionPasswordEditText = findViewById(R.id.password_encryption_edittext);
671 // Get the encryption password.
672 String encryptionPasswordString = encryptionPasswordEditText.getText().toString();
674 // Initialize a secure random number generator.
675 SecureRandom secureRandom = new SecureRandom();
677 // Get a 256 bit (32 byte) random salt.
678 byte[] saltByteArray = new byte[32];
679 secureRandom.nextBytes(saltByteArray);
681 // Convert the encryption password to a byte array.
682 byte[] encryptionPasswordByteArray = encryptionPasswordString.getBytes(StandardCharsets.UTF_8);
684 // Append the salt to the encryption password byte array. This protects against rainbow table attacks.
685 byte[] encryptionPasswordWithSaltByteArray = new byte[encryptionPasswordByteArray.length + saltByteArray.length];
686 System.arraycopy(encryptionPasswordByteArray, 0, encryptionPasswordWithSaltByteArray, 0, encryptionPasswordByteArray.length);
687 System.arraycopy(saltByteArray, 0, encryptionPasswordWithSaltByteArray, encryptionPasswordByteArray.length, saltByteArray.length);
689 // Get a SHA-512 message digest.
690 MessageDigest messageDigest = MessageDigest.getInstance("SHA-512");
692 // Hash the salted encryption password. Otherwise, any characters after the 32nd character in the password are ignored.
693 byte[] hashedEncryptionPasswordWithSaltByteArray = messageDigest.digest(encryptionPasswordWithSaltByteArray);
695 // Truncate the encryption password byte array to 256 bits (32 bytes).
696 byte[] truncatedHashedEncryptionPasswordWithSaltByteArray = Arrays.copyOf(hashedEncryptionPasswordWithSaltByteArray, 32);
698 // Create an AES secret key from the encryption password byte array.
699 SecretKeySpec secretKey = new SecretKeySpec(truncatedHashedEncryptionPasswordWithSaltByteArray, "AES");
701 // Generate a random 12 byte initialization vector. According to NIST, a 12 byte initialization vector is more secure than a 16 byte one.
702 byte[] initializationVector = new byte[12];
703 secureRandom.nextBytes(initializationVector);
705 // 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.
706 Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
708 // Set the GCM tag length to be 128 bits (the maximum) and apply the initialization vector.
709 GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, initializationVector);
711 // Initialize the cipher.
712 cipher.init(Cipher.ENCRYPT_MODE, secretKey, gcmParameterSpec);
714 // Add the salt and the initialization vector to the export file.
715 encryptedExportFileOutputStream.write(saltByteArray);
716 encryptedExportFileOutputStream.write(initializationVector);
718 // Create a cipher output stream.
719 CipherOutputStream cipherOutputStream = new CipherOutputStream(encryptedExportFileOutputStream, cipher);
721 // 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.
722 int numberOfBytesRead;
723 byte[] encryptedBytes = new byte[16];
725 // 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.
726 while ((numberOfBytesRead = unencryptedExportFileInputStream.read(encryptedBytes)) != -1) {
727 // Write the data to the cipher output stream.
728 cipherOutputStream.write(encryptedBytes, 0, numberOfBytesRead);
731 // Close the streams.
732 cipherOutputStream.flush();
733 cipherOutputStream.close();
734 encryptedExportFileOutputStream.close();
735 unencryptedExportFileInputStream.close();
737 // Wipe the encryption data from memory.
738 //noinspection UnusedAssignment
739 encryptionPasswordString = "";
740 Arrays.fill(saltByteArray, (byte) 0);
741 Arrays.fill(encryptionPasswordByteArray, (byte) 0);
742 Arrays.fill(encryptionPasswordWithSaltByteArray, (byte) 0);
743 Arrays.fill(hashedEncryptionPasswordWithSaltByteArray, (byte) 0);
744 Arrays.fill(truncatedHashedEncryptionPasswordWithSaltByteArray, (byte) 0);
745 Arrays.fill(initializationVector, (byte) 0);
746 Arrays.fill(encryptedBytes, (byte) 0);
748 // Delete the temporary unencrypted export file.
749 //noinspection ResultOfMethodCallIgnored
750 temporaryUnencryptedExportFile.delete();
751 } catch (Exception exception) {
752 exportStatus = exception.toString();
755 // Show a disposition snackbar.
756 if (exportStatus.equals(ImportExportDatabaseHelper.EXPORT_SUCCESSFUL)) {
757 Snackbar.make(fileNameEditText, getString(R.string.export_successful), Snackbar.LENGTH_SHORT).show();
759 Snackbar.make(fileNameEditText, getString(R.string.export_failed) + " " + exportStatus, Snackbar.LENGTH_INDEFINITE).show();
763 case OPENPGP_ENCRYPTION:
764 // Create an unencrypted export in the private location.
765 importExportDatabaseHelper.exportUnencrypted(temporaryUnencryptedExportFile, this);
767 // Create an encryption intent for OpenKeychain.
768 Intent openKeychainEncryptIntent = new Intent("org.sufficientlysecure.keychain.action.ENCRYPT_DATA");
770 // Include the temporary unencrypted export file URI.
771 openKeychainEncryptIntent.setData(FileProvider.getUriForFile(this, getString(R.string.file_provider), temporaryUnencryptedExportFile));
773 // Allow OpenKeychain to read the file URI.
774 openKeychainEncryptIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
776 // Send the intent to the OpenKeychain package.
777 openKeychainEncryptIntent.setPackage("org.sufficientlysecure.keychain");
780 startActivityForResult(openKeychainEncryptIntent, OPENPGP_EXPORT_RESULT_CODE);
784 // Add the file to the list of recent files. This doesn't currently work, but maybe it will someday.
785 MediaScannerConnection.scanFile(this, new String[] {exportFileString}, new String[] {"application/x-sqlite3"}, null);
788 private void importSettings() {
789 // Get a handle for the views.
790 Spinner encryptionSpinner = findViewById(R.id.encryption_spinner);
791 EditText fileNameEditText = findViewById(R.id.file_name_edittext);
793 // Instantiate the import export database helper.
794 ImportExportDatabaseHelper importExportDatabaseHelper = new ImportExportDatabaseHelper();
796 // Get the import file.
797 File importFile = new File(fileNameEditText.getText().toString());
799 // Initialize the import status string
800 String importStatus = "";
802 // Import according to the encryption type.
803 switch (encryptionSpinner.getSelectedItemPosition()) {
805 // Import the unencrypted file.
806 importStatus = importExportDatabaseHelper.importUnencrypted(importFile, this);
809 case PASSWORD_ENCRYPTION:
810 // Use a private temporary import location.
811 File temporaryUnencryptedImportFile = new File(getApplicationContext().getCacheDir() + "/" + getString(R.string.settings_pbs));
814 // Create an encrypted import file input stream.
815 FileInputStream encryptedImportFileInputStream = new FileInputStream(importFile);
817 // Delete the temporary import file if it exists.
818 if (temporaryUnencryptedImportFile.exists()) {
819 //noinspection ResultOfMethodCallIgnored
820 temporaryUnencryptedImportFile.delete();
823 // Create an unencrypted import file output stream.
824 FileOutputStream unencryptedImportFileOutputStream = new FileOutputStream(temporaryUnencryptedImportFile);
826 // Get a handle for the encryption password EditText.
827 EditText encryptionPasswordEditText = findViewById(R.id.password_encryption_edittext);
829 // Get the encryption password.
830 String encryptionPasswordString = encryptionPasswordEditText.getText().toString();
832 // Get the salt from the beginning of the import file.
833 byte[] saltByteArray = new byte[32];
834 //noinspection ResultOfMethodCallIgnored
835 encryptedImportFileInputStream.read(saltByteArray);
837 // Get the initialization vector from the import file.
838 byte[] initializationVector = new byte[12];
839 //noinspection ResultOfMethodCallIgnored
840 encryptedImportFileInputStream.read(initializationVector);
842 // Convert the encryption password to a byte array.
843 byte[] encryptionPasswordByteArray = encryptionPasswordString.getBytes(StandardCharsets.UTF_8);
845 // Append the salt to the encryption password byte array. This protects against rainbow table attacks.
846 byte[] encryptionPasswordWithSaltByteArray = new byte[encryptionPasswordByteArray.length + saltByteArray.length];
847 System.arraycopy(encryptionPasswordByteArray, 0, encryptionPasswordWithSaltByteArray, 0, encryptionPasswordByteArray.length);
848 System.arraycopy(saltByteArray, 0, encryptionPasswordWithSaltByteArray, encryptionPasswordByteArray.length, saltByteArray.length);
850 // Get a SHA-512 message digest.
851 MessageDigest messageDigest = MessageDigest.getInstance("SHA-512");
853 // Hash the salted encryption password. Otherwise, any characters after the 32nd character in the password are ignored.
854 byte[] hashedEncryptionPasswordWithSaltByteArray = messageDigest.digest(encryptionPasswordWithSaltByteArray);
856 // Truncate the encryption password byte array to 256 bits (32 bytes).
857 byte[] truncatedHashedEncryptionPasswordWithSaltByteArray = Arrays.copyOf(hashedEncryptionPasswordWithSaltByteArray, 32);
859 // Create an AES secret key from the encryption password byte array.
860 SecretKeySpec secretKey = new SecretKeySpec(truncatedHashedEncryptionPasswordWithSaltByteArray, "AES");
862 // 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.
863 Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
865 // Set the GCM tag length to be 128 bits (the maximum) and apply the initialization vector.
866 GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, initializationVector);
868 // Initialize the cipher.
869 cipher.init(Cipher.DECRYPT_MODE, secretKey, gcmParameterSpec);
871 // Create a cipher input stream.
872 CipherInputStream cipherInputStream = new CipherInputStream(encryptedImportFileInputStream, cipher);
874 // 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.
875 int numberOfBytesRead;
876 byte[] decryptedBytes = new byte[16];
878 // 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.
879 while ((numberOfBytesRead = cipherInputStream.read(decryptedBytes)) != -1) {
880 // Write the data to the unencrypted import file output stream.
881 unencryptedImportFileOutputStream.write(decryptedBytes, 0, numberOfBytesRead);
884 // Close the streams.
885 unencryptedImportFileOutputStream.flush();
886 unencryptedImportFileOutputStream.close();
887 cipherInputStream.close();
888 encryptedImportFileInputStream.close();
890 // Wipe the encryption data from memory.
891 //noinspection UnusedAssignment
892 encryptionPasswordString = "";
893 Arrays.fill(saltByteArray, (byte) 0);
894 Arrays.fill(initializationVector, (byte) 0);
895 Arrays.fill(encryptionPasswordByteArray, (byte) 0);
896 Arrays.fill(encryptionPasswordWithSaltByteArray, (byte) 0);
897 Arrays.fill(hashedEncryptionPasswordWithSaltByteArray, (byte) 0);
898 Arrays.fill(truncatedHashedEncryptionPasswordWithSaltByteArray, (byte) 0);
899 Arrays.fill(decryptedBytes, (byte) 0);
901 // Import the unencrypted database from the private location.
902 importStatus = importExportDatabaseHelper.importUnencrypted(temporaryUnencryptedImportFile, this);
904 // Delete the temporary unencrypted import file.
905 //noinspection ResultOfMethodCallIgnored
906 temporaryUnencryptedImportFile.delete();
907 } catch (Exception exception) {
908 importStatus = exception.toString();
912 case OPENPGP_ENCRYPTION:
914 // Create an decryption intent for OpenKeychain.
915 Intent openKeychainDecryptIntent = new Intent("org.sufficientlysecure.keychain.action.DECRYPT_DATA");
917 // Include the URI to be decrypted.
918 openKeychainDecryptIntent.setData(FileProvider.getUriForFile(this, getString(R.string.file_provider), importFile));
920 // Allow OpenKeychain to read the file URI.
921 openKeychainDecryptIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
923 // Send the intent to the OpenKeychain package.
924 openKeychainDecryptIntent.setPackage("org.sufficientlysecure.keychain");
927 startActivity(openKeychainDecryptIntent);
928 } catch (IllegalArgumentException exception) { // The file import location is not valid.
929 // Display a snack bar with the import error.
930 Snackbar.make(fileNameEditText, getString(R.string.import_failed) + " " + exception.toString(), Snackbar.LENGTH_INDEFINITE).show();
935 // Respond to the import disposition.
936 if (importStatus.equals(ImportExportDatabaseHelper.IMPORT_SUCCESSFUL)) { // The import was successful.
937 // Create an intent to restart Privacy Browser.
938 Intent restartIntent = getParentActivityIntent();
940 // Assert that the intent is not null to remove the lint error below.
941 assert restartIntent != null;
943 // `Intent.FLAG_ACTIVITY_CLEAR_TASK` removes all activities from the stack. It requires `Intent.FLAG_ACTIVITY_NEW_TASK`.
944 restartIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
947 startActivity(restartIntent);
948 } else if (!(encryptionSpinner.getSelectedItemPosition() == OPENPGP_ENCRYPTION)){ // The import was not successful.
949 // Display a snack bar with the import error.
950 Snackbar.make(fileNameEditText, getString(R.string.import_failed) + " " + importStatus, Snackbar.LENGTH_INDEFINITE).show();