From d044daeedd9ae42e72ce3d3b2ed191778b173943 Mon Sep 17 00:00:00 2001 From: Vincent Breitmoser Date: Mon, 7 Jul 2014 17:32:16 +0200 Subject: get rid of AppMsg library --- .gitmodules | 3 - OpenKeychain/build.gradle | 1 - .../keychain/ui/EditKeyActivityOld.java | 744 --------------------- OpenKeychain/src/main/res/values/colors.xml | 1 + README.md | 4 - extern/AppMsg | 1 - settings.gradle | 1 - 7 files changed, 1 insertion(+), 754 deletions(-) delete mode 100644 OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivityOld.java delete mode 160000 extern/AppMsg diff --git a/.gitmodules b/.gitmodules index b7b0e1173..60afe0b9d 100644 --- a/.gitmodules +++ b/.gitmodules @@ -7,9 +7,6 @@ [submodule "extern/zxing-qr-code"] path = extern/zxing-qr-code url = https://github.com/open-keychain/zxing-qr-code.git -[submodule "extern/AppMsg"] - path = extern/AppMsg - url = https://github.com/open-keychain/Android-AppMsg.git [submodule "extern/spongycastle"] path = extern/spongycastle url = https://github.com/open-keychain/spongycastle.git diff --git a/OpenKeychain/build.gradle b/OpenKeychain/build.gradle index f419141b4..1136f669b 100644 --- a/OpenKeychain/build.gradle +++ b/OpenKeychain/build.gradle @@ -16,7 +16,6 @@ dependencies { compile project(':extern:spongycastle:pg') compile project(':extern:spongycastle:pkix') compile project(':extern:spongycastle:prov') - compile project(':extern:AppMsg:library') compile project(':extern:SuperToasts:supertoasts') compile project(':extern:minidns') compile project(':extern:KeybaseLib:Lib') diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivityOld.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivityOld.java deleted file mode 100644 index 51457cd45..000000000 --- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivityOld.java +++ /dev/null @@ -1,744 +0,0 @@ -/* - * Copyright (C) 2012-2014 Dominik Schürmann - * Copyright (C) 2010-2014 Thialfihar - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package org.sufficientlysecure.keychain.ui; - -import android.content.Context; -import android.content.DialogInterface; -import android.content.Intent; -import android.net.Uri; -import android.os.Bundle; -import android.os.Handler; -import android.os.Message; -import android.os.Messenger; -import android.support.v4.app.ActivityCompat; -import android.support.v7.app.ActionBarActivity; -import android.view.LayoutInflater; -import android.view.View; -import android.view.View.OnClickListener; -import android.view.ViewGroup; -import android.widget.Button; -import android.widget.CheckBox; -import android.widget.CompoundButton; -import android.widget.CompoundButton.OnCheckedChangeListener; -import android.widget.LinearLayout; -import android.widget.Toast; - -import com.devspark.appmsg.AppMsg; - -import org.sufficientlysecure.keychain.Constants; -import org.sufficientlysecure.keychain.R; -import org.sufficientlysecure.keychain.helper.ActionBarHelper; -import org.sufficientlysecure.keychain.helper.ExportHelper; -import org.sufficientlysecure.keychain.pgp.KeyRing; -import org.sufficientlysecure.keychain.pgp.UncachedSecretKey; -import org.sufficientlysecure.keychain.pgp.WrappedSecretKey; -import org.sufficientlysecure.keychain.pgp.WrappedSecretKeyRing; -import org.sufficientlysecure.keychain.pgp.exception.PgpGeneralException; -import org.sufficientlysecure.keychain.provider.KeychainContract.KeyRings; -import org.sufficientlysecure.keychain.provider.ProviderHelper; -import org.sufficientlysecure.keychain.service.PassphraseCacheService; -import org.sufficientlysecure.keychain.ui.dialog.CustomAlertDialogBuilder; -import org.sufficientlysecure.keychain.ui.dialog.PassphraseDialogFragment; -import org.sufficientlysecure.keychain.ui.dialog.SetPassphraseDialogFragment; -import org.sufficientlysecure.keychain.ui.widget.Editor; -import org.sufficientlysecure.keychain.ui.widget.Editor.EditorListener; -import org.sufficientlysecure.keychain.ui.widget.KeyEditor; -import org.sufficientlysecure.keychain.ui.widget.SectionView; -import org.sufficientlysecure.keychain.ui.widget.UserIdEditor; -import org.sufficientlysecure.keychain.util.Log; - -import java.util.ArrayList; -import java.util.Calendar; -import java.util.List; -import java.util.Vector; - -public class EditKeyActivityOld extends ActionBarActivity implements EditorListener { - - // Actions for internal use only: - public static final String ACTION_CREATE_KEY = Constants.INTENT_PREFIX + "CREATE_KEY"; - public static final String ACTION_EDIT_KEY = Constants.INTENT_PREFIX + "EDIT_KEY"; - - // possible extra keys - public static final String EXTRA_USER_IDS = "user_ids"; - public static final String EXTRA_NO_PASSPHRASE = "no_passphrase"; - public static final String EXTRA_GENERATE_DEFAULT_KEYS = "generate_default_keys"; - - // EDIT - private Uri mDataUri; - - private SectionView mUserIdsView; - private SectionView mKeysView; - - private String mCurrentPassphrase = null; - private String mNewPassphrase = null; - private String mSavedNewPassphrase = null; - private boolean mIsPassphraseSet; - private boolean mNeedsSaving; - private boolean mIsBrandNewKeyring = false; - - private Button mChangePassphrase; - - private CheckBox mNoPassphrase; - - Vector mUserIds; - Vector mKeys; - Vector mKeysUsages; - boolean mMasterCanSign = true; - - ExportHelper mExportHelper; - - public boolean needsSaving() { - mNeedsSaving = (mUserIdsView == null) ? false : mUserIdsView.needsSaving(); - mNeedsSaving |= (mKeysView == null) ? false : mKeysView.needsSaving(); - mNeedsSaving |= hasPassphraseChanged(); - mNeedsSaving |= mIsBrandNewKeyring; - return mNeedsSaving; - } - - - public void somethingChanged() { - ActivityCompat.invalidateOptionsMenu(this); - } - - public void onDeleted(Editor e, boolean wasNewItem) { - somethingChanged(); - } - - public void onEdited() { - somethingChanged(); - } - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - - mExportHelper = new ExportHelper(this); - - // Inflate a "Done"/"Cancel" custom action bar view - ActionBarHelper.setTwoButtonView(getSupportActionBar(), - R.string.btn_save, R.drawable.ic_action_save, - new View.OnClickListener() { - @Override - public void onClick(View v) { - // Save - saveClicked(); - } - }, R.string.menu_key_edit_cancel, R.drawable.ic_action_cancel, - new View.OnClickListener() { - @Override - public void onClick(View v) { - // Cancel - cancelClicked(); - } - } - ); - - mUserIds = new Vector(); - mKeys = new Vector(); - mKeysUsages = new Vector(); - - // Catch Intents opened from other apps - Intent intent = getIntent(); - String action = intent.getAction(); - if (ACTION_CREATE_KEY.equals(action)) { - handleActionCreateKey(intent); - } else if (ACTION_EDIT_KEY.equals(action)) { - handleActionEditKey(intent); - } - } - - /** - * Handle intent action to create new key - * - * @param intent - */ - private void handleActionCreateKey(Intent intent) { - Bundle extras = intent.getExtras(); - - mCurrentPassphrase = ""; - mIsBrandNewKeyring = true; - - if (extras != null) { - // if userId is given, prefill the fields - if (extras.containsKey(EXTRA_USER_IDS)) { - Log.d(Constants.TAG, "UserIds are given!"); - mUserIds.add(extras.getString(EXTRA_USER_IDS)); - } - - // if no passphrase is given - if (extras.containsKey(EXTRA_NO_PASSPHRASE)) { - boolean noPassphrase = extras.getBoolean(EXTRA_NO_PASSPHRASE); - if (noPassphrase) { - // check "no passphrase" checkbox and remove button - mNoPassphrase.setChecked(true); - mChangePassphrase.setVisibility(View.GONE); - } - } - - // generate key - if (extras.containsKey(EXTRA_GENERATE_DEFAULT_KEYS)) { - /* - boolean generateDefaultKeys = extras.getBoolean(EXTRA_GENERATE_DEFAULT_KEYS); - if (generateDefaultKeys) { - - // fill values for this action - Bundle data = new Bundle(); - data.putString(KeychainIntentService.GENERATE_KEY_SYMMETRIC_PASSPHRASE, - mCurrentPassphrase); - - serviceIntent.putExtra(KeychainIntentService.EXTRA_DATA, data); - - // Message is received after generating is done in KeychainIntentService - KeychainIntentServiceHandler saveHandler = new KeychainIntentServiceHandler( - this, getResources().getQuantityString(R.plurals.progress_generating, 1), - ProgressDialog.STYLE_HORIZONTAL, true, - - new DialogInterface.OnCancelListener() { - @Override - public void onCancel(DialogInterface dialog) { - // Stop key generation on cancel - stopService(serviceIntent); - EditKeyActivity.this.setResult(Activity.RESULT_CANCELED); - EditKeyActivity.this.finish(); - } - }) { - - @Override - public void handleMessage(Message message) { - // handle messages by standard KeychainIntentServiceHandler first - super.handleMessage(message); - - if (message.arg1 == KeychainIntentServiceHandler.MESSAGE_OKAY) { - // get new key from data bundle returned from service - Bundle data = message.getDataAsStringList(); - - ArrayList newKeys = - PgpConversionHelper.BytesToPGPSecretKeyList(data - .getByteArray(KeychainIntentService.RESULT_NEW_KEY)); - - ArrayList keyUsageFlags = data.getIntegerArrayList( - KeychainIntentService.RESULT_KEY_USAGES); - - if (newKeys.size() == keyUsageFlags.size()) { - for (int i = 0; i < newKeys.size(); ++i) { - mKeys.add(newKeys.get(i)); - mKeysUsages.add(keyUsageFlags.get(i)); - } - } - - buildLayout(true); - } - } - }; - - // Create a new Messenger for the communication back - Messenger messenger = new Messenger(saveHandler); - serviceIntent.putExtra(KeychainIntentService.EXTRA_MESSENGER, messenger); - - saveHandler.showProgressDialog(this); - - // start service with intent - startService(serviceIntent); - } - */ - } - } else { - buildLayout(false); - } - } - - /** - * Handle intent action to edit existing key - * - * @param intent - */ - private void handleActionEditKey(Intent intent) { - mDataUri = intent.getData(); - if (mDataUri == null) { - Log.e(Constants.TAG, "Intent data missing. Should be Uri of key!"); - finish(); - } else { - Log.d(Constants.TAG, "uri: " + mDataUri); - - try { - Uri secretUri = KeyRings.buildUnifiedKeyRingUri(mDataUri); - WrappedSecretKeyRing keyRing = new ProviderHelper(this).getWrappedSecretKeyRing(secretUri); - - mMasterCanSign = keyRing.getSubKey().canCertify(); - for (WrappedSecretKey key : keyRing.secretKeyIterator()) { - // Turn into uncached instance - mKeys.add(key.getUncached()); - mKeysUsages.add(key.getKeyUsage()); // get usage when view is created - } - - boolean isSet = false; - for (String userId : keyRing.getSubKey().getUserIds()) { - Log.d(Constants.TAG, "Added userId " + userId); - if (!isSet) { - isSet = true; - String[] parts = KeyRing.splitUserId(userId); - if (parts[0] != null) { - setTitle(parts[0]); - } - } - mUserIds.add(userId); - } - - buildLayout(false); - - mCurrentPassphrase = ""; - mIsPassphraseSet = keyRing.hasPassphrase(); - if (!mIsPassphraseSet) { - // check "no passphrase" checkbox and remove button - mNoPassphrase.setChecked(true); - mChangePassphrase.setVisibility(View.GONE); - } - - } catch (ProviderHelper.NotFoundException e) { - Log.e(Constants.TAG, "Keyring not found: " + e.getMessage(), e); - Toast.makeText(this, R.string.error_no_secret_key_found, Toast.LENGTH_SHORT).show(); - finish(); - } - - } - } - - /** - * Shows the dialog to set a new passphrase - */ - private void showSetPassphraseDialog() { - // Message is received after passphrase is cached - Handler returnHandler = new Handler() { - @Override - public void handleMessage(Message message) { - if (message.what == SetPassphraseDialogFragment.MESSAGE_OKAY) { - Bundle data = message.getData(); - - // set new returned passphrase! - mNewPassphrase = data - .getString(SetPassphraseDialogFragment.MESSAGE_NEW_PASSPHRASE); - - updatePassphraseButtonText(); - somethingChanged(); - } - } - }; - - // Create a new Messenger for the communication back - Messenger messenger = new Messenger(returnHandler); - - // set title based on isPassphraseSet() - int title; - if (isPassphraseSet()) { - title = R.string.title_change_passphrase; - } else { - title = R.string.title_set_passphrase; - } - - SetPassphraseDialogFragment setPassphraseDialog = SetPassphraseDialogFragment.newInstance( - messenger, null, title); - - setPassphraseDialog.show(getSupportFragmentManager(), "setPassphraseDialog"); - } - - /** - * Build layout based on mUserId, mKeys and mKeysUsages Vectors. It creates Views for every user - * id and key. - * - * @param newKeys - */ - private void buildLayout(boolean newKeys) { - setContentView(R.layout.edit_key_activity); - - // find views - mChangePassphrase = (Button) findViewById(R.id.edit_key_btn_change_passphrase); - mNoPassphrase = (CheckBox) findViewById(R.id.edit_key_no_passphrase); - // Build layout based on given userIds and keys - - LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); - - LinearLayout container = (LinearLayout) findViewById(R.id.edit_key_container); - if (mIsPassphraseSet) { - mChangePassphrase.setText(getString(R.string.btn_change_passphrase)); - } - mUserIdsView = (SectionView) inflater.inflate(R.layout.edit_key_section, container, false); - mUserIdsView.setType(SectionView.TYPE_USER_ID); - mUserIdsView.setCanBeEdited(mMasterCanSign); - mUserIdsView.setUserIds(mUserIds); - mUserIdsView.setEditorListener(this); - container.addView(mUserIdsView); - mKeysView = (SectionView) inflater.inflate(R.layout.edit_key_section, container, false); - mKeysView.setType(SectionView.TYPE_KEY); - mKeysView.setCanBeEdited(mMasterCanSign); - mKeysView.setKeys(mKeys, mKeysUsages, newKeys); - mKeysView.setEditorListener(this); - container.addView(mKeysView); - - updatePassphraseButtonText(); - - mChangePassphrase.setOnClickListener(new OnClickListener() { - public void onClick(View v) { - showSetPassphraseDialog(); - } - }); - - // disable passphrase when no passphrase checkbox is checked! - mNoPassphrase.setOnCheckedChangeListener(new OnCheckedChangeListener() { - - @Override - public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { - if (isChecked) { - // remove passphrase - mSavedNewPassphrase = mNewPassphrase; - mNewPassphrase = ""; - mChangePassphrase.setVisibility(View.GONE); - } else { - mNewPassphrase = mSavedNewPassphrase; - mChangePassphrase.setVisibility(View.VISIBLE); - } - somethingChanged(); - } - }); - } - - private long getMasterKeyId() { - if (mKeysView.getEditors().getChildCount() == 0) { - return 0; - } - return ((KeyEditor) mKeysView.getEditors().getChildAt(0)).getValue().getKeyId(); - } - - public boolean isPassphraseSet() { - if (mNoPassphrase.isChecked()) { - return true; - } else if ((mIsPassphraseSet) - || (mNewPassphrase != null && !mNewPassphrase.equals(""))) { - return true; - } else { - return false; - } - } - - public boolean hasPassphraseChanged() { - if (mNoPassphrase != null) { - if (mNoPassphrase.isChecked()) { - return mIsPassphraseSet; - } else { - return (mNewPassphrase != null && !mNewPassphrase.equals("")); - } - } else { - return false; - } - } - - private void saveClicked() { - final long masterKeyId = getMasterKeyId(); - if (needsSaving()) { //make sure, as some versions don't support invalidateOptionsMenu - try { - if (!isPassphraseSet()) { - throw new PgpGeneralException(this.getString(R.string.set_a_passphrase)); - } - - String passphrase; - if (mIsPassphraseSet) { - passphrase = PassphraseCacheService.getCachedPassphrase(this, masterKeyId); - } else { - passphrase = ""; - } - if (passphrase == null) { - PassphraseDialogFragment.show(this, masterKeyId, - new Handler() { - @Override - public void handleMessage(Message message) { - if (message.what == PassphraseDialogFragment.MESSAGE_OKAY) { - mCurrentPassphrase = PassphraseCacheService.getCachedPassphrase( - EditKeyActivityOld.this, masterKeyId); - checkEmptyIDsWanted(); - } - } - }); - } else { - mCurrentPassphrase = passphrase; - checkEmptyIDsWanted(); - } - } catch (PgpGeneralException e) { - AppMsg.makeText(this, getString(R.string.error_message, e.getMessage()), - AppMsg.STYLE_ALERT).show(); - } - } else { - AppMsg.makeText(this, R.string.error_change_something_first, AppMsg.STYLE_ALERT).show(); - } - } - - private void checkEmptyIDsWanted() { - try { - ArrayList userIDs = getUserIds(mUserIdsView); - List newIDs = mUserIdsView.getNewIDFlags(); - ArrayList originalIDs = mUserIdsView.getOriginalIDs(); - int curID = 0; - for (String userID : userIDs) { - if (userID.equals("") && (!userID.equals(originalIDs.get(curID)) || newIDs.get(curID))) { - CustomAlertDialogBuilder alert = new CustomAlertDialogBuilder( - EditKeyActivityOld.this); - - alert.setIcon(R.drawable.ic_dialog_alert_holo_light); - alert.setTitle(R.string.warning); - alert.setMessage(EditKeyActivityOld.this.getString(R.string.ask_empty_id_ok)); - - alert.setPositiveButton(EditKeyActivityOld.this.getString(android.R.string.yes), - new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int id) { - dialog.dismiss(); - finallySaveClicked(); - } - } - ); - alert.setNegativeButton(this.getString(android.R.string.no), - new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int id) { - dialog.dismiss(); - } - } - ); - alert.setCancelable(false); - alert.show(); - return; - } - curID++; - } - } catch (PgpGeneralException e) { - Log.e(Constants.TAG, getString(R.string.error_message, e.getMessage())); - AppMsg.makeText(this, getString(R.string.error_message, e.getMessage()), AppMsg.STYLE_ALERT).show(); - } - finallySaveClicked(); - } - - private boolean[] toPrimitiveArray(final List booleanList) { - final boolean[] primitives = new boolean[booleanList.size()]; - int index = 0; - for (Boolean object : booleanList) { - primitives[index++] = object; - } - return primitives; - } - - private void finallySaveClicked() { - /* - try { - // Send all information needed to service to edit key in other thread - Intent intent = new Intent(this, KeychainIntentService.class); - - intent.setAction(KeychainIntentService.ACTION_SAVE_KEYRING); - - OldSaveKeyringParcel saveParams = new OldSaveKeyringParcel(); - saveParams.userIds = getUserIds(mUserIdsView); - saveParams.originalIDs = mUserIdsView.getOriginalIDs(); - saveParams.deletedIDs = mUserIdsView.getDeletedIDs(); - saveParams.newIDs = toPrimitiveArray(mUserIdsView.getNewIDFlags()); - saveParams.primaryIDChanged = mUserIdsView.primaryChanged(); - saveParams.moddedKeys = toPrimitiveArray(mKeysView.getNeedsSavingArray()); - saveParams.deletedKeys = mKeysView.getDeletedKeys(); - saveParams.keysExpiryDates = getKeysExpiryDates(mKeysView); - saveParams.keysUsages = getKeysUsages(mKeysView); - saveParams.newPassphrase = mNewPassphrase; - saveParams.oldPassphrase = mCurrentPassphrase; - saveParams.newKeys = toPrimitiveArray(mKeysView.getNewKeysArray()); - saveParams.keys = getKeys(mKeysView); - saveParams.originalPrimaryID = mUserIdsView.getOriginalPrimaryID(); - - // fill values for this action - Bundle data = new Bundle(); - data.putBoolean(KeychainIntentService.SAVE_KEYRING_CAN_SIGN, mMasterCanSign); - data.putParcelable(KeychainIntentService.SAVE_KEYRING_PARCEL, saveParams); - - intent.putExtra(KeychainIntentService.EXTRA_DATA, data); - - // Message is received after saving is done in KeychainIntentService - KeychainIntentServiceHandler saveHandler = new KeychainIntentServiceHandler(this, - getString(R.string.progress_saving), ProgressDialog.STYLE_HORIZONTAL) { - public void handleMessage(Message message) { - // handle messages by standard KeychainIntentServiceHandler first - super.handleMessage(message); - - if (message.arg1 == KeychainIntentServiceHandler.MESSAGE_OKAY) { - Intent data = new Intent(); - - // return uri pointing to new created key - Uri uri = KeyRings.buildGenericKeyRingUri(getMasterKeyId()); - data.setData(uri); - - setResult(RESULT_OK, data); - finish(); - } - } - }; - - // Create a new Messenger for the communication back - Messenger messenger = new Messenger(saveHandler); - intent.putExtra(KeychainIntentService.EXTRA_MESSENGER, messenger); - - saveHandler.showProgressDialog(this); - - // start service with intent - startService(intent); - } catch (PgpGeneralException e) { - Log.e(Constants.TAG, getString(R.string.error_message, e.getMessage())); - AppMsg.makeText(this, getString(R.string.error_message, e.getMessage()), - AppMsg.STYLE_ALERT).show(); - } - */ - } - - private void cancelClicked() { - if (needsSaving()) { //ask if we want to save - CustomAlertDialogBuilder alert = new CustomAlertDialogBuilder( - EditKeyActivityOld.this); - - alert.setIcon(R.drawable.ic_dialog_alert_holo_light); - alert.setTitle(R.string.warning); - alert.setMessage(EditKeyActivityOld.this.getString(R.string.ask_save_changed_key)); - - alert.setPositiveButton(EditKeyActivityOld.this.getString(android.R.string.yes), - new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int id) { - dialog.dismiss(); - saveClicked(); - } - }); - alert.setNegativeButton(this.getString(android.R.string.no), - new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog, int id) { - dialog.dismiss(); - setResult(RESULT_CANCELED); - finish(); - } - }); - alert.setCancelable(false); - alert.show(); - } else { - setResult(RESULT_CANCELED); - finish(); - } - } - - /** - * Returns user ids from the SectionView - * - * @param userIdsView - * @return - */ - private ArrayList getUserIds(SectionView userIdsView) throws PgpGeneralException { - ArrayList userIds = new ArrayList(); - - ViewGroup userIdEditors = userIdsView.getEditors(); - - boolean gotMainUserId = false; - for (int i = 0; i < userIdEditors.getChildCount(); ++i) { - UserIdEditor editor = (UserIdEditor) userIdEditors.getChildAt(i); - String userId; - userId = editor.getValue(); - - if (editor.isMainUserId()) { - userIds.add(0, userId); - gotMainUserId = true; - } else { - userIds.add(userId); - } - } - - if (userIds.size() == 0) { - throw new PgpGeneralException(getString(R.string.error_key_needs_a_user_id)); - } - - if (!gotMainUserId) { - throw new PgpGeneralException(getString(R.string.error_main_user_id_must_not_be_empty)); - } - - return userIds; - } - - /** - * Returns keys from the SectionView - * - * @param keysView - * @return - */ - private ArrayList getKeys(SectionView keysView) throws PgpGeneralException { - ArrayList keys = new ArrayList(); - - ViewGroup keyEditors = keysView.getEditors(); - - if (keyEditors.getChildCount() == 0) { - throw new PgpGeneralException(getString(R.string.error_key_needs_master_key)); - } - - for (int i = 0; i < keyEditors.getChildCount(); ++i) { - KeyEditor editor = (KeyEditor) keyEditors.getChildAt(i); - keys.add(editor.getValue()); - } - - return keys; - } - - /** - * Returns usage selections of keys from the SectionView - * - * @param keysView - * @return - */ - private ArrayList getKeysUsages(SectionView keysView) throws PgpGeneralException { - ArrayList keysUsages = new ArrayList(); - - ViewGroup keyEditors = keysView.getEditors(); - - if (keyEditors.getChildCount() == 0) { - throw new PgpGeneralException(getString(R.string.error_key_needs_master_key)); - } - - for (int i = 0; i < keyEditors.getChildCount(); ++i) { - KeyEditor editor = (KeyEditor) keyEditors.getChildAt(i); - keysUsages.add(editor.getUsage()); - } - - return keysUsages; - } - - private ArrayList getKeysExpiryDates(SectionView keysView) throws PgpGeneralException { - ArrayList keysExpiryDates = new ArrayList(); - - ViewGroup keyEditors = keysView.getEditors(); - - if (keyEditors.getChildCount() == 0) { - throw new PgpGeneralException(getString(R.string.error_key_needs_master_key)); - } - - for (int i = 0; i < keyEditors.getChildCount(); ++i) { - KeyEditor editor = (KeyEditor) keyEditors.getChildAt(i); - keysExpiryDates.add(editor.getExpiryDate()); - } - - return keysExpiryDates; - } - - private void updatePassphraseButtonText() { - mChangePassphrase.setText(isPassphraseSet() ? getString(R.string.btn_change_passphrase) - : getString(R.string.btn_set_passphrase)); - } - -} diff --git a/OpenKeychain/src/main/res/values/colors.xml b/OpenKeychain/src/main/res/values/colors.xml index c0042d215..449a09003 100644 --- a/OpenKeychain/src/main/res/values/colors.xml +++ b/OpenKeychain/src/main/res/values/colors.xml @@ -5,6 +5,7 @@ #9933cc #cecbce #808080 + #ffdd3333 #33999999 #33CCCCCC diff --git a/README.md b/README.md index 9a80eaf07..6a388e1c5 100644 --- a/README.md +++ b/README.md @@ -219,10 +219,6 @@ Some parts and some libraries are Apache License v2, MIT X11 License (see below) https://github.com/Bearded-Hen/Android-Bootstrap MIT License -* Android AppMsg - https://github.com/johnkil/Android-AppMsg - Apache License v2 - ### Images * icon.svg modified version of kgpg_key2_kopete.svgz diff --git a/extern/AppMsg b/extern/AppMsg deleted file mode 160000 index 61e747419..000000000 --- a/extern/AppMsg +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 61e74741909a712db2e0d31ddffa5b7cf37c21f2 diff --git a/settings.gradle b/settings.gradle index d8802320c..31ee13c8a 100644 --- a/settings.gradle +++ b/settings.gradle @@ -9,7 +9,6 @@ include ':extern:spongycastle:core' include ':extern:spongycastle:pg' include ':extern:spongycastle:pkix' include ':extern:spongycastle:prov' -include ':extern:AppMsg:library' include ':extern:SuperToasts:supertoasts' include ':extern:minidns' include ':extern:KeybaseLib:Lib' -- cgit v1.2.3 From 2c62aa90c0560c975d34b39df4379b5e1fcd6884 Mon Sep 17 00:00:00 2001 From: Vincent Breitmoser Date: Mon, 7 Jul 2014 17:34:41 +0200 Subject: use SuperToast instead of AppMsg in code, part 1 --- OpenKeychain/src/main/AndroidManifest.xml | 5 ---- .../service/KeychainIntentServiceHandler.java | 7 +++-- .../keychain/ui/CertifyKeyActivity.java | 18 +++++++------ .../keychain/ui/DecryptFileFragment.java | 10 ++----- .../keychain/ui/DecryptMessageFragment.java | 9 +++---- .../keychain/ui/EncryptFileFragment.java | 27 +++++++++---------- .../keychain/ui/EncryptMessageFragment.java | 17 +++++------- .../keychain/ui/KeyListActivity.java | 16 +++++------ .../keychain/ui/KeyListFragment.java | 15 +++++------ .../keychain/ui/ViewKeyActivity.java | 31 +++++++--------------- .../keychain/ui/ViewKeyMainFragment.java | 7 +++-- .../keychain/ui/ViewKeyShareFragment.java | 15 +++++------ .../ui/dialog/ShareQrCodeDialogFragment.java | 7 +++-- .../sufficientlysecure/keychain/util/Notify.java | 2 +- .../src/main/res/layout/certify_key_activity.xml | 1 - .../src/main/res/layout/key_list_activity.xml | 6 +++++ OpenKeychain/src/main/res/values/strings.xml | 1 + 17 files changed, 82 insertions(+), 112 deletions(-) diff --git a/OpenKeychain/src/main/AndroidManifest.xml b/OpenKeychain/src/main/AndroidManifest.xml index 2283235e7..abc57e1cd 100644 --- a/OpenKeychain/src/main/AndroidManifest.xml +++ b/OpenKeychain/src/main/AndroidManifest.xml @@ -85,11 +85,6 @@ android:configChanges="orientation|screenSize|keyboardHidden|keyboard" android:label="@string/title_wizard" android:windowSoftInputMode="stateHidden" /> - userIds = mUserIdsAdapter.getSelectedUserIds(); if (userIds.isEmpty()) { - AppMsg.makeText(CertifyKeyActivity.this, "No User IDs to sign selected!", - AppMsg.STYLE_ALERT).show(); + Notify.showNotify(CertifyKeyActivity.this, "No Notify.Style IDs to sign selected!", + Notify.Style.ERROR); return; } @@ -274,8 +274,8 @@ public class CertifyKeyActivity extends ActionBarActivity implements if (message.arg1 == KeychainIntentServiceHandler.MESSAGE_OKAY) { - AppMsg.makeText(CertifyKeyActivity.this, R.string.key_certify_success, - AppMsg.STYLE_INFO).show(); + Notify.showNotify(CertifyKeyActivity.this, R.string.key_certify_success, + Notify.Style.INFO); // check if we need to send the key to the server or not if (mUploadKeyCheckbox.isChecked()) { @@ -327,8 +327,10 @@ public class CertifyKeyActivity extends ActionBarActivity implements super.handleMessage(message); if (message.arg1 == KeychainIntentServiceHandler.MESSAGE_OKAY) { - AppMsg.makeText(CertifyKeyActivity.this, R.string.key_send_success, - AppMsg.STYLE_INFO).show(); + Intent intent = new Intent(); + intent.putExtra(OperationResultParcel.EXTRA_RESULT, message.getData()); + Notify.showNotify(CertifyKeyActivity.this, R.string.key_send_success, + Notify.Style.INFO); setResult(RESULT_OK); finish(); diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/DecryptFileFragment.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/DecryptFileFragment.java index c12b5b7be..56dfdbd95 100644 --- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/DecryptFileFragment.java +++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/DecryptFileFragment.java @@ -34,8 +34,6 @@ import android.widget.CheckBox; import android.widget.EditText; import android.widget.ImageButton; -import com.devspark.appmsg.AppMsg; - import org.sufficientlysecure.keychain.Constants; import org.sufficientlysecure.keychain.R; import org.sufficientlysecure.keychain.helper.FileHelper; @@ -129,7 +127,6 @@ public class DecryptFileFragment extends DecryptFragment { } if (mInputFilename.equals("")) { - //AppMsg.makeText(getActivity(), R.string.no_file_selected, AppMsg.STYLE_ALERT).show(); Notify.showNotify(getActivity(), R.string.no_file_selected, Notify.Style.ERROR); return; } @@ -137,11 +134,8 @@ public class DecryptFileFragment extends DecryptFragment { if (mInputUri == null && mInputFilename.startsWith("file")) { File file = new File(mInputFilename); if (!file.exists() || !file.isFile()) { - AppMsg.makeText( - getActivity(), - getString(R.string.error_message, - getString(R.string.error_file_not_found)), AppMsg.STYLE_ALERT) - .show(); + Notify.showNotify(getActivity(), getString(R.string.error_message, + getString(R.string.error_file_not_found)), Notify.Style.ERROR); return; } } diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/DecryptMessageFragment.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/DecryptMessageFragment.java index 46462f924..cf7a0b4b8 100644 --- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/DecryptMessageFragment.java +++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/DecryptMessageFragment.java @@ -28,8 +28,6 @@ import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.EditText; -import com.devspark.appmsg.AppMsg; - import org.sufficientlysecure.keychain.Constants; import org.sufficientlysecure.keychain.R; import org.sufficientlysecure.keychain.compatibility.ClipboardReflection; @@ -38,6 +36,7 @@ import org.sufficientlysecure.keychain.pgp.PgpHelper; import org.sufficientlysecure.keychain.service.KeychainIntentService; import org.sufficientlysecure.keychain.service.KeychainIntentServiceHandler; import org.sufficientlysecure.keychain.util.Log; +import org.sufficientlysecure.keychain.util.Notify; import java.util.regex.Matcher; @@ -107,12 +106,10 @@ public class DecryptMessageFragment extends DecryptFragment { mCiphertext = matcher.group(1); decryptStart(null); } else { - AppMsg.makeText(getActivity(), R.string.error_invalid_data, AppMsg.STYLE_ALERT) - .show(); + Notify.showNotify(getActivity(), R.string.error_invalid_data, Notify.Style.ERROR); } } else { - AppMsg.makeText(getActivity(), R.string.error_invalid_data, AppMsg.STYLE_ALERT) - .show(); + Notify.showNotify(getActivity(), R.string.error_invalid_data, Notify.Style.ERROR); } } diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/EncryptFileFragment.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/EncryptFileFragment.java index f5d89d186..6ff8d421b 100644 --- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/EncryptFileFragment.java +++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/EncryptFileFragment.java @@ -37,8 +37,6 @@ import android.widget.EditText; import android.widget.ImageButton; import android.widget.Spinner; -import com.devspark.appmsg.AppMsg; - import org.sufficientlysecure.keychain.Constants; import org.sufficientlysecure.keychain.R; import org.sufficientlysecure.keychain.helper.FileHelper; @@ -51,6 +49,7 @@ import org.sufficientlysecure.keychain.ui.dialog.FileDialogFragment; import org.sufficientlysecure.keychain.ui.dialog.PassphraseDialogFragment; import org.sufficientlysecure.keychain.util.Choice; import org.sufficientlysecure.keychain.util.Log; +import org.sufficientlysecure.keychain.util.Notify; import java.io.File; @@ -218,18 +217,18 @@ public class EncryptFileFragment extends Fragment { } if (mInputFilename.equals("")) { - AppMsg.makeText(getActivity(), R.string.no_file_selected, AppMsg.STYLE_ALERT).show(); + Notify.showNotify(getActivity(), R.string.no_file_selected, Notify.Style.ERROR); return; } if (mInputUri == null && !mInputFilename.startsWith("content")) { File file = new File(mInputFilename); if (!file.exists() || !file.isFile()) { - AppMsg.makeText( + Notify.showNotify( getActivity(), getString(R.string.error_message, - getString(R.string.error_file_not_found)), AppMsg.STYLE_ALERT) - .show(); + getString(R.string.error_file_not_found)), Notify.Style.ERROR + ); return; } } @@ -240,13 +239,13 @@ public class EncryptFileFragment extends Fragment { boolean gotPassphrase = (mEncryptInterface.getPassphrase() != null && mEncryptInterface.getPassphrase().length() != 0); if (!gotPassphrase) { - AppMsg.makeText(getActivity(), R.string.passphrase_must_not_be_empty, AppMsg.STYLE_ALERT) - .show(); + Notify.showNotify(getActivity(), R.string.passphrase_must_not_be_empty, Notify.Style.ERROR) + ; return; } if (!mEncryptInterface.getPassphrase().equals(mEncryptInterface.getPassphraseAgain())) { - AppMsg.makeText(getActivity(), R.string.passphrases_do_not_match, AppMsg.STYLE_ALERT).show(); + Notify.showNotify(getActivity(), R.string.passphrases_do_not_match, Notify.Style.ERROR); return; } } else { @@ -256,13 +255,13 @@ public class EncryptFileFragment extends Fragment { && mEncryptInterface.getEncryptionKeys().length > 0); if (!gotEncryptionKeys) { - AppMsg.makeText(getActivity(), R.string.select_encryption_key, AppMsg.STYLE_ALERT).show(); + Notify.showNotify(getActivity(), R.string.select_encryption_key, Notify.Style.ERROR); return; } if (!gotEncryptionKeys && mEncryptInterface.getSignatureKey() == 0) { - AppMsg.makeText(getActivity(), R.string.select_encryption_or_signature_key, - AppMsg.STYLE_ALERT).show(); + Notify.showNotify(getActivity(), R.string.select_encryption_or_signature_key, + Notify.Style.ERROR); return; } @@ -345,8 +344,8 @@ public class EncryptFileFragment extends Fragment { super.handleMessage(message); if (message.arg1 == KeychainIntentServiceHandler.MESSAGE_OKAY) { - AppMsg.makeText(getActivity(), R.string.encrypt_sign_successful, - AppMsg.STYLE_INFO).show(); + Notify.showNotify(getActivity(), R.string.encrypt_sign_successful, + Notify.Style.INFO); if (mDeleteAfter.isChecked()) { // Create and show dialog to delete original file diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/EncryptMessageFragment.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/EncryptMessageFragment.java index 8a6103b16..e1760b4ed 100644 --- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/EncryptMessageFragment.java +++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/EncryptMessageFragment.java @@ -30,8 +30,6 @@ import android.view.View; import android.view.ViewGroup; import android.widget.TextView; -import com.devspark.appmsg.AppMsg; - import org.sufficientlysecure.keychain.Constants; import org.sufficientlysecure.keychain.R; import org.sufficientlysecure.keychain.compatibility.ClipboardReflection; @@ -41,6 +39,7 @@ import org.sufficientlysecure.keychain.service.KeychainIntentServiceHandler; import org.sufficientlysecure.keychain.service.PassphraseCacheService; import org.sufficientlysecure.keychain.ui.dialog.PassphraseDialogFragment; import org.sufficientlysecure.keychain.util.Log; +import org.sufficientlysecure.keychain.util.Notify; public class EncryptMessageFragment extends Fragment { public static final String ARG_TEXT = "text"; @@ -126,13 +125,12 @@ public class EncryptMessageFragment extends Fragment { boolean gotPassphrase = (mEncryptInterface.getPassphrase() != null && mEncryptInterface.getPassphrase().length() != 0); if (!gotPassphrase) { - AppMsg.makeText(getActivity(), R.string.passphrase_must_not_be_empty, AppMsg.STYLE_ALERT) - .show(); + Notify.showNotify(getActivity(), R.string.passphrase_must_not_be_empty, Notify.Style.ERROR); return; } if (!mEncryptInterface.getPassphrase().equals(mEncryptInterface.getPassphraseAgain())) { - AppMsg.makeText(getActivity(), R.string.passphrases_do_not_match, AppMsg.STYLE_ALERT).show(); + Notify.showNotify(getActivity(), R.string.passphrases_do_not_match, Notify.Style.ERROR); return; } @@ -143,8 +141,8 @@ public class EncryptMessageFragment extends Fragment { && mEncryptInterface.getEncryptionKeys().length > 0); if (!gotEncryptionKeys && mEncryptInterface.getSignatureKey() == 0) { - AppMsg.makeText(getActivity(), R.string.select_encryption_or_signature_key, - AppMsg.STYLE_ALERT).show(); + Notify.showNotify(getActivity(), R.string.select_encryption_or_signature_key, + Notify.Style.ERROR); return; } @@ -226,9 +224,8 @@ public class EncryptMessageFragment extends Fragment { if (toClipboard) { ClipboardReflection.copyToClipboard(getActivity(), output); - AppMsg.makeText(getActivity(), - R.string.encrypt_sign_clipboard_successful, AppMsg.STYLE_INFO) - .show(); + Notify.showNotify(getActivity(), + R.string.encrypt_sign_clipboard_successful, Notify.Style.INFO); } else { Intent sendIntent = new Intent(Intent.ACTION_SEND); diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListActivity.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListActivity.java index 849576284..c219fb98c 100644 --- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListActivity.java +++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListActivity.java @@ -25,15 +25,11 @@ import android.os.Messenger; import android.view.Menu; import android.view.MenuItem; -import com.devspark.appmsg.AppMsg; - import org.spongycastle.bcpg.sig.KeyFlags; import org.sufficientlysecure.keychain.Constants; import org.sufficientlysecure.keychain.Constants.choice.algorithm; import org.sufficientlysecure.keychain.R; import org.sufficientlysecure.keychain.helper.ExportHelper; -import org.sufficientlysecure.keychain.helper.OtherHelper; -import org.sufficientlysecure.keychain.keyimport.ImportKeysListEntry; import org.sufficientlysecure.keychain.provider.KeychainContract; import org.sufficientlysecure.keychain.provider.KeychainDatabase; import org.sufficientlysecure.keychain.service.KeychainIntentService; @@ -41,9 +37,9 @@ import org.sufficientlysecure.keychain.service.KeychainIntentServiceHandler; import org.sufficientlysecure.keychain.service.SaveKeyringParcel; import org.sufficientlysecure.keychain.service.SaveKeyringParcel.SubkeyAdd; import org.sufficientlysecure.keychain.util.Log; +import org.sufficientlysecure.keychain.util.Notify; import java.io.IOException; -import java.util.ArrayList; public class KeyListActivity extends DrawerActivity { @@ -96,21 +92,21 @@ public class KeyListActivity extends DrawerActivity { case R.id.menu_key_list_debug_read: try { KeychainDatabase.debugRead(this); - AppMsg.makeText(this, "Restored from backup", AppMsg.STYLE_CONFIRM).show(); + Notify.showNotify(this, "Restored Notify.Style backup", Notify.Style.INFO); getContentResolver().notifyChange(KeychainContract.KeyRings.CONTENT_URI, null); } catch(IOException e) { Log.e(Constants.TAG, "IO Error", e); - AppMsg.makeText(this, "IO Error: " + e.getMessage(), AppMsg.STYLE_ALERT).show(); + Notify.showNotify(this, "IO Notify.Style: " + e.getMessage(), Notify.Style.ERROR); } return true; case R.id.menu_key_list_debug_write: try { KeychainDatabase.debugWrite(this); - AppMsg.makeText(this, "Backup successful", AppMsg.STYLE_CONFIRM).show(); + Notify.showNotify(this, "Backup Notify.Style", Notify.Style.INFO); } catch(IOException e) { Log.e(Constants.TAG, "IO Error", e); - AppMsg.makeText(this, "IO Error: " + e.getMessage(), AppMsg.STYLE_ALERT).show(); + Notify.showNotify(this, "IO Notify.Style: " + e.getMessage(), Notify.Style.ERROR); } return true; @@ -171,4 +167,4 @@ public class KeyListActivity extends DrawerActivity { startService(intent); } -} \ No newline at end of file +} diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListFragment.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListFragment.java index 9d0a80406..c8f6b7b1e 100644 --- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListFragment.java +++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListFragment.java @@ -52,8 +52,6 @@ import android.widget.ListView; import android.widget.TextView; import android.widget.Button; -import com.devspark.appmsg.AppMsg; - import org.sufficientlysecure.keychain.Constants; import org.sufficientlysecure.keychain.R; import org.sufficientlysecure.keychain.helper.ExportHelper; @@ -62,6 +60,7 @@ import org.sufficientlysecure.keychain.provider.KeychainContract.KeyRings; import org.sufficientlysecure.keychain.ui.dialog.DeleteKeyDialogFragment; import org.sufficientlysecure.keychain.util.Highlighter; import org.sufficientlysecure.keychain.util.Log; +import org.sufficientlysecure.keychain.util.Notify; import java.util.Date; import java.util.HashMap; @@ -104,10 +103,10 @@ public class KeyListFragment extends LoaderFragment @Override public void onClick(View v) { - Intent intent = new Intent(getActivity(), EditKeyActivityOld.class); - intent.setAction(EditKeyActivityOld.ACTION_CREATE_KEY); - intent.putExtra(EditKeyActivityOld.EXTRA_GENERATE_DEFAULT_KEYS, true); - intent.putExtra(EditKeyActivityOld.EXTRA_USER_IDS, ""); // show user id view + Intent intent = new Intent(getActivity(), EditKeyActivity.class); + intent.setAction(EditKeyActivity.ACTION_CREATE_KEY); + intent.putExtra(EditKeyActivity.EXTRA_GENERATE_DEFAULT_KEYS, true); + intent.putExtra(EditKeyActivity.EXTRA_USER_IDS, ""); // show user id view startActivityForResult(intent, 0); } }); @@ -339,8 +338,8 @@ public class KeyListFragment extends LoaderFragment public void showDeleteKeyDialog(final ActionMode mode, long[] masterKeyIds, boolean hasSecret) { // Can only work on singular secret keys if(hasSecret && masterKeyIds.length > 1) { - AppMsg.makeText(getActivity(), R.string.secret_cannot_multiple, - AppMsg.STYLE_ALERT).show(); + Notify.showNotify(getActivity(), R.string.secret_cannot_multiple, + Notify.Style.ERROR); return; } diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyActivity.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyActivity.java index a9cd0976b..b8b2542ce 100644 --- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyActivity.java +++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyActivity.java @@ -44,8 +44,6 @@ import android.view.MenuItem; import android.view.View; import android.view.Window; -import com.devspark.appmsg.AppMsg; - import org.sufficientlysecure.keychain.Constants; import org.sufficientlysecure.keychain.R; import org.sufficientlysecure.keychain.helper.ContactHelper; @@ -54,11 +52,13 @@ import org.sufficientlysecure.keychain.pgp.KeyRing; import org.sufficientlysecure.keychain.pgp.PgpKeyHelper; import org.sufficientlysecure.keychain.provider.KeychainContract; import org.sufficientlysecure.keychain.provider.ProviderHelper; +import org.sufficientlysecure.keychain.service.OperationResultParcel; import org.sufficientlysecure.keychain.service.OperationResults.ImportResult; import org.sufficientlysecure.keychain.ui.adapter.PagerTabStripAdapter; import org.sufficientlysecure.keychain.ui.widget.SlidingTabLayout.TabColorizer; import org.sufficientlysecure.keychain.util.Log; import org.sufficientlysecure.keychain.ui.widget.SlidingTabLayout; +import org.sufficientlysecure.keychain.util.Notify; import java.util.Date; import java.util.HashMap; @@ -295,7 +295,7 @@ public class ViewKeyActivity extends ActionBarActivity implements } } } catch (ProviderHelper.NotFoundException e) { - AppMsg.makeText(this, R.string.error_key_not_found, AppMsg.STYLE_ALERT).show(); + Notify.showNotify(this, R.string.error_key_not_found, Notify.Style.ERROR); Log.e(Constants.TAG, "Key not found", e); } return super.onOptionsItemSelected(item); @@ -352,22 +352,11 @@ public class ViewKeyActivity extends ActionBarActivity implements @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { - switch (requestCode) { - case REQUEST_CODE_LOOKUP_KEY: { - if (resultCode == Activity.RESULT_OK) { - ImportResult result = data.getParcelableExtra(ImportKeysActivity.EXTRA_RESULT); - if (result != null) { - result.displayNotify(this); - } - } - break; - } - - default: { - super.onActivityResult(requestCode, resultCode, data); - - break; - } + if (data.hasExtra(OperationResultParcel.EXTRA_RESULT)) { + OperationResultParcel result = data.getParcelableExtra(OperationResultParcel.EXTRA_RESULT); + result.createNotify(this).show(); + } else { + super.onActivityResult(requestCode, resultCode, data); } } @@ -455,8 +444,8 @@ public class ViewKeyActivity extends ActionBarActivity implements public void handleMessage(Message msg) { switch (msg.what) { case NFC_SENT: - AppMsg.makeText(ViewKeyActivity.this, R.string.nfc_successful, - AppMsg.STYLE_INFO).show(); + Notify.showNotify( + ViewKeyActivity.this, R.string.nfc_successful, Notify.Style.INFO); break; } } diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java index f0636cf2c..2a0f518d8 100644 --- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java +++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyMainFragment.java @@ -29,8 +29,6 @@ import android.view.View; import android.view.ViewGroup; import android.widget.ListView; -import com.devspark.appmsg.AppMsg; - import org.sufficientlysecure.keychain.Constants; import org.sufficientlysecure.keychain.R; import org.sufficientlysecure.keychain.pgp.exception.PgpGeneralException; @@ -40,6 +38,7 @@ import org.sufficientlysecure.keychain.provider.KeychainContract.UserIds; import org.sufficientlysecure.keychain.provider.ProviderHelper; import org.sufficientlysecure.keychain.ui.adapter.UserIdsAdapter; import org.sufficientlysecure.keychain.util.Log; +import org.sufficientlysecure.keychain.util.Notify; import java.util.Date; @@ -225,7 +224,7 @@ public class ViewKeyMainFragment extends LoaderFragment implements private void encrypt(Uri dataUri) { // If there is no encryption key, don't bother. if (!mHasEncrypt) { - AppMsg.makeText(getActivity(), R.string.error_no_encrypt_subkey, AppMsg.STYLE_ALERT).show(); + Notify.showNotify(getActivity(), R.string.error_no_encrypt_subkey, Notify.Style.ERROR); return; } try { @@ -246,7 +245,7 @@ public class ViewKeyMainFragment extends LoaderFragment implements private void certify(Uri dataUri) { Intent signIntent = new Intent(getActivity(), CertifyKeyActivity.class); signIntent.setData(dataUri); - startActivity(signIntent); + startActivityForResult(signIntent, 0); } private void editKey(Uri dataUri) { diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyShareFragment.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyShareFragment.java index 52b573f47..c2339c25f 100644 --- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyShareFragment.java +++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyShareFragment.java @@ -33,8 +33,6 @@ import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; -import com.devspark.appmsg.AppMsg; - import org.sufficientlysecure.keychain.Constants; import org.sufficientlysecure.keychain.R; import org.sufficientlysecure.keychain.compatibility.ClipboardReflection; @@ -47,6 +45,7 @@ import org.sufficientlysecure.keychain.provider.ProviderHelper; import org.sufficientlysecure.keychain.ui.dialog.ShareNfcDialogFragment; import org.sufficientlysecure.keychain.ui.dialog.ShareQrCodeDialogFragment; import org.sufficientlysecure.keychain.util.Log; +import org.sufficientlysecure.keychain.util.Notify; import org.sufficientlysecure.keychain.util.QrCodeUtils; import java.io.IOException; @@ -171,13 +170,13 @@ public class ViewKeyShareFragment extends LoaderFragment implements } else { message = getResources().getString(R.string.key_copied_to_clipboard); } - AppMsg.makeText(getActivity(), message, AppMsg.STYLE_INFO).show(); + Notify.showNotify(getActivity(), message, Notify.Style.OK); } else { // Android will fail with android.os.TransactionTooLargeException if key is too big // see http://www.lonestarprod.com/?p=34 if (content.length() >= 86389) { - AppMsg.makeText(getActivity(), R.string.key_too_big_for_sharing, - AppMsg.STYLE_ALERT).show(); + Notify.showNotify(getActivity(), R.string.key_too_big_for_sharing, + Notify.Style.ERROR); return; } @@ -195,13 +194,13 @@ public class ViewKeyShareFragment extends LoaderFragment implements } } catch (PgpGeneralException e) { Log.e(Constants.TAG, "error processing key!", e); - AppMsg.makeText(getActivity(), R.string.error_key_processing, AppMsg.STYLE_ALERT).show(); + Notify.showNotify(getActivity(), R.string.error_key_processing, Notify.Style.ERROR); } catch (IOException e) { Log.e(Constants.TAG, "error processing key!", e); - AppMsg.makeText(getActivity(), R.string.error_key_processing, AppMsg.STYLE_ALERT).show(); + Notify.showNotify(getActivity(), R.string.error_key_processing, Notify.Style.ERROR); } catch (ProviderHelper.NotFoundException e) { Log.e(Constants.TAG, "key not found!", e); - AppMsg.makeText(getActivity(), R.string.error_key_not_found, AppMsg.STYLE_ALERT).show(); + Notify.showNotify(getActivity(), R.string.error_key_not_found, Notify.Style.ERROR); } } diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/ShareQrCodeDialogFragment.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/ShareQrCodeDialogFragment.java index 24608784b..eb779f401 100644 --- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/ShareQrCodeDialogFragment.java +++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/dialog/ShareQrCodeDialogFragment.java @@ -27,14 +27,13 @@ import android.view.View; import android.widget.ImageView; import android.widget.TextView; -import com.devspark.appmsg.AppMsg; - import org.sufficientlysecure.keychain.Constants; import org.sufficientlysecure.keychain.R; import org.sufficientlysecure.keychain.pgp.PgpKeyHelper; import org.sufficientlysecure.keychain.provider.KeychainContract.KeyRings; import org.sufficientlysecure.keychain.provider.ProviderHelper; import org.sufficientlysecure.keychain.util.Log; +import org.sufficientlysecure.keychain.util.Notify; import org.sufficientlysecure.keychain.util.QrCodeUtils; public class ShareQrCodeDialogFragment extends DialogFragment { @@ -87,7 +86,7 @@ public class ShareQrCodeDialogFragment extends DialogFragment { KeyRings.FINGERPRINT, ProviderHelper.FIELD_TYPE_BLOB); if (blob == null) { Log.e(Constants.TAG, "key not found!"); - AppMsg.makeText(getActivity(), R.string.error_key_not_found, AppMsg.STYLE_ALERT).show(); + Notify.showNotify(getActivity(), R.string.error_key_not_found, Notify.Style.ERROR); return null; } @@ -97,7 +96,7 @@ public class ShareQrCodeDialogFragment extends DialogFragment { setQrCode(content); } catch (ProviderHelper.NotFoundException e) { Log.e(Constants.TAG, "key not found!", e); - AppMsg.makeText(getActivity(), R.string.error_key_not_found, AppMsg.STYLE_ALERT).show(); + Notify.showNotify(getActivity(), R.string.error_key_not_found, Notify.Style.ERROR); return null; } diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/util/Notify.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/util/Notify.java index 67f81fb24..22e3f5d66 100644 --- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/util/Notify.java +++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/util/Notify.java @@ -29,7 +29,7 @@ import com.github.johnpersano.supertoasts.SuperToast; */ public class Notify { - public static enum Style {OK, WARN, ERROR} + public static enum Style {OK, WARN, INFO, ERROR} /** * Shows a simple in-layout notification with the CharSequence given as parameter diff --git a/OpenKeychain/src/main/res/layout/certify_key_activity.xml b/OpenKeychain/src/main/res/layout/certify_key_activity.xml index bb43fa805..1443ffd46 100644 --- a/OpenKeychain/src/main/res/layout/certify_key_activity.xml +++ b/OpenKeychain/src/main/res/layout/certify_key_activity.xml @@ -1,6 +1,5 @@ diff --git a/OpenKeychain/src/main/res/layout/key_list_activity.xml b/OpenKeychain/src/main/res/layout/key_list_activity.xml index c4c2c35cb..156351887 100644 --- a/OpenKeychain/src/main/res/layout/key_list_activity.xml +++ b/OpenKeychain/src/main/res/layout/key_list_activity.xml @@ -4,6 +4,12 @@ android:layout_width="match_parent" android:layout_height="match_parent" > + + diff --git a/OpenKeychain/src/main/res/values/strings.xml b/OpenKeychain/src/main/res/values/strings.xml index 29780f235..36002b763 100644 --- a/OpenKeychain/src/main/res/values/strings.xml +++ b/OpenKeychain/src/main/res/values/strings.xml @@ -656,6 +656,7 @@ Unlocking keyring + Internal error! Certifier Certificate Details Identity -- cgit v1.2.3 From d8f278229352a58dbdcf49bb65538249f8c4ccc0 Mon Sep 17 00:00:00 2001 From: Vincent Breitmoser Date: Mon, 7 Jul 2014 17:35:23 +0200 Subject: use SuperToast instead of AppMsg in code, part 2 --- .../keychain/service/OperationResultParcel.java | 60 ++++++++++++++++++++++ .../keychain/service/OperationResults.java | 7 +-- 2 files changed, 64 insertions(+), 3 deletions(-) diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/service/OperationResultParcel.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/service/OperationResultParcel.java index 6bf6b655d..1df2a38f1 100644 --- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/service/OperationResultParcel.java +++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/service/OperationResultParcel.java @@ -1,10 +1,20 @@ package org.sufficientlysecure.keychain.service; +import android.app.Activity; +import android.content.Intent; import android.os.Parcel; import android.os.Parcelable; +import android.view.View; + +import com.github.johnpersano.supertoasts.SuperCardToast; +import com.github.johnpersano.supertoasts.SuperToast; +import com.github.johnpersano.supertoasts.util.OnClickWrapper; +import com.github.johnpersano.supertoasts.util.Style; import org.sufficientlysecure.keychain.Constants; import org.sufficientlysecure.keychain.R; +import org.sufficientlysecure.keychain.ui.LogDisplayActivity; +import org.sufficientlysecure.keychain.ui.LogDisplayFragment; import org.sufficientlysecure.keychain.util.IterableIterator; import org.sufficientlysecure.keychain.util.Log; @@ -21,6 +31,9 @@ import java.util.ArrayList; * */ public class OperationResultParcel implements Parcelable { + + public static final String EXTRA_RESULT = "operation_result"; + /** Holds the overall result, the number specifying varying degrees of success. The first bit * is 0 on overall success, 1 on overall failure. All other bits may be used for more specific * conditions. */ @@ -104,6 +117,43 @@ public class OperationResultParcel implements Parcelable { } + public SuperCardToast createNotify(final Activity activity) { + + int resultType = getResult(); + + String str; + int duration, color; + + // Not an overall failure + if ((resultType & OperationResultParcel.RESULT_ERROR) == 0) { + + if (getLog().containsWarnings()) { + duration = 0; + color = Style.ORANGE; + } else { + duration = SuperToast.Duration.LONG; + color = Style.GREEN; + } + + str = activity.getString(R.string.import_error); + + } else { + duration = 0; + color = Style.RED; + str = activity.getString(R.string.import_error); + } + + SuperCardToast toast = new SuperCardToast(activity, + SuperToast.Type.STANDARD, Style.getStyle(color, SuperToast.Animations.POPUP)); + toast.setText(str); + toast.setDuration(duration); + toast.setIndeterminate(duration == 0); + toast.setSwipeToDismiss(true); + + return toast; + + } + /** This is an enum of all possible log events. * * Element names should generally be prefixed with MSG_XX_ where XX is an @@ -123,6 +173,8 @@ public class OperationResultParcel implements Parcelable { */ public static enum LogType { + INTERNAL_ERROR (R.string.internal_error), + // import public MSG_IP(R.string.msg_ip), MSG_IP_APPLY_BATCH (R.string.msg_ip_apply_batch), @@ -313,6 +365,14 @@ public class OperationResultParcel implements Parcelable { add(new OperationResultParcel.LogEntryParcel(level, type, indent, (Object[]) null)); } + public LogEntryParcel getResultId() { + LogEntryParcel entry = get(size()-1); + if (entry.mLevel != LogLevel.OK && entry.mLevel != LogLevel.ERROR) { + return new LogEntryParcel(LogLevel.ERROR, LogType.INTERNAL_ERROR, 0); + } + return entry; + } + public boolean containsWarnings() { for(LogEntryParcel entry : new IterableIterator(iterator())) { if (entry.mLevel == LogLevel.WARN || entry.mLevel == LogLevel.ERROR) { diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/service/OperationResults.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/service/OperationResults.java index fd3d4ed00..39c11a855 100644 --- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/service/OperationResults.java +++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/service/OperationResults.java @@ -80,7 +80,7 @@ public abstract class OperationResults { } }; - public void displayNotify(final Activity activity) { + public SuperCardToast createNotify(final Activity activity) { int resultType = getResult(); @@ -88,7 +88,7 @@ public abstract class OperationResults { int duration, color; // Not an overall failure - if ((resultType & ImportResult.RESULT_ERROR) == 0) { + if ((resultType & OperationResultParcel.RESULT_ERROR) == 0) { String withWarnings; // Any warnings? @@ -157,7 +157,8 @@ public abstract class OperationResults { } )); } - toast.show(); + + return toast; } -- cgit v1.2.3 From 5eb414a22b28c93e47fe7f62ee786b898d9a21d4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominik=20Sch=C3=BCrmann?= Date: Fri, 25 Jul 2014 01:34:29 +0200 Subject: Program flow fixes --- .../keychain/helper/Preferences.java | 2 +- .../keychain/ui/CreateKeyActivity.java | 46 +++++++++++----------- .../keychain/ui/FirstTimeActivity.java | 27 +++++++++---- .../keychain/ui/KeyListActivity.java | 16 ++------ 4 files changed, 48 insertions(+), 43 deletions(-) diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/helper/Preferences.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/helper/Preferences.java index e55c14a2a..5d765b663 100644 --- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/helper/Preferences.java +++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/helper/Preferences.java @@ -139,7 +139,7 @@ public class Preferences { editor.commit(); } - public boolean getFirstTime() { + public boolean isFirstTime() { return mSharedPreferences.getBoolean(Constants.Pref.FIRST_TIME, true); } diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/CreateKeyActivity.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/CreateKeyActivity.java index d2073d9a7..fe1b7e688 100644 --- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/CreateKeyActivity.java +++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/CreateKeyActivity.java @@ -45,10 +45,10 @@ import java.util.regex.Matcher; public class CreateKeyActivity extends ActionBarActivity { - AutoCompleteTextView nameEdit; - AutoCompleteTextView emailEdit; - EditText passphraseEdit; - Button createButton; + AutoCompleteTextView mNameEdit; + AutoCompleteTextView mEmailEdit; + EditText mPassphraseEdit; + Button mCreateButton; @Override protected void onCreate(Bundle savedInstanceState) { @@ -56,19 +56,19 @@ public class CreateKeyActivity extends ActionBarActivity { setContentView(R.layout.create_key_activity); - nameEdit = (AutoCompleteTextView) findViewById(R.id.name); - emailEdit = (AutoCompleteTextView) findViewById(R.id.email); - passphraseEdit = (EditText) findViewById(R.id.passphrase); - createButton = (Button) findViewById(R.id.create_key_button); + mNameEdit = (AutoCompleteTextView) findViewById(R.id.name); + mEmailEdit = (AutoCompleteTextView) findViewById(R.id.email); + mPassphraseEdit = (EditText) findViewById(R.id.passphrase); + mCreateButton = (Button) findViewById(R.id.create_key_button); - emailEdit.setThreshold(1); // Start working from first character - emailEdit.setAdapter( + mEmailEdit.setThreshold(1); // Start working from first character + mEmailEdit.setAdapter( new ArrayAdapter (this, android.R.layout.simple_spinner_dropdown_item, ContactHelper.getPossibleUserEmails(this) ) ); - emailEdit.addTextChangedListener(new TextWatcher() { + mEmailEdit.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) { } @@ -83,27 +83,28 @@ public class CreateKeyActivity extends ActionBarActivity { if (email.length() > 0) { Matcher emailMatcher = Patterns.EMAIL_ADDRESS.matcher(email); if (emailMatcher.matches()) { - emailEdit.setCompoundDrawablesWithIntrinsicBounds(0, 0, + mEmailEdit.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.uid_mail_ok, 0); } else { - emailEdit.setCompoundDrawablesWithIntrinsicBounds(0, 0, + mEmailEdit.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.uid_mail_bad, 0); } } else { // remove drawable if email is empty - emailEdit.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0); + mEmailEdit.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0); } } }); - nameEdit.setThreshold(1); // Start working from first character - nameEdit.setAdapter( + + mNameEdit.setThreshold(1); // Start working from first character + mNameEdit.setAdapter( new ArrayAdapter (this, android.R.layout.simple_spinner_dropdown_item, ContactHelper.getPossibleUserNames(this) ) ); - createButton.setOnClickListener(new View.OnClickListener() { + mCreateButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { createKeyCheck(); @@ -113,9 +114,9 @@ public class CreateKeyActivity extends ActionBarActivity { } private void createKeyCheck() { - if (isEditTextNotEmpty(this, nameEdit) - && isEditTextNotEmpty(this, emailEdit) - && isEditTextNotEmpty(this, passphraseEdit)) { + if (isEditTextNotEmpty(this, mNameEdit) + && isEditTextNotEmpty(this, mEmailEdit) + && isEditTextNotEmpty(this, mPassphraseEdit)) { createKey(); } } @@ -134,6 +135,7 @@ public class CreateKeyActivity extends ActionBarActivity { super.handleMessage(message); if (message.arg1 == KeychainIntentServiceHandler.MESSAGE_OKAY) { + CreateKeyActivity.this.setResult(RESULT_OK); CreateKeyActivity.this.finish(); } } @@ -146,9 +148,9 @@ public class CreateKeyActivity extends ActionBarActivity { parcel.mAddSubKeys.add(new SaveKeyringParcel.SubkeyAdd(Constants.choice.algorithm.rsa, 4096, KeyFlags.CERTIFY_OTHER, null)); parcel.mAddSubKeys.add(new SaveKeyringParcel.SubkeyAdd(Constants.choice.algorithm.rsa, 4096, KeyFlags.SIGN_DATA, null)); parcel.mAddSubKeys.add(new SaveKeyringParcel.SubkeyAdd(Constants.choice.algorithm.rsa, 4096, KeyFlags.ENCRYPT_COMMS | KeyFlags.ENCRYPT_STORAGE, null)); - String userId = nameEdit.getText().toString() + " <" + emailEdit.getText().toString() + ">"; + String userId = mNameEdit.getText().toString() + " <" + mEmailEdit.getText().toString() + ">"; parcel.mAddUserIds.add(userId); - parcel.mNewPassphrase = passphraseEdit.getText().toString(); + parcel.mNewPassphrase = mPassphraseEdit.getText().toString(); // get selected key entries data.putParcelable(KeychainIntentService.SAVE_KEYRING_PARCEL, parcel); diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/FirstTimeActivity.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/FirstTimeActivity.java index aa4120d2c..4271b2d5a 100644 --- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/FirstTimeActivity.java +++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/FirstTimeActivity.java @@ -25,6 +25,7 @@ import android.view.Window; import android.widget.Button; import org.sufficientlysecure.keychain.R; +import org.sufficientlysecure.keychain.helper.Preferences; public class FirstTimeActivity extends ActionBarActivity { @@ -47,9 +48,7 @@ public class FirstTimeActivity extends ActionBarActivity { mSkipSetup.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { - Intent intent = new Intent(FirstTimeActivity.this, KeyListActivity.class); - startActivity(intent); - finish(); + finishSetup(); } }); @@ -58,8 +57,7 @@ public class FirstTimeActivity extends ActionBarActivity { public void onClick(View v) { Intent intent = new Intent(FirstTimeActivity.this, ImportKeysActivity.class); intent.setAction(ImportKeysActivity.ACTION_IMPORT_KEY_FROM_FILE_AND_RETURN); - startActivity(intent); - finish(); + startActivityForResult(intent, 1); } }); @@ -67,11 +65,26 @@ public class FirstTimeActivity extends ActionBarActivity { @Override public void onClick(View v) { Intent intent = new Intent(FirstTimeActivity.this, CreateKeyActivity.class); - startActivity(intent); - finish(); + startActivityForResult(intent, 1); } }); } + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + super.onActivityResult(requestCode, resultCode, data); + + if (resultCode == RESULT_OK) { + finishSetup(); + } + } + + private void finishSetup() { + Preferences prefs = Preferences.getPreferences(this); + prefs.setFirstTime(false); + Intent intent = new Intent(FirstTimeActivity.this, KeyListActivity.class); + startActivity(intent); + finish(); + } } diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListActivity.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListActivity.java index 9cc623c83..095762283 100644 --- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListActivity.java +++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListActivity.java @@ -17,28 +17,19 @@ package org.sufficientlysecure.keychain.ui; -import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; -import android.os.Message; -import android.os.Messenger; import android.view.Menu; import android.view.MenuItem; import com.devspark.appmsg.AppMsg; -import org.spongycastle.bcpg.sig.KeyFlags; import org.sufficientlysecure.keychain.Constants; -import org.sufficientlysecure.keychain.Constants.choice.algorithm; import org.sufficientlysecure.keychain.R; import org.sufficientlysecure.keychain.helper.ExportHelper; import org.sufficientlysecure.keychain.helper.Preferences; import org.sufficientlysecure.keychain.provider.KeychainContract; import org.sufficientlysecure.keychain.provider.KeychainDatabase; -import org.sufficientlysecure.keychain.service.KeychainIntentService; -import org.sufficientlysecure.keychain.service.KeychainIntentServiceHandler; -import org.sufficientlysecure.keychain.service.SaveKeyringParcel; -import org.sufficientlysecure.keychain.service.SaveKeyringParcel.SubkeyAdd; import org.sufficientlysecure.keychain.util.Log; import java.io.IOException; @@ -51,11 +42,10 @@ public class KeyListActivity extends DrawerActivity { public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); + // if this is the first time show first time activity Preferences prefs = Preferences.getPreferences(this); - if (prefs.getFirstTime()) { - prefs.setFirstTime(false); - Intent intent = new Intent(this, FirstTimeActivity.class); - startActivity(intent); + if (prefs.isFirstTime()) { + startActivity(new Intent(this, FirstTimeActivity.class)); finish(); return; } -- cgit v1.2.3 From 9ea514855080513664ed7a95bb658e59cfb1bc17 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominik=20Sch=C3=BCrmann?= Date: Fri, 25 Jul 2014 01:34:57 +0200 Subject: Update libs --- extern/openpgp-api-lib | 2 +- extern/spongycastle | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/extern/openpgp-api-lib b/extern/openpgp-api-lib index cd1a6748d..869ab96e6 160000 --- a/extern/openpgp-api-lib +++ b/extern/openpgp-api-lib @@ -1 +1 @@ -Subproject commit cd1a6748dd7a4c7a251a4f75eb289955dfbb1058 +Subproject commit 869ab96e6dcd4821fd5360248429e49dae6fbaca diff --git a/extern/spongycastle b/extern/spongycastle index c142a844b..a68ebd1ff 160000 --- a/extern/spongycastle +++ b/extern/spongycastle @@ -1 +1 @@ -Subproject commit c142a844b680652adb751a193a4e4a926a4c080b +Subproject commit a68ebd1ffc5af880903b2905c17e4f6ac0f13988 -- cgit v1.2.3 From ab2b90342e805a0a625e059dcfe2db11157a5680 Mon Sep 17 00:00:00 2001 From: Vincent Breitmoser Date: Sat, 26 Jul 2014 03:47:29 +0200 Subject: test and fix: adding an empty user id should fail --- .../keychain/tests/PgpKeyOperationTest.java | 14 +++++++++++++- .../sufficientlysecure/keychain/pgp/PgpKeyOperation.java | 5 +++++ .../keychain/service/OperationResultParcel.java | 1 + OpenKeychain/src/main/res/values/strings.xml | 1 + 4 files changed, 20 insertions(+), 1 deletion(-) diff --git a/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/tests/PgpKeyOperationTest.java b/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/tests/PgpKeyOperationTest.java index 5c6072c25..e423d790d 100644 --- a/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/tests/PgpKeyOperationTest.java +++ b/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/tests/PgpKeyOperationTest.java @@ -107,7 +107,7 @@ public class PgpKeyOperationTest { } @Test - public void testAlgorithmChoice() { + public void createSecretKeyRingTests() { OperationResultParcel.OperationLog log = new OperationResultParcel.OperationLog(); @@ -629,6 +629,15 @@ public class PgpKeyOperationTest { @Test public void testUserIdAdd() throws Exception { + { + parcel.mAddUserIds.add(""); + WrappedSecretKeyRing secretRing = new WrappedSecretKeyRing(ring.getEncoded(), false, 0); + OperationResultParcel.OperationLog log = new OperationResultParcel.OperationLog(); + UncachedKeyRing modified = op.modifySecretKeyRing(secretRing, parcel, passphrase, log, 0); + Assert.assertNull("adding an empty user id should fail", modified); + } + + parcel.reset(); parcel.mAddUserIds.add("rainbow"); UncachedKeyRing modified = applyModificationWithChecks(parcel, ring, onlyA, onlyB); @@ -689,6 +698,9 @@ public class PgpKeyOperationTest { parcel.reset(); //noinspection SpellCheckingInspection parcel.mChangePrimaryUserId = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"; + if (parcel.mChangePrimaryUserId.equals(passphrase)) { + parcel.mChangePrimaryUserId += "A"; + } WrappedSecretKeyRing secretRing = new WrappedSecretKeyRing(ring.getEncoded(), false, 0); OperationResultParcel.OperationLog log = new OperationResultParcel.OperationLog(); diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpKeyOperation.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpKeyOperation.java index 00f73a5b0..69244ca14 100644 --- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpKeyOperation.java +++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpKeyOperation.java @@ -313,6 +313,11 @@ public class PgpKeyOperation { for (String userId : saveParcel.mAddUserIds) { log.add(LogLevel.INFO, LogType.MSG_MF_UID_ADD, indent); + if (userId.equals("")) { + log.add(LogLevel.ERROR, LogType.MSG_MF_UID_ERROR_EMPTY, indent+1); + return null; + } + // this operation supersedes all previous binding and revocation certificates, // so remove those to retain assertions from canonicalization for later operations @SuppressWarnings("unchecked") diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/service/OperationResultParcel.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/service/OperationResultParcel.java index 89d534df6..e55ec5568 100644 --- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/service/OperationResultParcel.java +++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/service/OperationResultParcel.java @@ -279,6 +279,7 @@ public class OperationResultParcel implements Parcelable { MSG_MF_UID_ADD (R.string.msg_mf_uid_add), MSG_MF_UID_PRIMARY (R.string.msg_mf_uid_primary), MSG_MF_UID_REVOKE (R.string.msg_mf_uid_revoke), + MSG_MF_UID_ERROR_EMPTY (R.string.msg_mf_uid_error_empty), MSG_MF_UNLOCK_ERROR (R.string.msg_mf_unlock_error), MSG_MF_UNLOCK (R.string.msg_mf_unlock), ; diff --git a/OpenKeychain/src/main/res/values/strings.xml b/OpenKeychain/src/main/res/values/strings.xml index 55ecf3ae0..d1a20813b 100644 --- a/OpenKeychain/src/main/res/values/strings.xml +++ b/OpenKeychain/src/main/res/values/strings.xml @@ -674,6 +674,7 @@ Adding user id %s Changing primary uid to %s Revoking user id %s + User ID must not be empty! Error unlocking keyring! Unlocking keyring -- cgit v1.2.3 From a1c163e993d057aa963960bc1e588ef67be90065 Mon Sep 17 00:00:00 2001 From: Vincent Breitmoser Date: Sat, 26 Jul 2014 03:48:13 +0200 Subject: tests: add a couple of UncachedKeyRing.merge tests --- .../keychain/tests/UncachedKeyringMergeTest.java | 375 +++++++++++++++++++++ 1 file changed, 375 insertions(+) create mode 100644 OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/tests/UncachedKeyringMergeTest.java diff --git a/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/tests/UncachedKeyringMergeTest.java b/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/tests/UncachedKeyringMergeTest.java new file mode 100644 index 000000000..cde1991dd --- /dev/null +++ b/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/tests/UncachedKeyringMergeTest.java @@ -0,0 +1,375 @@ +package org.sufficientlysecure.keychain.tests; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.RobolectricTestRunner; +import org.robolectric.shadows.ShadowLog; +import org.spongycastle.bcpg.BCPGInputStream; +import org.spongycastle.bcpg.Packet; +import org.spongycastle.bcpg.PublicKeyPacket; +import org.spongycastle.bcpg.sig.KeyFlags; +import org.sufficientlysecure.keychain.Constants; +import org.sufficientlysecure.keychain.pgp.PgpKeyOperation; +import org.sufficientlysecure.keychain.pgp.UncachedKeyRing; +import org.sufficientlysecure.keychain.pgp.UncachedPublicKey; +import org.sufficientlysecure.keychain.pgp.WrappedPublicKeyRing; +import org.sufficientlysecure.keychain.pgp.WrappedSecretKey; +import org.sufficientlysecure.keychain.pgp.WrappedSecretKeyRing; +import org.sufficientlysecure.keychain.service.OperationResultParcel; +import org.sufficientlysecure.keychain.service.SaveKeyringParcel; +import org.sufficientlysecure.keychain.support.KeyringTestingHelper; +import org.sufficientlysecure.keychain.support.KeyringTestingHelper.RawPacket; +import org.sufficientlysecure.keychain.util.ProgressScaler; + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.util.ArrayList; +import java.util.Iterator; + +/** Tests for the UncachedKeyring.merge method. + * + * This is another complex, crypto-related method. It merges information from one keyring into + * another, keeping information from the base (ie, called object) keyring in case of conflicts. + * The types of keys may be Public or Secret and can be mixed, For mixed types the result type + * will be the same as the base keyring. + * + * Test cases: + * - Merging keyrings with different masterKeyIds should fail + * - Merging a key with itself should be a no-operation + * - Merging a key with an extra revocation certificate, it should have that certificate + * - Merging a key with an extra user id, it should have that extra user id and its certificates + * - Merging a key with an extra user id certificate, it should have that certificate + * - Merging a key with an extra subkey, it should have that subkey + * - Merging a key with an extra subkey certificate, it should have that certificate + * - All of the above operations should work regardless of the key types. This means in particular + * that for new subkeys, an equivalent subkey of the proper type must be generated. + * - In case of two secret keys with the same id but different S2K, the key of the base keyring + * should be preferred (TODO or should it?) + * + * Note that the merge operation does not care about certificate validity, a bad certificate or + * packet will be copied regardless. Filtering out bad packets is done with canonicalization. + * + */ +@RunWith(RobolectricTestRunner.class) +@org.robolectric.annotation.Config(emulateSdk = 18) // Robolectric doesn't yet support 19 +public class UncachedKeyringMergeTest { + + static UncachedKeyRing staticRingA, staticRingB; + static int totalPackets; + UncachedKeyRing ringA, ringB; + ArrayList onlyA = new ArrayList(); + ArrayList onlyB = new ArrayList(); + OperationResultParcel.OperationLog log = new OperationResultParcel.OperationLog(); + PgpKeyOperation op; + SaveKeyringParcel parcel; + + @BeforeClass + public static void setUpOnce() throws Exception { + ShadowLog.stream = System.out; + + { + SaveKeyringParcel parcel = new SaveKeyringParcel(); + parcel.mAddSubKeys.add(new SaveKeyringParcel.SubkeyAdd( + Constants.choice.algorithm.rsa, 1024, KeyFlags.CERTIFY_OTHER, null)); + parcel.mAddSubKeys.add(new SaveKeyringParcel.SubkeyAdd( + Constants.choice.algorithm.rsa, 1024, KeyFlags.SIGN_DATA, null)); + + parcel.mAddUserIds.add("twi"); + parcel.mAddUserIds.add("pink"); + // passphrase is tested in PgpKeyOperationTest, just use empty here + parcel.mNewPassphrase = ""; + PgpKeyOperation op = new PgpKeyOperation(null); + + OperationResultParcel.OperationLog log = new OperationResultParcel.OperationLog(); + staticRingA = op.createSecretKeyRing(parcel, log, 0); + } + + { + SaveKeyringParcel parcel = new SaveKeyringParcel(); + parcel.mAddSubKeys.add(new SaveKeyringParcel.SubkeyAdd( + Constants.choice.algorithm.rsa, 1024, KeyFlags.CERTIFY_OTHER, null)); + + parcel.mAddUserIds.add("shy"); + // passphrase is tested in PgpKeyOperationTest, just use empty here + parcel.mNewPassphrase = ""; + PgpKeyOperation op = new PgpKeyOperation(null); + + OperationResultParcel.OperationLog log = new OperationResultParcel.OperationLog(); + staticRingB = op.createSecretKeyRing(parcel, log, 0); + } + + Assert.assertNotNull("initial test key creation must succeed", staticRingA); + Assert.assertNotNull("initial test key creation must succeed", staticRingB); + + // we sleep here for a second, to make sure all new certificates have different timestamps + Thread.sleep(1000); + } + + @Before + public void setUp() throws Exception { + // show Log.x messages in system.out + ShadowLog.stream = System.out; + ringA = staticRingA; + ringB = staticRingB; + + // setting up some parameters just to reduce code duplication + op = new PgpKeyOperation(new ProgressScaler(null, 0, 100, 100)); + + // set this up, gonna need it more than once + parcel = new SaveKeyringParcel(); + parcel.mMasterKeyId = ringA.getMasterKeyId(); + parcel.mFingerprint = ringA.getFingerprint(); + } + + public void testSelfNoOp() throws Exception { + + UncachedKeyRing merged = mergeWithChecks(ringA, ringA, null); + Assert.assertArrayEquals("keyring merged with itself must be identical", + ringA.getEncoded(), merged.getEncoded() + ); + + } + + @Test + public void testDifferentMasterKeyIds() throws Exception { + + Assert.assertNotEquals("generated key ids must be different", + ringA.getMasterKeyId(), ringB.getMasterKeyId()); + + Assert.assertNull("merging keys with differing key ids must fail", + ringA.merge(ringB, log, 0)); + Assert.assertNull("merging keys with differing key ids must fail", + ringB.merge(ringA, log, 0)); + + } + + @Test + public void testAddedUserId() throws Exception { + + UncachedKeyRing modifiedA, modifiedB; { + WrappedSecretKeyRing secretRing = new WrappedSecretKeyRing(ringA.getEncoded(), false, 0); + + parcel.reset(); + parcel.mAddUserIds.add("flim"); + modifiedA = op.modifySecretKeyRing(secretRing, parcel, "", log, 0); + + parcel.reset(); + parcel.mAddUserIds.add("flam"); + modifiedB = op.modifySecretKeyRing(secretRing, parcel, "", log, 0); + } + + { // merge A into base + UncachedKeyRing merged = mergeWithChecks(ringA, modifiedA); + + Assert.assertEquals("merged keyring must have lost no packets", 0, onlyA.size()); + Assert.assertEquals("merged keyring must have gained two packets", 2, onlyB.size()); + Assert.assertTrue("merged keyring must contain new user id", + merged.getPublicKey().getUnorderedUserIds().contains("flim")); + } + + { // merge A into B + UncachedKeyRing merged = mergeWithChecks(modifiedA, modifiedB, ringA); + + Assert.assertEquals("merged keyring must have lost no packets", 0, onlyA.size()); + Assert.assertEquals("merged keyring must have gained four packets", 4, onlyB.size()); + Assert.assertTrue("merged keyring must contain first new user id", + merged.getPublicKey().getUnorderedUserIds().contains("flim")); + Assert.assertTrue("merged keyring must contain second new user id", + merged.getPublicKey().getUnorderedUserIds().contains("flam")); + + } + + } + + @Test + public void testAddedSubkeyId() throws Exception { + + UncachedKeyRing modifiedA, modifiedB; + long subKeyIdA, subKeyIdB; + { + WrappedSecretKeyRing secretRing = new WrappedSecretKeyRing(ringA.getEncoded(), false, 0); + + parcel.reset(); + parcel.mAddSubKeys.add(new SaveKeyringParcel.SubkeyAdd( + Constants.choice.algorithm.rsa, 1024, KeyFlags.SIGN_DATA, null)); + modifiedA = op.modifySecretKeyRing(secretRing, parcel, "", log, 0); + modifiedB = op.modifySecretKeyRing(secretRing, parcel, "", log, 0); + + { + Iterator it = modifiedA.getPublicKeys(); + it.next(); it.next(); + subKeyIdA = it.next().getKeyId(); + } + + { + Iterator it = modifiedB.getPublicKeys(); + it.next(); it.next(); + subKeyIdB = it.next().getKeyId(); + } + + } + + { + UncachedKeyRing merged = mergeWithChecks(ringA, modifiedA); + + Assert.assertEquals("merged keyring must have lost no packets", 0, onlyA.size()); + Assert.assertEquals("merged keyring must have gained two packets", 2, onlyB.size()); + + long mergedKeyId; + { + Iterator it = merged.getPublicKeys(); + it.next(); it.next(); + mergedKeyId = it.next().getKeyId(); + } + Assert.assertEquals("merged keyring must contain the new subkey", subKeyIdA, mergedKeyId); + } + + { + UncachedKeyRing merged = mergeWithChecks(modifiedA, modifiedB, ringA); + + Assert.assertEquals("merged keyring must have lost no packets", 0, onlyA.size()); + Assert.assertEquals("merged keyring must have gained four packets", 4, onlyB.size()); + + Iterator it = merged.getPublicKeys(); + it.next(); it.next(); + Assert.assertEquals("merged keyring must contain the new subkey", + subKeyIdA, it.next().getKeyId()); + Assert.assertEquals("merged keyring must contain both new subkeys", + subKeyIdB, it.next().getKeyId()); + } + + } + + @Test + public void testAddedKeySignature() throws Exception { + } + + @Test + public void testAddedUserIdSignature() throws Exception { + + final UncachedKeyRing pubRing = ringA.extractPublicKeyRing(); + + final UncachedKeyRing modified; { + WrappedPublicKeyRing publicRing = new WrappedPublicKeyRing( + pubRing.getEncoded(), false, 0); + + WrappedSecretKey secretKey = new WrappedSecretKeyRing( + ringB.getEncoded(), false, 0).getSecretKey(); + secretKey.unlock(""); + // sign all user ids + modified = secretKey.certifyUserIds(publicRing, publicRing.getPublicKey().getUnorderedUserIds()); + } + + { + UncachedKeyRing merged = ringA.merge(modified, log, 0); + Assert.assertNotNull("merge must succeed", merged); + Assert.assertArrayEquals("foreign signatures should not be merged into secret key", + ringA.getEncoded(), merged.getEncoded() + ); + } + + { + UncachedKeyRing merged = pubRing.merge(modified, log, 0); + Assert.assertNotNull("merge must succeed", merged); + Assert.assertFalse( + "merging keyring with extra signatures into its base should yield that same keyring", + KeyringTestingHelper.diffKeyrings(merged.getEncoded(), modified.getEncoded(), onlyA, onlyB) + ); + } + } + + private UncachedKeyRing mergeWithChecks(UncachedKeyRing a, UncachedKeyRing b) + throws Exception { + return mergeWithChecks(a, b, a, true); + } + + private UncachedKeyRing mergeWithChecks(UncachedKeyRing a, UncachedKeyRing b, boolean commutative) + throws Exception { + return mergeWithChecks(a, b, a, commutative); + } + + private UncachedKeyRing mergeWithChecks(UncachedKeyRing a, UncachedKeyRing b, UncachedKeyRing base) + throws Exception { + return mergeWithChecks(a, b, base, true); + } + + private UncachedKeyRing mergeWithChecks(UncachedKeyRing a, UncachedKeyRing b, + UncachedKeyRing base, boolean commutative) + throws Exception { + + Assert.assertTrue("merging keyring must be secret type", a.isSecret()); + Assert.assertTrue("merged keyring must be secret type", b.isSecret()); + + final UncachedKeyRing resultA; + UncachedKeyRing resultB; + + { // sec + sec + resultA = a.merge(b, log, 0); + Assert.assertNotNull("merge must succeed as sec(a)+sec(b)", resultA); + + resultB = b.merge(a, log, 0); + Assert.assertNotNull("merge must succeed as sec(b)+sec(a)", resultB); + + // check commutativity, if requested + if (commutative) { + Assert.assertFalse("result of merge must be commutative", + KeyringTestingHelper.diffKeyrings( + resultA.getEncoded(), resultB.getEncoded(), onlyA, onlyB) + ); + } + } + + final UncachedKeyRing pubA = a.extractPublicKeyRing(); + final UncachedKeyRing pubB = b.extractPublicKeyRing(); + + { // sec + pub, pub + sec, and pub + pub + + try { + resultB = a.merge(pubB, log, 0); + Assert.assertNotNull("merge must succeed as sec(a)+pub(b)", resultA); + + Assert.assertFalse("result of sec(a)+pub(b) must be same as sec(a)+sec(b)", + KeyringTestingHelper.diffKeyrings( + resultA.getEncoded(), resultB.getEncoded(), onlyA, onlyB) + ); + } catch (RuntimeException e) { + System.out.println("special case, dummy key generation not in yet"); + } + + final UncachedKeyRing pubResult = resultA.extractPublicKeyRing(); + + resultB = pubA.merge(b, log, 0); + Assert.assertNotNull("merge must succeed as pub(a)+sec(b)", resultA); + + Assert.assertFalse("result of pub(a)+sec(b) must be same as pub(sec(a)+sec(b))", + KeyringTestingHelper.diffKeyrings( + pubResult.getEncoded(), resultB.getEncoded(), onlyA, onlyB) + ); + + resultB = pubA.merge(pubB, log, 0); + Assert.assertNotNull("merge must succeed as pub(a)+pub(b)", resultA); + + Assert.assertFalse("result of pub(a)+pub(b) must be same as pub(sec(a)+sec(b))", + KeyringTestingHelper.diffKeyrings( + pubResult.getEncoded(), resultB.getEncoded(), onlyA, onlyB) + ); + + } + + if (base != null) { + // set up onlyA and onlyB to be a diff to the base + Assert.assertTrue("merged keyring must differ from base", + KeyringTestingHelper.diffKeyrings( + base.getEncoded(), resultA.getEncoded(), onlyA, onlyB) + ); + } + + return resultA; + + } + +} \ No newline at end of file -- cgit v1.2.3 From 7fe1b00080ad7bcdbda890e9c2c60ad4a1225a9f Mon Sep 17 00:00:00 2001 From: Vincent Breitmoser Date: Sat, 26 Jul 2014 03:56:28 +0200 Subject: fixes for extractPublicKeyRing, update SpongyCastle --- .../keychain/pgp/UncachedKeyRing.java | 15 +++++++++------ .../keychain/pgp/WrappedPublicKeyRing.java | 18 +++++++++--------- extern/spongycastle | 2 +- 3 files changed, 19 insertions(+), 16 deletions(-) diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/pgp/UncachedKeyRing.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/pgp/UncachedKeyRing.java index 6020fc084..3b39eb201 100644 --- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/pgp/UncachedKeyRing.java +++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/pgp/UncachedKeyRing.java @@ -14,6 +14,7 @@ import org.spongycastle.openpgp.PGPSecretKeyRing; import org.spongycastle.openpgp.PGPSignature; import org.spongycastle.openpgp.PGPSignatureList; import org.spongycastle.openpgp.PGPUtil; +import org.spongycastle.openpgp.operator.jcajce.JcaKeyFingerprintCalculator; import org.sufficientlysecure.keychain.Constants; import org.sufficientlysecure.keychain.pgp.exception.PgpGeneralException; import org.sufficientlysecure.keychain.service.OperationResultParcel.OperationLog; @@ -24,6 +25,7 @@ import org.sufficientlysecure.keychain.util.Log; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; @@ -193,7 +195,7 @@ public class UncachedKeyRing { * - Remove all certificates flagged as "local" * - Remove all certificates which are superseded by a newer one on the same target, * including revocations with later re-certifications. - * - Remove all certificates of unknown type: + * - Remove all certificates in other positions if not of known type: * - key revocation signatures on the master key * - subkey binding signatures for subkeys * - certifications and certification revocations for user ids @@ -658,7 +660,7 @@ public class UncachedKeyRing { return left.length - right.length; } // compare byte-by-byte - for (int i = 0; i < left.length && i < right.length; i++) { + for (int i = 0; i < left.length; i++) { if (left[i] != right[i]) { return (left[i] & 0xff) - (right[i] & 0xff); } @@ -768,19 +770,20 @@ public class UncachedKeyRing { } - public UncachedKeyRing extractPublicKeyRing() { + public UncachedKeyRing extractPublicKeyRing() throws IOException { if(!isSecret()) { throw new RuntimeException("Tried to extract public keyring from non-secret keyring. " + "This is a programming error and should never happen!"); } - ArrayList keys = new ArrayList(); Iterator it = mRing.getPublicKeys(); + ByteArrayOutputStream stream = new ByteArrayOutputStream(2048); while (it.hasNext()) { - keys.add(it.next()); + stream.write(it.next().getEncoded()); } - return new UncachedKeyRing(new PGPPublicKeyRing(keys)); + return new UncachedKeyRing( + new PGPPublicKeyRing(stream.toByteArray(), new JcaKeyFingerprintCalculator())); } /** This method replaces a public key in a keyring. diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/pgp/WrappedPublicKeyRing.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/pgp/WrappedPublicKeyRing.java index 57d84072a..bb1f7d778 100644 --- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/pgp/WrappedPublicKeyRing.java +++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/pgp/WrappedPublicKeyRing.java @@ -1,14 +1,11 @@ package org.sufficientlysecure.keychain.pgp; import org.spongycastle.bcpg.ArmoredOutputStream; -import org.spongycastle.openpgp.PGPKeyRing; import org.spongycastle.openpgp.PGPObjectFactory; import org.spongycastle.openpgp.PGPPublicKey; import org.spongycastle.openpgp.PGPPublicKeyRing; -import org.sufficientlysecure.keychain.Constants; import org.sufficientlysecure.keychain.pgp.exception.PgpGeneralException; import org.sufficientlysecure.keychain.util.IterableIterator; -import org.sufficientlysecure.keychain.util.Log; import java.io.IOException; import java.util.Iterator; @@ -25,17 +22,20 @@ public class WrappedPublicKeyRing extends WrappedKeyRing { PGPPublicKeyRing getRing() { if(mRing == null) { + // get first object in block PGPObjectFactory factory = new PGPObjectFactory(mPubKey); - PGPKeyRing keyRing = null; try { - if ((keyRing = (PGPKeyRing) factory.nextObject()) == null) { - Log.e(Constants.TAG, "No keys given!"); + Object obj = factory.nextObject(); + if (! (obj instanceof PGPPublicKeyRing)) { + throw new RuntimeException("Error constructing WrappedPublicKeyRing, should never happen!"); + } + mRing = (PGPPublicKeyRing) obj; + if (factory.nextObject() != null) { + throw new RuntimeException("Encountered trailing data after keyring, should never happen!"); } } catch (IOException e) { - Log.e(Constants.TAG, "Error while converting to PGPKeyRing!", e); + throw new RuntimeException("IO Error constructing WrappedPublicKeyRing, should never happen!"); } - - mRing = (PGPPublicKeyRing) keyRing; } return mRing; } diff --git a/extern/spongycastle b/extern/spongycastle index c142a844b..41ef8b1f5 160000 --- a/extern/spongycastle +++ b/extern/spongycastle @@ -1 +1 @@ -Subproject commit c142a844b680652adb751a193a4e4a926a4c080b +Subproject commit 41ef8b1f539dd3d8748865d68a34ed307f699eec -- cgit v1.2.3 From 7296ac484914bbe5cec90b37cc1319db49f7d9b8 Mon Sep 17 00:00:00 2001 From: Vincent Breitmoser Date: Sat, 26 Jul 2014 03:57:54 +0200 Subject: UncachedKeyRing.merge: copy over new secret subkeys into secret keyrings --- .../keychain/pgp/UncachedKeyRing.java | 21 +++++++++------------ 1 file changed, 9 insertions(+), 12 deletions(-) diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/pgp/UncachedKeyRing.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/pgp/UncachedKeyRing.java index 3b39eb201..91b06324a 100644 --- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/pgp/UncachedKeyRing.java +++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/pgp/UncachedKeyRing.java @@ -688,7 +688,14 @@ public class UncachedKeyRing { final PGPPublicKey resultKey = result.getPublicKey(key.getKeyID()); if (resultKey == null) { log.add(LogLevel.DEBUG, LogType.MSG_MG_NEW_SUBKEY, indent); - result = replacePublicKey(result, key); + // special case: if both rings are secret, copy over the secret key + if (isSecret() && other.isSecret()) { + PGPSecretKey sKey = ((PGPSecretKeyRing) candidate).getSecretKey(key.getKeyID()); + result = PGPSecretKeyRing.insertSecretKey((PGPSecretKeyRing) result, sKey); + } else { + // otherwise, just insert the public key + result = replacePublicKey(result, key); + } continue; } @@ -696,17 +703,7 @@ public class UncachedKeyRing { PGPPublicKey modified = resultKey; // Iterate certifications - for (PGPSignature cert : new IterableIterator(key.getSignatures())) { - int type = cert.getSignatureType(); - // Disregard certifications on user ids, we will deal with those later - if (type == PGPSignature.NO_CERTIFICATION - || type == PGPSignature.DEFAULT_CERTIFICATION - || type == PGPSignature.CASUAL_CERTIFICATION - || type == PGPSignature.POSITIVE_CERTIFICATION - || type == PGPSignature.CERTIFICATION_REVOCATION) { - continue; - } - + for (PGPSignature cert : new IterableIterator(key.getKeySignatures())) { // Don't merge foreign stuff into secret keys if (cert.getKeyID() != masterKeyId && isSecret()) { continue; -- cgit v1.2.3 From eab4c4ba8e4865153b3fa2122ea28628db5f7bb0 Mon Sep 17 00:00:00 2001 From: Vincent Breitmoser Date: Sat, 26 Jul 2014 04:35:38 +0200 Subject: test: (almost) full coverage for UncachedKeyRing.merge --- .../keychain/support/KeyringTestingHelper.java | 12 ++++ .../keychain/tests/UncachedKeyringMergeTest.java | 69 ++++++++++++++++------ 2 files changed, 64 insertions(+), 17 deletions(-) diff --git a/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/support/KeyringTestingHelper.java b/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/support/KeyringTestingHelper.java index 3fa668e6e..98c7b0743 100644 --- a/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/support/KeyringTestingHelper.java +++ b/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/support/KeyringTestingHelper.java @@ -21,6 +21,7 @@ import android.content.Context; import org.spongycastle.util.Arrays; import org.sufficientlysecure.keychain.pgp.NullProgressable; import org.sufficientlysecure.keychain.pgp.UncachedKeyRing; +import org.sufficientlysecure.keychain.pgp.UncachedPublicKey; import org.sufficientlysecure.keychain.pgp.exception.PgpGeneralException; import org.sufficientlysecure.keychain.provider.ProviderHelper; import org.sufficientlysecure.keychain.service.OperationResults; @@ -331,6 +332,17 @@ public class KeyringTestingHelper { } + public static E getNth(Iterator it, int position) { + while(position-- > 0) { + it.next(); + } + return it.next(); + } + + public static long getSubkeyId(UncachedKeyRing ring, int position) { + return getNth(ring.getPublicKeys(), position).getKeyId(); + } + private void retrieveKeyAndExpectNotFound(ProviderHelper providerHelper, long masterKeyId) { try { providerHelper.getWrappedPublicKeyRing(masterKeyId); diff --git a/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/tests/UncachedKeyringMergeTest.java b/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/tests/UncachedKeyringMergeTest.java index cde1991dd..0b249dcce 100644 --- a/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/tests/UncachedKeyringMergeTest.java +++ b/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/tests/UncachedKeyringMergeTest.java @@ -9,6 +9,7 @@ import org.robolectric.RobolectricTestRunner; import org.robolectric.shadows.ShadowLog; import org.spongycastle.bcpg.BCPGInputStream; import org.spongycastle.bcpg.Packet; +import org.spongycastle.bcpg.PacketTags; import org.spongycastle.bcpg.PublicKeyPacket; import org.spongycastle.bcpg.sig.KeyFlags; import org.sufficientlysecure.keychain.Constants; @@ -199,17 +200,8 @@ public class UncachedKeyringMergeTest { modifiedA = op.modifySecretKeyRing(secretRing, parcel, "", log, 0); modifiedB = op.modifySecretKeyRing(secretRing, parcel, "", log, 0); - { - Iterator it = modifiedA.getPublicKeys(); - it.next(); it.next(); - subKeyIdA = it.next().getKeyId(); - } - - { - Iterator it = modifiedB.getPublicKeys(); - it.next(); it.next(); - subKeyIdB = it.next().getKeyId(); - } + subKeyIdA = KeyringTestingHelper.getSubkeyId(modifiedA, 2); + subKeyIdB = KeyringTestingHelper.getSubkeyId(modifiedB, 2); } @@ -219,12 +211,7 @@ public class UncachedKeyringMergeTest { Assert.assertEquals("merged keyring must have lost no packets", 0, onlyA.size()); Assert.assertEquals("merged keyring must have gained two packets", 2, onlyB.size()); - long mergedKeyId; - { - Iterator it = merged.getPublicKeys(); - it.next(); it.next(); - mergedKeyId = it.next().getKeyId(); - } + long mergedKeyId = KeyringTestingHelper.getSubkeyId(merged, 2); Assert.assertEquals("merged keyring must contain the new subkey", subKeyIdA, mergedKeyId); } @@ -246,6 +233,24 @@ public class UncachedKeyringMergeTest { @Test public void testAddedKeySignature() throws Exception { + + final UncachedKeyRing modified; { + parcel.reset(); + parcel.mRevokeSubKeys.add(KeyringTestingHelper.getSubkeyId(ringA, 1)); + WrappedSecretKeyRing secretRing = new WrappedSecretKeyRing( + ringA.getEncoded(), false, 0); + modified = op.modifySecretKeyRing(secretRing, parcel, "", log, 0); + } + + { + UncachedKeyRing merged = ringA.merge(modified, log, 0); + Assert.assertNotNull("merge must succeed", merged); + Assert.assertFalse( + "merging keyring with extra signatures into its base should yield that same keyring", + KeyringTestingHelper.diffKeyrings(merged.getEncoded(), modified.getEncoded(), onlyA, onlyB) + ); + } + } @Test @@ -272,6 +277,36 @@ public class UncachedKeyringMergeTest { ); } + { + byte[] sig = KeyringTestingHelper.getNth( + modified.getPublicKey().getSignaturesForId("twi"), 1).getEncoded(); + + // inject the (foreign!) signature into subkey signature position + UncachedKeyRing moreModified = KeyringTestingHelper.injectPacket(modified, sig, 1); + + UncachedKeyRing merged = ringA.merge(moreModified, log, 0); + Assert.assertNotNull("merge must succeed", merged); + Assert.assertArrayEquals("foreign signatures should not be merged into secret key", + ringA.getEncoded(), merged.getEncoded() + ); + + merged = pubRing.merge(moreModified, log, 0); + Assert.assertNotNull("merge must succeed", merged); + Assert.assertTrue( + "merged keyring should contain new signature", + KeyringTestingHelper.diffKeyrings(pubRing.getEncoded(), merged.getEncoded(), onlyA, onlyB) + ); + Assert.assertEquals("merged keyring should be missing no packets", 0, onlyA.size()); + Assert.assertEquals("merged keyring should contain exactly two more packets", 2, onlyB.size()); + Assert.assertEquals("first added packet should be a signature", + PacketTags.SIGNATURE, onlyB.get(0).tag); + Assert.assertEquals("first added packet should be in the position we injected it at", + 1, onlyB.get(0).position); + Assert.assertEquals("second added packet should be a signature", + PacketTags.SIGNATURE, onlyB.get(1).tag); + + } + { UncachedKeyRing merged = pubRing.merge(modified, log, 0); Assert.assertNotNull("merge must succeed", merged); -- cgit v1.2.3 From d849b6d8a83deed28e8a22da642db781c4e6cf6d Mon Sep 17 00:00:00 2001 From: Vincent Breitmoser Date: Sat, 26 Jul 2014 04:38:30 +0200 Subject: test: don't need commutativity parameter here after all --- .../keychain/tests/UncachedKeyringMergeTest.java | 24 ++++++---------------- 1 file changed, 6 insertions(+), 18 deletions(-) diff --git a/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/tests/UncachedKeyringMergeTest.java b/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/tests/UncachedKeyringMergeTest.java index 0b249dcce..5c2f0b170 100644 --- a/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/tests/UncachedKeyringMergeTest.java +++ b/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/tests/UncachedKeyringMergeTest.java @@ -319,21 +319,11 @@ public class UncachedKeyringMergeTest { private UncachedKeyRing mergeWithChecks(UncachedKeyRing a, UncachedKeyRing b) throws Exception { - return mergeWithChecks(a, b, a, true); - } - - private UncachedKeyRing mergeWithChecks(UncachedKeyRing a, UncachedKeyRing b, boolean commutative) - throws Exception { - return mergeWithChecks(a, b, a, commutative); - } - - private UncachedKeyRing mergeWithChecks(UncachedKeyRing a, UncachedKeyRing b, UncachedKeyRing base) - throws Exception { - return mergeWithChecks(a, b, base, true); + return mergeWithChecks(a, b, a); } private UncachedKeyRing mergeWithChecks(UncachedKeyRing a, UncachedKeyRing b, - UncachedKeyRing base, boolean commutative) + UncachedKeyRing base) throws Exception { Assert.assertTrue("merging keyring must be secret type", a.isSecret()); @@ -350,12 +340,10 @@ public class UncachedKeyringMergeTest { Assert.assertNotNull("merge must succeed as sec(b)+sec(a)", resultB); // check commutativity, if requested - if (commutative) { - Assert.assertFalse("result of merge must be commutative", - KeyringTestingHelper.diffKeyrings( - resultA.getEncoded(), resultB.getEncoded(), onlyA, onlyB) - ); - } + Assert.assertFalse("result of merge must be commutative", + KeyringTestingHelper.diffKeyrings( + resultA.getEncoded(), resultB.getEncoded(), onlyA, onlyB) + ); } final UncachedKeyRing pubA = a.extractPublicKeyRing(); -- cgit v1.2.3 From 1c00227c41850be155748233a8010a8067cf679f Mon Sep 17 00:00:00 2001 From: Vincent Breitmoser Date: Sat, 26 Jul 2014 14:16:44 +0200 Subject: test: small code cleanup --- .../keychain/tests/PgpKeyOperationTest.java | 18 ++++-------------- 1 file changed, 4 insertions(+), 14 deletions(-) diff --git a/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/tests/PgpKeyOperationTest.java b/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/tests/PgpKeyOperationTest.java index e423d790d..2cc22deee 100644 --- a/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/tests/PgpKeyOperationTest.java +++ b/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/tests/PgpKeyOperationTest.java @@ -352,7 +352,8 @@ public class PgpKeyOperationTest { { // bad keysize should fail parcel.reset(); - parcel.mAddSubKeys.add(new SubkeyAdd(algorithm.rsa, 77, KeyFlags.SIGN_DATA, null)); + parcel.mAddSubKeys.add(new SubkeyAdd( + algorithm.rsa, new Random().nextInt(1024), KeyFlags.SIGN_DATA, null)); WrappedSecretKeyRing secretRing = new WrappedSecretKeyRing(ring.getEncoded(), false, 0); OperationResultParcel.OperationLog log = new OperationResultParcel.OperationLog(); @@ -379,12 +380,7 @@ public class PgpKeyOperationTest { public void testSubkeyModify() throws Exception { long expiry = new Date().getTime()/1000 + 1024; - long keyId; - { - Iterator it = ring.getPublicKeys(); - it.next(); - keyId = it.next().getKeyId(); - } + long keyId = KeyringTestingHelper.getSubkeyId(ring, 1); UncachedKeyRing modified = ring; { @@ -463,13 +459,7 @@ public class PgpKeyOperationTest { @Test public void testSubkeyRevoke() throws Exception { - long keyId; - { - Iterator it = ring.getPublicKeys(); - it.next(); - keyId = it.next().getKeyId(); - } - + long keyId = KeyringTestingHelper.getSubkeyId(ring, 1); int flags = ring.getPublicKey(keyId).getKeyUsage(); UncachedKeyRing modified; -- cgit v1.2.3 From cf6e4254c7f31e24a75ddbd11a1be20137175ef8 Mon Sep 17 00:00:00 2001 From: Vincent Breitmoser Date: Sat, 26 Jul 2014 15:51:21 +0200 Subject: test: add misc UncachedKeyRing tests --- .../keychain/tests/PgpKeyOperationTest.java | 2 +- .../tests/UncachedKeyringCanonicalizeTest.java | 8 +- .../keychain/tests/UncachedKeyringMergeTest.java | 1 - .../keychain/tests/UncachedKeyringTest.java | 129 +++++++++++++++++++++ 4 files changed, 132 insertions(+), 8 deletions(-) create mode 100644 OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/tests/UncachedKeyringTest.java diff --git a/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/tests/PgpKeyOperationTest.java b/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/tests/PgpKeyOperationTest.java index 2cc22deee..3c5d5b1c2 100644 --- a/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/tests/PgpKeyOperationTest.java +++ b/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/tests/PgpKeyOperationTest.java @@ -353,7 +353,7 @@ public class PgpKeyOperationTest { { // bad keysize should fail parcel.reset(); parcel.mAddSubKeys.add(new SubkeyAdd( - algorithm.rsa, new Random().nextInt(1024), KeyFlags.SIGN_DATA, null)); + algorithm.rsa, new Random().nextInt(512), KeyFlags.SIGN_DATA, null)); WrappedSecretKeyRing secretRing = new WrappedSecretKeyRing(ring.getEncoded(), false, 0); OperationResultParcel.OperationLog log = new OperationResultParcel.OperationLog(); diff --git a/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/tests/UncachedKeyringCanonicalizeTest.java b/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/tests/UncachedKeyringCanonicalizeTest.java index 6f3cf31b5..5724708e1 100644 --- a/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/tests/UncachedKeyringCanonicalizeTest.java +++ b/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/tests/UncachedKeyringCanonicalizeTest.java @@ -174,13 +174,11 @@ public class UncachedKeyringCanonicalizeTest { Assert.assertEquals("two packets should be stripped after canonicalization", 2, onlyA.size()); Assert.assertEquals("no new packets after canonicalization", 0, onlyB.size()); - Packet p; - p = new BCPGInputStream(new ByteArrayInputStream(onlyA.get(0).buf)).readPacket(); + Packet p = new BCPGInputStream(new ByteArrayInputStream(onlyA.get(0).buf)).readPacket(); Assert.assertTrue("first stripped packet must be user id", p instanceof UserIDPacket); Assert.assertEquals("missing user id must be the expected one", "twi", ((UserIDPacket) p).getID()); - p = new BCPGInputStream(new ByteArrayInputStream(onlyA.get(1).buf)).readPacket(); Assert.assertArrayEquals("second stripped packet must be signature we removed", sig.getEncoded(), onlyA.get(1).buf); @@ -197,13 +195,11 @@ public class UncachedKeyringCanonicalizeTest { Assert.assertEquals("two packets should be missing after canonicalization", 2, onlyA.size()); Assert.assertEquals("no new packets after canonicalization", 0, onlyB.size()); - Packet p; - p = new BCPGInputStream(new ByteArrayInputStream(onlyA.get(0).buf)).readPacket(); + Packet p = new BCPGInputStream(new ByteArrayInputStream(onlyA.get(0).buf)).readPacket(); Assert.assertTrue("first stripped packet must be user id", p instanceof UserIDPacket); Assert.assertEquals("missing user id must be the expected one", "twi", ((UserIDPacket) p).getID()); - p = new BCPGInputStream(new ByteArrayInputStream(onlyA.get(1).buf)).readPacket(); Assert.assertArrayEquals("second stripped packet must be signature we removed", sig.getEncoded(), onlyA.get(1).buf); } diff --git a/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/tests/UncachedKeyringMergeTest.java b/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/tests/UncachedKeyringMergeTest.java index 5c2f0b170..af60085ce 100644 --- a/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/tests/UncachedKeyringMergeTest.java +++ b/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/tests/UncachedKeyringMergeTest.java @@ -60,7 +60,6 @@ import java.util.Iterator; public class UncachedKeyringMergeTest { static UncachedKeyRing staticRingA, staticRingB; - static int totalPackets; UncachedKeyRing ringA, ringB; ArrayList onlyA = new ArrayList(); ArrayList onlyB = new ArrayList(); diff --git a/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/tests/UncachedKeyringTest.java b/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/tests/UncachedKeyringTest.java new file mode 100644 index 000000000..23ae177d0 --- /dev/null +++ b/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/tests/UncachedKeyringTest.java @@ -0,0 +1,129 @@ +package org.sufficientlysecure.keychain.tests; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.RobolectricTestRunner; +import org.robolectric.shadows.ShadowLog; +import org.spongycastle.bcpg.sig.KeyFlags; +import org.sufficientlysecure.keychain.Constants; +import org.sufficientlysecure.keychain.pgp.PgpKeyOperation; +import org.sufficientlysecure.keychain.pgp.UncachedKeyRing; +import org.sufficientlysecure.keychain.pgp.UncachedPublicKey; +import org.sufficientlysecure.keychain.pgp.exception.PgpGeneralException; +import org.sufficientlysecure.keychain.service.OperationResultParcel; +import org.sufficientlysecure.keychain.service.SaveKeyringParcel; +import org.sufficientlysecure.keychain.support.KeyringTestingHelper.RawPacket; +import org.sufficientlysecure.keychain.util.ProgressScaler; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +@RunWith(RobolectricTestRunner.class) +@org.robolectric.annotation.Config(emulateSdk = 18) // Robolectric doesn't yet support 19 +public class UncachedKeyringTest { + + static UncachedKeyRing staticRing, staticPubRing; + UncachedKeyRing ring, pubRing; + ArrayList onlyA = new ArrayList(); + ArrayList onlyB = new ArrayList(); + OperationResultParcel.OperationLog log = new OperationResultParcel.OperationLog(); + PgpKeyOperation op; + SaveKeyringParcel parcel; + + @BeforeClass + public static void setUpOnce() throws Exception { + ShadowLog.stream = System.out; + + SaveKeyringParcel parcel = new SaveKeyringParcel(); + parcel.mAddSubKeys.add(new SaveKeyringParcel.SubkeyAdd( + Constants.choice.algorithm.rsa, 1024, KeyFlags.CERTIFY_OTHER, null)); + parcel.mAddSubKeys.add(new SaveKeyringParcel.SubkeyAdd( + Constants.choice.algorithm.rsa, 1024, KeyFlags.SIGN_DATA, null)); + parcel.mAddSubKeys.add(new SaveKeyringParcel.SubkeyAdd( + Constants.choice.algorithm.rsa, 1024, KeyFlags.ENCRYPT_COMMS, null)); + + parcel.mAddUserIds.add("twi"); + parcel.mAddUserIds.add("pink"); + // passphrase is tested in PgpKeyOperationTest, just use empty here + parcel.mNewPassphrase = ""; + PgpKeyOperation op = new PgpKeyOperation(null); + + OperationResultParcel.OperationLog log = new OperationResultParcel.OperationLog(); + staticRing = op.createSecretKeyRing(parcel, log, 0); + staticPubRing = staticRing.extractPublicKeyRing(); + + Assert.assertNotNull("initial test key creation must succeed", staticRing); + + // we sleep here for a second, to make sure all new certificates have different timestamps + Thread.sleep(1000); + } + + + @Before + public void setUp() throws Exception { + // show Log.x messages in system.out + ShadowLog.stream = System.out; + ring = staticRing; + pubRing = staticPubRing; + } + + @Test(expected = UnsupportedOperationException.class) + public void testPublicKeyItRemove() throws Exception { + Iterator it = ring.getPublicKeys(); + it.remove(); + } + + @Test(expected = PgpGeneralException.class) + public void testDecodeFromEmpty() throws Exception { + UncachedKeyRing.decodeFromData(new byte[0]); + } + + @Test + public void testArmorIdentity() throws Exception { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + ring.encodeArmored(out, "OpenKeychain"); + + Assert.assertArrayEquals("armor encoded and decoded ring should be identical to original", + ring.getEncoded(), + UncachedKeyRing.decodeFromData(out.toByteArray()).getEncoded()); + } + + @Test(expected = PgpGeneralException.class) + public void testDecodeEncodeMulti() throws Exception { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + + // encode secret and public ring in here + ring.encodeArmored(out, "OpenKeychain"); + pubRing.encodeArmored(out, "OpenKeychain"); + + List rings = + UncachedKeyRing.fromStream(new ByteArrayInputStream(out.toByteArray())); + Assert.assertEquals("there should be two rings in the stream", 2, rings.size()); + Assert.assertArrayEquals("first ring should be the first we put in", + ring.getEncoded(), rings.get(0).getEncoded()); + Assert.assertArrayEquals("second ring should be the second we put in", + pubRing.getEncoded(), rings.get(1).getEncoded()); + + // this should fail with PgpGeneralException, since it expects exactly one ring + UncachedKeyRing.decodeFromData(out.toByteArray()); + } + + @Test(expected = RuntimeException.class) + public void testPublicAvailableSubkeys() throws Exception { + // can't do this! + pubRing.getAvailableSubkeys(); + } + + @Test(expected = RuntimeException.class) + public void testPublicExtractPublic() throws Exception { + // can't do this, either! + pubRing.extractPublicKeyRing(); + } + +} -- cgit v1.2.3 From 236a502ea75d0cd6f999d0059db7d15f685c2ff2 Mon Sep 17 00:00:00 2001 From: Vincent Breitmoser Date: Sat, 26 Jul 2014 15:51:35 +0200 Subject: generic UncachedKeyRing fixes --- .../keychain/pgp/UncachedKeyRing.java | 49 +++++++++++----------- 1 file changed, 24 insertions(+), 25 deletions(-) diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/pgp/UncachedKeyRing.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/pgp/UncachedKeyRing.java index 91b06324a..b8f582d6c 100644 --- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/pgp/UncachedKeyRing.java +++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/pgp/UncachedKeyRing.java @@ -91,7 +91,7 @@ public class UncachedKeyRing { final Iterator it = mRing.getPublicKeys(); return new Iterator() { public void remove() { - it.remove(); + throw new UnsupportedOperationException(); } public UncachedPublicKey next() { return new UncachedPublicKey(it.next()); @@ -121,42 +121,41 @@ public class UncachedKeyRing { public static UncachedKeyRing decodeFromData(byte[] data) throws PgpGeneralException, IOException { - BufferedInputStream bufferedInput = - new BufferedInputStream(new ByteArrayInputStream(data)); - if (bufferedInput.available() > 0) { - InputStream in = PGPUtil.getDecoderStream(bufferedInput); - PGPObjectFactory objectFactory = new PGPObjectFactory(in); - // get first object in block - Object obj; - if ((obj = objectFactory.nextObject()) != null && obj instanceof PGPKeyRing) { - return new UncachedKeyRing((PGPKeyRing) obj); - } else { - throw new PgpGeneralException("Object not recognized as PGPKeyRing!"); - } - } else { + List parsed = fromStream(new ByteArrayInputStream(data)); + + if (parsed.isEmpty()) { throw new PgpGeneralException("Object not recognized as PGPKeyRing!"); } + if (parsed.size() > 1) { + throw new PgpGeneralException( + "Expected single keyring in stream, found " + parsed.size()); + } + + return parsed.get(0); + } public static List fromStream(InputStream stream) throws PgpGeneralException, IOException { - PGPObjectFactory objectFactory = new PGPObjectFactory(PGPUtil.getDecoderStream(stream)); - List result = new Vector(); - // go through all objects in this block - Object obj; - while ((obj = objectFactory.nextObject()) != null) { - Log.d(Constants.TAG, "Found class: " + obj.getClass()); + while(stream.available() > 0) { + PGPObjectFactory objectFactory = new PGPObjectFactory(PGPUtil.getDecoderStream(stream)); - if (obj instanceof PGPKeyRing) { + // go through all objects in this block + Object obj; + while ((obj = objectFactory.nextObject()) != null) { + Log.d(Constants.TAG, "Found class: " + obj.getClass()); + if (!(obj instanceof PGPKeyRing)) { + throw new PgpGeneralException( + "Bad object of type " + obj.getClass().getName() + " in stream!"); + } result.add(new UncachedKeyRing((PGPKeyRing) obj)); - } else { - Log.e(Constants.TAG, "Object not recognized as PGPKeyRing!"); } } + return result; } @@ -327,7 +326,7 @@ public class UncachedKeyRing { if (cert.getCreationTime().after(now)) { // Creation date in the future? No way! - log.add(LogLevel.WARN, LogType.MSG_KC_REVOKE_BAD_TIME, indent); + log.add(LogLevel.WARN, LogType.MSG_KC_UID_BAD_TIME, indent); modified = PGPPublicKey.removeCertification(modified, zert); badCerts += 1; continue; @@ -335,7 +334,7 @@ public class UncachedKeyRing { if (cert.isLocal()) { // Creation date in the future? No way! - log.add(LogLevel.WARN, LogType.MSG_KC_REVOKE_BAD_LOCAL, indent); + log.add(LogLevel.WARN, LogType.MSG_KC_UID_BAD_LOCAL, indent); modified = PGPPublicKey.removeCertification(modified, zert); badCerts += 1; continue; -- cgit v1.2.3 From 13bfa3b4873d304cce6b223fa3460718c0654071 Mon Sep 17 00:00:00 2001 From: Vincent Breitmoser Date: Sat, 26 Jul 2014 22:15:49 +0200 Subject: test: add tons of tests and fuzzing for UncachedKeyRing.canonicalize --- .../tests/UncachedKeyringCanonicalizeTest.java | 490 +++++++++++++++++++-- 1 file changed, 453 insertions(+), 37 deletions(-) diff --git a/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/tests/UncachedKeyringCanonicalizeTest.java b/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/tests/UncachedKeyringCanonicalizeTest.java index 5724708e1..b7181fdab 100644 --- a/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/tests/UncachedKeyringCanonicalizeTest.java +++ b/OpenKeychain-Test/src/test/java/org/sufficientlysecure/keychain/tests/UncachedKeyringCanonicalizeTest.java @@ -12,6 +12,19 @@ import org.spongycastle.bcpg.Packet; import org.spongycastle.bcpg.PacketTags; import org.spongycastle.bcpg.UserIDPacket; import org.spongycastle.bcpg.sig.KeyFlags; +import org.spongycastle.openpgp.PGPPrivateKey; +import org.spongycastle.openpgp.PGPPublicKey; +import org.spongycastle.openpgp.PGPSecretKey; +import org.spongycastle.openpgp.PGPSecretKeyRing; +import org.spongycastle.openpgp.PGPSignature; +import org.spongycastle.openpgp.PGPSignatureGenerator; +import org.spongycastle.openpgp.PGPSignatureSubpacketGenerator; +import org.spongycastle.openpgp.PGPUtil; +import org.spongycastle.openpgp.operator.PBESecretKeyDecryptor; +import org.spongycastle.openpgp.operator.PGPContentSignerBuilder; +import org.spongycastle.openpgp.operator.jcajce.JcaKeyFingerprintCalculator; +import org.spongycastle.openpgp.operator.jcajce.JcaPGPContentSignerBuilder; +import org.spongycastle.openpgp.operator.jcajce.JcePBESecretKeyDecryptorBuilder; import org.sufficientlysecure.keychain.Constants; import org.sufficientlysecure.keychain.pgp.PgpKeyOperation; import org.sufficientlysecure.keychain.pgp.UncachedKeyRing; @@ -24,8 +37,16 @@ import org.sufficientlysecure.keychain.support.KeyringTestingHelper.RawPacket; import java.io.ByteArrayInputStream; import java.util.ArrayList; +import java.util.Date; import java.util.Iterator; + +/** Tests for the UncachedKeyring.canonicalize method. + * + * This is a complex and crypto-relevant method, which takes care of sanitizing keyrings. + * Test cases are made for all its assertions. + */ + @RunWith(RobolectricTestRunner.class) @org.robolectric.annotation.Config(emulateSdk = 18) // Robolectric doesn't yet support 19 public class UncachedKeyringCanonicalizeTest { @@ -36,6 +57,8 @@ public class UncachedKeyringCanonicalizeTest { ArrayList onlyA = new ArrayList(); ArrayList onlyB = new ArrayList(); OperationResultParcel.OperationLog log = new OperationResultParcel.OperationLog(); + PGPSignatureSubpacketGenerator subHashedPacketsGen; + PGPSecretKey secretKey; @BeforeClass public static void setUpOnce() throws Exception { @@ -71,8 +94,13 @@ public class UncachedKeyringCanonicalizeTest { // show Log.x messages in system.out ShadowLog.stream = System.out; ring = staticRing; + + subHashedPacketsGen = new PGPSignatureSubpacketGenerator(); + secretKey = new PGPSecretKeyRing(ring.getEncoded(), new JcaKeyFingerprintCalculator()) + .getSecretKey(); } + /** Make sure the assumptions made about the generated ring packet structure are valid. */ @Test public void testGeneratedRingStructure() throws Exception { Iterator it = KeyringTestingHelper.parseKeyring(ring.getEncoded()); @@ -107,43 +135,6 @@ public class UncachedKeyringCanonicalizeTest { } - @Test public void testBrokenSignature() throws Exception { - - byte[] brokenSig; - { - UncachedPublicKey masterKey = ring.getPublicKey(); - WrappedSignature sig = masterKey.getSignaturesForId("twi").next(); - brokenSig = sig.getEncoded(); - // break the signature - brokenSig[brokenSig.length - 5] += 1; - } - - byte[] reng = ring.getEncoded(); - for(int i = 0; i < totalPackets; i++) { - - byte[] brokenBytes = KeyringTestingHelper.injectPacket(reng, brokenSig, i); - Assert.assertEquals("broken ring must be original + injected size", - reng.length + brokenSig.length, brokenBytes.length); - - try { - UncachedKeyRing brokenRing = UncachedKeyRing.decodeFromData(brokenBytes); - - brokenRing = brokenRing.canonicalize(log, 0); - if (brokenRing == null) { - System.out.println("ok, canonicalization failed."); - continue; - } - - Assert.assertArrayEquals("injected bad signature must be gone after canonicalization", - ring.getEncoded(), brokenRing.getEncoded()); - - } catch (Exception e) { - System.out.println("ok, rejected with: " + e.getMessage()); - } - } - - } - @Test public void testUidSignature() throws Exception { UncachedPublicKey masterKey = ring.getPublicKey(); @@ -206,4 +197,429 @@ public class UncachedKeyringCanonicalizeTest { } + @Test public void testUidDestroy() throws Exception { + + // signature for "twi" + ring = KeyringTestingHelper.removePacket(ring, 2); + // signature for "pink" + ring = KeyringTestingHelper.removePacket(ring, 3); + + // canonicalization should fail, because there are no valid uids left + UncachedKeyRing canonicalized = ring.canonicalize(log, 0); + Assert.assertNull("canonicalization of keyring with no valid uids should fail", canonicalized); + + } + + @Test public void testRevocationRedundant() throws Exception { + + PGPSignature revocation = forgeSignature( + secretKey, PGPSignature.KEY_REVOCATION, subHashedPacketsGen, secretKey.getPublicKey()); + + UncachedKeyRing modified = KeyringTestingHelper.injectPacket(ring, revocation.getEncoded(), 1); + + // try to add the same packet again, it should be rejected in all positions + injectEverywhere(modified, revocation.getEncoded()); + + // an older (but different!) revocation should be rejected as well + subHashedPacketsGen.setSignatureCreationTime(false, new Date(new Date().getTime() -1000*1000)); + revocation = forgeSignature( + secretKey, PGPSignature.KEY_REVOCATION, subHashedPacketsGen, secretKey.getPublicKey()); + + injectEverywhere(modified, revocation.getEncoded()); + + } + + @Test public void testUidRedundant() throws Exception { + + // an older uid certificate should be rejected + subHashedPacketsGen.setSignatureCreationTime(false, new Date(new Date().getTime() -1000*1000)); + PGPSignature revocation = forgeSignature( + secretKey, PGPSignature.DEFAULT_CERTIFICATION, subHashedPacketsGen, "twi", secretKey.getPublicKey()); + + injectEverywhere(ring, revocation.getEncoded()); + + } + + @Test public void testUidRevocationOutdated() throws Exception { + // an older uid revocation cert should be rejected + subHashedPacketsGen.setSignatureCreationTime(false, new Date(new Date().getTime() -1000*1000)); + PGPSignature revocation = forgeSignature( + secretKey, PGPSignature.CERTIFICATION_REVOCATION, subHashedPacketsGen, "twi", secretKey.getPublicKey()); + + injectEverywhere(ring, revocation.getEncoded()); + + } + + @Test public void testUidRevocationRedundant() throws Exception { + + PGPSignature revocation = forgeSignature( + secretKey, PGPSignature.CERTIFICATION_REVOCATION, subHashedPacketsGen, "twi", secretKey.getPublicKey()); + + // add that revocation to the base, and check if the redundant one will be rejected as well + UncachedKeyRing modified = KeyringTestingHelper.injectPacket(ring, revocation.getEncoded(), 2); + + injectEverywhere(modified, revocation.getEncoded()); + + // an older (but different!) uid revocation should be rejected as well + subHashedPacketsGen.setSignatureCreationTime(false, new Date(new Date().getTime() -1000*1000)); + revocation = forgeSignature( + secretKey, PGPSignature.CERTIFICATION_REVOCATION, subHashedPacketsGen, "twi", secretKey.getPublicKey()); + + injectEverywhere(modified, revocation.getEncoded()); + + } + + @Test public void testSignatureBroken() throws Exception { + + injectEverytype(secretKey, ring, subHashedPacketsGen, true); + + } + + @Test public void testForeignSignature() throws Exception { + + SaveKeyringParcel parcel = new SaveKeyringParcel(); + parcel.mAddSubKeys.add(new SaveKeyringParcel.SubkeyAdd( + Constants.choice.algorithm.rsa, 1024, KeyFlags.CERTIFY_OTHER, null)); + parcel.mAddUserIds.add("trix"); + PgpKeyOperation op = new PgpKeyOperation(null); + + OperationResultParcel.OperationLog log = new OperationResultParcel.OperationLog(); + UncachedKeyRing foreign = op.createSecretKeyRing(parcel, log, 0); + + Assert.assertNotNull("initial test key creation must succeed", foreign); + PGPSecretKey foreignSecretKey = + new PGPSecretKeyRing(foreign.getEncoded(), new JcaKeyFingerprintCalculator()) + .getSecretKey(); + + injectEverytype(foreignSecretKey, ring, subHashedPacketsGen); + + } + + @Test public void testSignatureFuture() throws Exception { + + // generate future + subHashedPacketsGen.setSignatureCreationTime(false, new Date(new Date().getTime() + 1000 * 1000)); + + injectEverytype(secretKey, ring, subHashedPacketsGen); + + + } + + @Test public void testSignatureLocal() throws Exception { + + // generate future + subHashedPacketsGen.setSignatureCreationTime(false, new Date()); + subHashedPacketsGen.setExportable(false, false); + + injectEverytype(secretKey, ring, subHashedPacketsGen); + + } + + @Test public void testSubkeyDestroy() throws Exception { + + // signature for second key (first subkey) + UncachedKeyRing modified = KeyringTestingHelper.removePacket(ring, 6); + + // canonicalization should fail, because there are no valid uids left + UncachedKeyRing canonicalized = modified.canonicalize(log, 0); + Assert.assertTrue("keyring with missing subkey binding sig should differ from intact one after canonicalization", + KeyringTestingHelper.diffKeyrings(ring.getEncoded(), canonicalized.getEncoded(), + onlyA, onlyB) + ); + + Assert.assertEquals("canonicalized keyring should have two extra packets", 2, onlyA.size()); + Assert.assertEquals("canonicalized keyring should have no extra packets", 0, onlyB.size()); + + Assert.assertEquals("first missing packet should be the subkey", + PacketTags.SECRET_SUBKEY, onlyA.get(0).tag); + Assert.assertEquals("second missing packet should be subkey's signature", + PacketTags.SIGNATURE, onlyA.get(1).tag); + Assert.assertEquals("second missing packet should be next to subkey", + onlyA.get(0).position + 1, onlyA.get(1).position); + + } + + @Test public void testSubkeyBindingNoPKB() throws Exception { + + UncachedPublicKey pKey = KeyringTestingHelper.getNth(ring.getPublicKeys(), 1); + Assert.assertTrue("second subkey must be able to sign", pKey.canSign()); + + PGPSignature sig; + + subHashedPacketsGen.setKeyFlags(false, KeyFlags.SIGN_DATA); + + { + // forge a (newer) signature, which has the sign flag but no primary key binding sig + PGPSignatureSubpacketGenerator unhashedSubs = new PGPSignatureSubpacketGenerator(); + + // just add any random signature, because why not + unhashedSubs.setEmbeddedSignature(false, forgeSignature( + secretKey, PGPSignature.POSITIVE_CERTIFICATION, subHashedPacketsGen, + secretKey.getPublicKey() + ) + ); + + sig = forgeSignature( + secretKey, PGPSignature.SUBKEY_BINDING, subHashedPacketsGen, unhashedSubs, + secretKey.getPublicKey(), pKey.getPublicKey()); + + // inject in the right position + UncachedKeyRing modified = KeyringTestingHelper.injectPacket(ring, sig.getEncoded(), 6); + + // canonicalize, and check if we lose the bad signature + UncachedKeyRing canonicalized = modified.canonicalize(log, 0); + Assert.assertFalse("subkey binding signature should be gone after canonicalization", + KeyringTestingHelper.diffKeyrings(ring.getEncoded(), canonicalized.getEncoded(), + onlyA, onlyB) + ); + } + + { // now try one with a /bad/ primary key binding signature + + PGPSignatureSubpacketGenerator unhashedSubs = new PGPSignatureSubpacketGenerator(); + // this one is signed by the primary key itself, not the subkey - but it IS primary binding + unhashedSubs.setEmbeddedSignature(false, forgeSignature( + secretKey, PGPSignature.PRIMARYKEY_BINDING, subHashedPacketsGen, + secretKey.getPublicKey(), pKey.getPublicKey() + ) + ); + + sig = forgeSignature( + secretKey, PGPSignature.SUBKEY_BINDING, subHashedPacketsGen, unhashedSubs, + secretKey.getPublicKey(), pKey.getPublicKey()); + + // inject in the right position + UncachedKeyRing modified = KeyringTestingHelper.injectPacket(ring, sig.getEncoded(), 6); + + // canonicalize, and check if we lose the bad signature + UncachedKeyRing canonicalized = modified.canonicalize(log, 0); + Assert.assertFalse("subkey binding signature should be gone after canonicalization", + KeyringTestingHelper.diffKeyrings(ring.getEncoded(), canonicalized.getEncoded(), + onlyA, onlyB) + ); + } + + } + + @Test public void testSubkeyBindingRedundant() throws Exception { + + UncachedPublicKey pKey = KeyringTestingHelper.getNth(ring.getPublicKeys(), 2); + + subHashedPacketsGen.setKeyFlags(false, KeyFlags.ENCRYPT_COMMS); + PGPSignature sig2 = forgeSignature( + secretKey, PGPSignature.SUBKEY_BINDING, subHashedPacketsGen, + secretKey.getPublicKey(), pKey.getPublicKey()); + + subHashedPacketsGen.setSignatureCreationTime(false, new Date(new Date().getTime() -1000*1000)); + PGPSignature sig1 = forgeSignature( + secretKey, PGPSignature.SUBKEY_REVOCATION, subHashedPacketsGen, + secretKey.getPublicKey(), pKey.getPublicKey()); + + subHashedPacketsGen = new PGPSignatureSubpacketGenerator(); + subHashedPacketsGen.setSignatureCreationTime(false, new Date(new Date().getTime() -100*1000)); + PGPSignature sig3 = forgeSignature( + secretKey, PGPSignature.SUBKEY_BINDING, subHashedPacketsGen, + secretKey.getPublicKey(), pKey.getPublicKey()); + + UncachedKeyRing modified = KeyringTestingHelper.injectPacket(ring, sig1.getEncoded(), 8); + modified = KeyringTestingHelper.injectPacket(modified, sig2.getEncoded(), 9); + modified = KeyringTestingHelper.injectPacket(modified, sig1.getEncoded(), 10); + modified = KeyringTestingHelper.injectPacket(modified, sig3.getEncoded(), 11); + + // canonicalize, and check if we lose the bad signature + UncachedKeyRing canonicalized = modified.canonicalize(log, 0); + Assert.assertTrue("subkey binding signature should be gone after canonicalization", + KeyringTestingHelper.diffKeyrings(modified.getEncoded(), canonicalized.getEncoded(), + onlyA, onlyB) + ); + + Assert.assertEquals("canonicalized keyring should have lost two packets", 3, onlyA.size()); + Assert.assertEquals("canonicalized keyring should have no extra packets", 0, onlyB.size()); + + Assert.assertEquals("first missing packet should be the subkey", + PacketTags.SIGNATURE, onlyA.get(0).tag); + Assert.assertEquals("second missing packet should be a signature", + PacketTags.SIGNATURE, onlyA.get(1).tag); + Assert.assertEquals("second missing packet should be a signature", + PacketTags.SIGNATURE, onlyA.get(2).tag); + + } + + private static final int[] sigtypes_direct = new int[] { + PGPSignature.KEY_REVOCATION, + PGPSignature.DIRECT_KEY, + }; + private static final int[] sigtypes_uid = new int[] { + PGPSignature.DEFAULT_CERTIFICATION, + PGPSignature.NO_CERTIFICATION, + PGPSignature.CASUAL_CERTIFICATION, + PGPSignature.POSITIVE_CERTIFICATION, + PGPSignature.CERTIFICATION_REVOCATION, + }; + private static final int[] sigtypes_subkey = new int[] { + PGPSignature.SUBKEY_BINDING, + PGPSignature.PRIMARYKEY_BINDING, + PGPSignature.SUBKEY_REVOCATION, + }; + + private static void injectEverytype(PGPSecretKey secretKey, + UncachedKeyRing ring, + PGPSignatureSubpacketGenerator subHashedPacketsGen) + throws Exception { + injectEverytype(secretKey, ring, subHashedPacketsGen, false); + } + + private static void injectEverytype(PGPSecretKey secretKey, + UncachedKeyRing ring, + PGPSignatureSubpacketGenerator subHashedPacketsGen, + boolean breakSig) + throws Exception { + + for (int sigtype : sigtypes_direct) { + PGPSignature sig = forgeSignature( + secretKey, sigtype, subHashedPacketsGen, secretKey.getPublicKey()); + byte[] encoded = sig.getEncoded(); + if (breakSig) { + encoded[encoded.length-10] += 1; + } + injectEverywhere(ring, encoded); + } + + for (int sigtype : sigtypes_uid) { + PGPSignature sig = forgeSignature( + secretKey, sigtype, subHashedPacketsGen, "twi", secretKey.getPublicKey()); + + byte[] encoded = sig.getEncoded(); + if (breakSig) { + encoded[encoded.length-10] += 1; + } + injectEverywhere(ring, encoded); + } + + for (int sigtype : sigtypes_subkey) { + PGPSignature sig = forgeSignature( + secretKey, sigtype, subHashedPacketsGen, + secretKey.getPublicKey(), secretKey.getPublicKey()); + + byte[] encoded = sig.getEncoded(); + if (breakSig) { + encoded[encoded.length-10] += 1; + } + injectEverywhere(ring, encoded); + } + + } + + private static void injectEverywhere(UncachedKeyRing ring, byte[] packet) throws Exception { + + OperationResultParcel.OperationLog log = new OperationResultParcel.OperationLog(); + + byte[] encodedRing = ring.getEncoded(); + + for(int i = 0; i < totalPackets; i++) { + + byte[] brokenEncoded = KeyringTestingHelper.injectPacket(encodedRing, packet, i); + + try { + + UncachedKeyRing brokenRing = UncachedKeyRing.decodeFromData(brokenEncoded); + + brokenRing = brokenRing.canonicalize(log, 0); + if (brokenRing == null) { + System.out.println("ok, canonicalization failed."); + continue; + } + + Assert.assertArrayEquals("injected bad signature must be gone after canonicalization", + ring.getEncoded(), brokenRing.getEncoded()); + + } catch (Exception e) { + System.out.println("ok, rejected with: " + e.getMessage()); + } + } + + } + + private static PGPSignature forgeSignature(PGPSecretKey key, int type, + PGPSignatureSubpacketGenerator subpackets, + PGPPublicKey publicKey) + throws Exception { + + PBESecretKeyDecryptor keyDecryptor = new JcePBESecretKeyDecryptorBuilder().setProvider( + Constants.BOUNCY_CASTLE_PROVIDER_NAME).build("".toCharArray()); + PGPPrivateKey privateKey = key.extractPrivateKey(keyDecryptor); + + PGPContentSignerBuilder signerBuilder = new JcaPGPContentSignerBuilder( + publicKey.getAlgorithm(), PGPUtil.SHA1) + .setProvider(Constants.BOUNCY_CASTLE_PROVIDER_NAME); + + PGPSignatureGenerator sGen = new PGPSignatureGenerator(signerBuilder); + sGen.setHashedSubpackets(subpackets.generate()); + sGen.init(type, privateKey); + return sGen.generateCertification(publicKey); + + } + + private static PGPSignature forgeSignature(PGPSecretKey key, int type, + PGPSignatureSubpacketGenerator subpackets, + String userId, PGPPublicKey publicKey) + throws Exception { + + PBESecretKeyDecryptor keyDecryptor = new JcePBESecretKeyDecryptorBuilder().setProvider( + Constants.BOUNCY_CASTLE_PROVIDER_NAME).build("".toCharArray()); + PGPPrivateKey privateKey = key.extractPrivateKey(keyDecryptor); + + PGPContentSignerBuilder signerBuilder = new JcaPGPContentSignerBuilder( + publicKey.getAlgorithm(), PGPUtil.SHA1) + .setProvider(Constants.BOUNCY_CASTLE_PROVIDER_NAME); + + PGPSignatureGenerator sGen = new PGPSignatureGenerator(signerBuilder); + sGen.setHashedSubpackets(subpackets.generate()); + sGen.init(type, privateKey); + return sGen.generateCertification(userId, publicKey); + + } + + private static PGPSignature forgeSignature(PGPSecretKey key, int type, + PGPSignatureSubpacketGenerator subpackets, + PGPPublicKey publicKey, PGPPublicKey signedKey) + throws Exception { + + PBESecretKeyDecryptor keyDecryptor = new JcePBESecretKeyDecryptorBuilder().setProvider( + Constants.BOUNCY_CASTLE_PROVIDER_NAME).build("".toCharArray()); + PGPPrivateKey privateKey = key.extractPrivateKey(keyDecryptor); + + PGPContentSignerBuilder signerBuilder = new JcaPGPContentSignerBuilder( + publicKey.getAlgorithm(), PGPUtil.SHA1) + .setProvider(Constants.BOUNCY_CASTLE_PROVIDER_NAME); + + PGPSignatureGenerator sGen = new PGPSignatureGenerator(signerBuilder); + sGen.setHashedSubpackets(subpackets.generate()); + sGen.init(type, privateKey); + return sGen.generateCertification(publicKey, signedKey); + + } + + private static PGPSignature forgeSignature(PGPSecretKey key, int type, + PGPSignatureSubpacketGenerator hashedSubs, + PGPSignatureSubpacketGenerator unhashedSubs, + PGPPublicKey publicKey, PGPPublicKey signedKey) + throws Exception { + + PBESecretKeyDecryptor keyDecryptor = new JcePBESecretKeyDecryptorBuilder().setProvider( + Constants.BOUNCY_CASTLE_PROVIDER_NAME).build("".toCharArray()); + PGPPrivateKey privateKey = key.extractPrivateKey(keyDecryptor); + + PGPContentSignerBuilder signerBuilder = new JcaPGPContentSignerBuilder( + publicKey.getAlgorithm(), PGPUtil.SHA1) + .setProvider(Constants.BOUNCY_CASTLE_PROVIDER_NAME); + + PGPSignatureGenerator sGen = new PGPSignatureGenerator(signerBuilder); + sGen.setHashedSubpackets(hashedSubs.generate()); + sGen.setUnhashedSubpackets(unhashedSubs.generate()); + sGen.init(type, privateKey); + return sGen.generateCertification(publicKey, signedKey); + + } + } -- cgit v1.2.3 From 45722d7cfbb2996ff994b3f2143e5871c2e564ba Mon Sep 17 00:00:00 2001 From: Vincent Breitmoser Date: Sat, 26 Jul 2014 22:16:33 +0200 Subject: canonicalize: couple of fixes --- .../keychain/pgp/UncachedKeyRing.java | 40 ++++++++++++++++------ .../keychain/pgp/WrappedSecretKey.java | 8 ----- 2 files changed, 30 insertions(+), 18 deletions(-) diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/pgp/UncachedKeyRing.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/pgp/UncachedKeyRing.java index b8f582d6c..8838075cd 100644 --- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/pgp/UncachedKeyRing.java +++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/pgp/UncachedKeyRing.java @@ -23,13 +23,11 @@ import org.sufficientlysecure.keychain.service.OperationResultParcel.LogType; import org.sufficientlysecure.keychain.util.IterableIterator; import org.sufficientlysecure.keychain.util.Log; -import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; -import java.util.ArrayList; import java.util.Comparator; import java.util.Date; import java.util.HashSet; @@ -514,14 +512,16 @@ public class UncachedKeyRing { continue; } + // if this certificate says it allows signing for the key if (zert.getHashedSubPackets().hasSubpacket(SignatureSubpacketTags.KEY_FLAGS)) { + int flags = ((KeyFlags) zert.getHashedSubPackets() .getSubpacket(SignatureSubpacketTags.KEY_FLAGS)).getFlags(); - // If this subkey is allowed to sign data, if ((flags & PGPKeyFlags.CAN_SIGN) == PGPKeyFlags.CAN_SIGN) { + boolean ok = false; + // it MUST have an embedded primary key binding signature try { PGPSignatureList list = zert.getUnhashedSubPackets().getEmbeddedSignatures(); - boolean ok = false; for (int i = 0; i < list.size(); i++) { WrappedSignature subsig = new WrappedSignature(list.get(i)); if (subsig.getSignatureType() == PGPSignature.PRIMARYKEY_BINDING) { @@ -535,17 +535,19 @@ public class UncachedKeyRing { } } } - if (!ok) { - log.add(LogLevel.WARN, LogType.MSG_KC_SUB_PRIMARY_NONE, indent); - badCerts += 1; - continue; - } } catch (Exception e) { log.add(LogLevel.WARN, LogType.MSG_KC_SUB_PRIMARY_BAD_ERR, indent); badCerts += 1; continue; } + // if it doesn't, get rid of this! + if (!ok) { + log.add(LogLevel.WARN, LogType.MSG_KC_SUB_PRIMARY_NONE, indent); + badCerts += 1; + continue; + } } + } // if we already have a cert, and this one is not newer: skip it @@ -558,6 +560,8 @@ public class UncachedKeyRing { selfCert = zert; // if this is newer than a possibly existing revocation, drop that one if (revocation != null && selfCert.getCreationTime().after(revocation.getCreationTime())) { + log.add(LogLevel.DEBUG, LogType.MSG_KC_SUB_REVOKE_DUP, indent); + redundantCerts += 1; revocation = null; } @@ -591,7 +595,7 @@ public class UncachedKeyRing { // it is not properly bound? error! if (selfCert == null) { - ring = replacePublicKey(ring, modified); + ring = removeSubKey(ring, key); log.add(LogLevel.ERROR, LogType.MSG_KC_SUB_NO_CERT, indent, PgpKeyHelper.convertKeyIdToHex(key.getKeyID())); @@ -803,4 +807,20 @@ public class UncachedKeyRing { return PGPSecretKeyRing.insertSecretKey(secRing, sKey); } + /** This method removes a subkey in a keyring. + * + * This method essentially wraps PGP*KeyRing.remove*Key, where the keyring may be of either + * the secret or public subclass. + * + * @return the resulting PGPKeyRing of the same type as the input + */ + private static PGPKeyRing removeSubKey(PGPKeyRing ring, PGPPublicKey key) { + if (ring instanceof PGPPublicKeyRing) { + return PGPPublicKeyRing.removePublicKey((PGPPublicKeyRing) ring, key); + } else { + PGPSecretKey sKey = ((PGPSecretKeyRing) ring).getSecretKey(key.getKeyID()); + return PGPSecretKeyRing.removeSecretKey((PGPSecretKeyRing) ring, sKey); + } + } + } diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/pgp/WrappedSecretKey.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/pgp/WrappedSecretKey.java index 98ad2b706..f0485d801 100644 --- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/pgp/WrappedSecretKey.java +++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/pgp/WrappedSecretKey.java @@ -51,14 +51,6 @@ public class WrappedSecretKey extends WrappedPublicKey { return (WrappedSecretKeyRing) mRing; } - /** Returns the wrapped PGPSecretKeyRing. - * This function is for compatibility only, should not be used anymore and will be removed - */ - @Deprecated - public PGPSecretKey getKeyExternal() { - return mSecretKey; - } - public boolean unlock(String passphrase) throws PgpGeneralException { try { PBESecretKeyDecryptor keyDecryptor = new JcePBESecretKeyDecryptorBuilder().setProvider( -- cgit v1.2.3 From a8782272b3db20ba6e88acab1d035d4699aa7166 Mon Sep 17 00:00:00 2001 From: Vincent Breitmoser Date: Sun, 27 Jul 2014 00:46:38 +0200 Subject: some more work on supertoast and result parcel stuff --- .../keychain/pgp/PgpImportExport.java | 22 ++++----- .../remote/ui/AccountSettingsFragment.java | 11 ++--- .../keychain/service/KeychainIntentService.java | 3 +- .../keychain/service/OperationResultParcel.java | 8 ---- .../keychain/service/OperationResults.java | 42 ++++++++++++----- .../keychain/ui/EditKeyActivity.java | 2 +- .../keychain/ui/EditKeyFragment.java | 14 ++++-- .../keychain/ui/ImportKeysActivity.java | 8 ++-- .../keychain/ui/KeyListFragment.java | 7 +-- .../keychain/ui/ViewKeyActivity.java | 2 - .../src/main/res/layout/edit_key_activity.xml | 53 +++++----------------- .../src/main/res/layout/edit_key_activity_new.xml | 13 ------ .../src/main/res/layout/key_list_activity.xml | 15 +++--- OpenKeychain/src/main/res/layout/notify_area.xml | 1 - .../src/main/res/layout/view_key_activity.xml | 6 +-- 15 files changed, 87 insertions(+), 120 deletions(-) delete mode 100644 OpenKeychain/src/main/res/layout/edit_key_activity_new.xml diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpImportExport.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpImportExport.java index 6fc55cfb8..9d334d9bd 100644 --- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpImportExport.java +++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/pgp/PgpImportExport.java @@ -34,7 +34,7 @@ import org.sufficientlysecure.keychain.provider.KeychainContract; import org.sufficientlysecure.keychain.provider.ProviderHelper; import org.sufficientlysecure.keychain.service.KeychainIntentService; import org.sufficientlysecure.keychain.service.OperationResultParcel.OperationLog; -import org.sufficientlysecure.keychain.service.OperationResults.ImportResult; +import org.sufficientlysecure.keychain.service.OperationResults.ImportKeyResult; import org.sufficientlysecure.keychain.service.OperationResults.SaveKeyringResult; import org.sufficientlysecure.keychain.util.Log; import org.sufficientlysecure.keychain.util.ProgressScaler; @@ -123,14 +123,14 @@ public class PgpImportExport { } /** Imports keys from given data. If keyIds is given only those are imported */ - public ImportResult importKeyRings(List entries) { + public ImportKeyResult importKeyRings(List entries) { updateProgress(R.string.progress_importing, 0, 100); // If there aren't even any keys, do nothing here. if (entries == null || entries.size() == 0) { - return new ImportResult( - ImportResult.RESULT_FAIL_NOTHING, mProviderHelper.getLog(), 0, 0, 0); + return new ImportKeyResult( + ImportKeyResult.RESULT_FAIL_NOTHING, mProviderHelper.getLog(), 0, 0, 0); } int newKeys = 0, oldKeys = 0, badKeys = 0; @@ -185,26 +185,26 @@ public class PgpImportExport { int resultType = 0; // special return case: no new keys at all if (badKeys == 0 && newKeys == 0 && oldKeys == 0) { - resultType = ImportResult.RESULT_FAIL_NOTHING; + resultType = ImportKeyResult.RESULT_FAIL_NOTHING; } else { if (newKeys > 0) { - resultType |= ImportResult.RESULT_OK_NEWKEYS; + resultType |= ImportKeyResult.RESULT_OK_NEWKEYS; } if (oldKeys > 0) { - resultType |= ImportResult.RESULT_OK_UPDATED; + resultType |= ImportKeyResult.RESULT_OK_UPDATED; } if (badKeys > 0) { - resultType |= ImportResult.RESULT_WITH_ERRORS; + resultType |= ImportKeyResult.RESULT_WITH_ERRORS; if (newKeys == 0 && oldKeys == 0) { - resultType |= ImportResult.RESULT_ERROR; + resultType |= ImportKeyResult.RESULT_ERROR; } } if (log.containsWarnings()) { - resultType |= ImportResult.RESULT_WITH_WARNINGS; + resultType |= ImportKeyResult.RESULT_WITH_WARNINGS; } } - return new ImportResult(resultType, log, newKeys, oldKeys, badKeys); + return new ImportKeyResult(resultType, log, newKeys, oldKeys, badKeys); } diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AccountSettingsFragment.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AccountSettingsFragment.java index 0b1d521ad..86460c45d 100644 --- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AccountSettingsFragment.java +++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/remote/ui/AccountSettingsFragment.java @@ -35,7 +35,7 @@ import org.sufficientlysecure.keychain.R; import org.sufficientlysecure.keychain.pgp.exception.PgpGeneralException; import org.sufficientlysecure.keychain.provider.ProviderHelper; import org.sufficientlysecure.keychain.remote.AccountSettings; -import org.sufficientlysecure.keychain.ui.EditKeyActivityOld; +import org.sufficientlysecure.keychain.ui.CreateKeyActivity; import org.sufficientlysecure.keychain.ui.SelectSecretKeyLayoutFragment; import org.sufficientlysecure.keychain.ui.adapter.KeyValueSpinnerAdapter; import org.sufficientlysecure.keychain.util.AlgorithmNames; @@ -163,12 +163,9 @@ public class AccountSettingsFragment extends Fragment implements } private void createKey() { - Intent intent = new Intent(getActivity(), EditKeyActivityOld.class); - intent.setAction(EditKeyActivityOld.ACTION_CREATE_KEY); - intent.putExtra(EditKeyActivityOld.EXTRA_GENERATE_DEFAULT_KEYS, true); - // set default user id to account name - intent.putExtra(EditKeyActivityOld.EXTRA_USER_IDS, mAccSettings.getAccountName()); - startActivityForResult(intent, REQUEST_CODE_CREATE_KEY); + Intent intent = new Intent(getActivity(), CreateKeyActivity.class); + // startActivityForResult(intent, REQUEST_CODE_CREATE_KEY); + startActivity(intent); } @Override diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java index 9a4cef2f1..f6a269e24 100644 --- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java +++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/service/KeychainIntentService.java @@ -53,6 +53,7 @@ import org.sufficientlysecure.keychain.provider.KeychainContract.KeyRings; import org.sufficientlysecure.keychain.provider.KeychainDatabase; import org.sufficientlysecure.keychain.provider.ProviderHelper; import org.sufficientlysecure.keychain.service.OperationResultParcel.OperationLog; +import org.sufficientlysecure.keychain.service.OperationResults.ImportKeyResult; import org.sufficientlysecure.keychain.util.InputData; import org.sufficientlysecure.keychain.util.Log; import org.sufficientlysecure.keychain.util.ProgressScaler; @@ -390,7 +391,7 @@ public class KeychainIntentService extends IntentService List entries = data.getParcelableArrayList(IMPORT_KEY_LIST); PgpImportExport pgpImportExport = new PgpImportExport(this, this); - OperationResults.ImportResult result = pgpImportExport.importKeyRings(entries); + ImportKeyResult result = pgpImportExport.importKeyRings(entries); Bundle resultData = new Bundle(); resultData.putParcelable(RESULT, result); diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/service/OperationResultParcel.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/service/OperationResultParcel.java index d80c508c3..2c6c29f8d 100644 --- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/service/OperationResultParcel.java +++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/service/OperationResultParcel.java @@ -391,14 +391,6 @@ public class OperationResultParcel implements Parcelable { mParcels.add(new OperationResultParcel.LogEntryParcel(level, type, indent, (Object[]) null)); } - public LogEntryParcel getResultId() { - LogEntryParcel entry = get(size()-1); - if (entry.mLevel != LogLevel.OK && entry.mLevel != LogLevel.ERROR) { - return new LogEntryParcel(LogLevel.ERROR, LogType.INTERNAL_ERROR, 0); - } - return entry; - } - public boolean containsWarnings() { for(LogEntryParcel entry : new IterableIterator(mParcels.iterator())) { if (entry.mLevel == LogLevel.WARN || entry.mLevel == LogLevel.ERROR) { diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/service/OperationResults.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/service/OperationResults.java index 39c11a855..fcb6c027d 100644 --- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/service/OperationResults.java +++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/service/OperationResults.java @@ -12,12 +12,13 @@ import com.github.johnpersano.supertoasts.util.OnClickWrapper; import com.github.johnpersano.supertoasts.util.Style; import org.sufficientlysecure.keychain.R; +import org.sufficientlysecure.keychain.pgp.UncachedKeyRing; import org.sufficientlysecure.keychain.ui.LogDisplayActivity; import org.sufficientlysecure.keychain.ui.LogDisplayFragment; public abstract class OperationResults { - public static class ImportResult extends OperationResultParcel { + public static class ImportKeyResult extends OperationResultParcel { public final int mNewKeys, mUpdatedKeys, mBadKeys; @@ -47,15 +48,15 @@ public abstract class OperationResults { return (mResult & RESULT_FAIL_NOTHING) == RESULT_FAIL_NOTHING; } - public ImportResult(Parcel source) { + public ImportKeyResult(Parcel source) { super(source); mNewKeys = source.readInt(); mUpdatedKeys = source.readInt(); mBadKeys = source.readInt(); } - public ImportResult(int result, OperationLog log, - int newKeys, int updatedKeys, int badKeys) { + public ImportKeyResult(int result, OperationLog log, + int newKeys, int updatedKeys, int badKeys) { super(result, log); mNewKeys = newKeys; mUpdatedKeys = updatedKeys; @@ -70,13 +71,13 @@ public abstract class OperationResults { dest.writeInt(mBadKeys); } - public static Creator CREATOR = new Creator() { - public ImportResult createFromParcel(final Parcel source) { - return new ImportResult(source); + public static Creator CREATOR = new Creator() { + public ImportKeyResult createFromParcel(final Parcel source) { + return new ImportKeyResult(source); } - public ImportResult[] newArray(final int size) { - return new ImportResult[size]; + public ImportKeyResult[] newArray(final int size) { + return new ImportKeyResult[size]; } }; @@ -92,7 +93,7 @@ public abstract class OperationResults { String withWarnings; // Any warnings? - if ((resultType & ImportResult.RESULT_WITH_WARNINGS) > 0) { + if ((resultType & ImportKeyResult.RESULT_WITH_WARNINGS) > 0) { duration = 0; color = Style.ORANGE; withWarnings = activity.getResources().getString(R.string.import_with_warnings); @@ -151,7 +152,7 @@ public abstract class OperationResults { public void onClick(View view, Parcelable token) { Intent intent = new Intent( activity, LogDisplayActivity.class); - intent.putExtra(LogDisplayFragment.EXTRA_RESULT, ImportResult.this); + intent.putExtra(LogDisplayFragment.EXTRA_RESULT, ImportKeyResult.this); activity.startActivity(intent); } } @@ -164,6 +165,25 @@ public abstract class OperationResults { } + public static class EditKeyResult extends OperationResultParcel { + + public EditKeyResult(Parcel source) { + super(source); + } + + public static Creator CREATOR = new Creator() { + public EditKeyResult createFromParcel(final Parcel source) { + return new EditKeyResult(source); + } + + public EditKeyResult[] newArray(final int size) { + return new EditKeyResult[size]; + } + }; + + } + + public static class SaveKeyringResult extends OperationResultParcel { public SaveKeyringResult(int result, OperationLog log) { diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java index d80425c3c..6ddaec17f 100644 --- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java +++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyActivity.java @@ -33,7 +33,7 @@ public class EditKeyActivity extends ActionBarActivity { public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - setContentView(R.layout.edit_key_activity_new); + setContentView(R.layout.edit_key_activity); Uri dataUri = getIntent().getData(); if (dataUri == null) { diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyFragment.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyFragment.java index b41871a39..8fc4cffb8 100644 --- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyFragment.java +++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/EditKeyFragment.java @@ -48,6 +48,7 @@ import org.sufficientlysecure.keychain.provider.ProviderHelper; import org.sufficientlysecure.keychain.service.KeychainIntentService; import org.sufficientlysecure.keychain.service.KeychainIntentServiceHandler; import org.sufficientlysecure.keychain.service.OperationResults; +import org.sufficientlysecure.keychain.service.OperationResults.ImportKeyResult; import org.sufficientlysecure.keychain.service.PassphraseCacheService; import org.sufficientlysecure.keychain.service.SaveKeyringParcel; import org.sufficientlysecure.keychain.ui.adapter.SubkeysAdapter; @@ -480,12 +481,19 @@ public class EditKeyFragment extends LoaderFragment implements return; } - // if good -> finish, return result to showkey and display there! + // if bad -> display here! + if (!result.success()) { + result.createNotify(getActivity()).show(); + return; + } -// result.displayNotify(ImportKeysActivity.this); + // if good -> finish, return result to showkey and display there! + Intent intent = new Intent(); + intent.putExtra(ImportKeyResult.EXTRA_RESULT, result); + getActivity().setResult(EditKeyActivity.RESULT_OK, intent); + getActivity().finish(); -// getActivity().finish(); } } }; diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysActivity.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysActivity.java index 3ff3b56bf..5ab4d69f1 100644 --- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysActivity.java +++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/ImportKeysActivity.java @@ -45,7 +45,7 @@ import org.sufficientlysecure.keychain.keyimport.ParcelableKeyRing; import org.sufficientlysecure.keychain.pgp.PgpKeyHelper; import org.sufficientlysecure.keychain.service.KeychainIntentService; import org.sufficientlysecure.keychain.service.KeychainIntentServiceHandler; -import org.sufficientlysecure.keychain.service.OperationResults.ImportResult; +import org.sufficientlysecure.keychain.service.OperationResults.ImportKeyResult; import org.sufficientlysecure.keychain.ui.adapter.PagerTabStripAdapter; import org.sufficientlysecure.keychain.ui.widget.SlidingTabLayout; import org.sufficientlysecure.keychain.util.Log; @@ -427,7 +427,7 @@ public class ImportKeysActivity extends ActionBarActivity { if (returnData == null) { return; } - final ImportResult result = + final ImportKeyResult result = returnData.getParcelable(KeychainIntentService.RESULT); if (result == null) { return; @@ -435,7 +435,7 @@ public class ImportKeysActivity extends ActionBarActivity { if (ACTION_IMPORT_KEY_FROM_KEYSERVER_AND_RETURN_RESULT.equals(getIntent().getAction())) { Intent intent = new Intent(); - intent.putExtra(EXTRA_RESULT, result); + intent.putExtra(ImportKeyResult.EXTRA_RESULT, result); ImportKeysActivity.this.setResult(RESULT_OK, intent); ImportKeysActivity.this.finish(); return; @@ -451,7 +451,7 @@ public class ImportKeysActivity extends ActionBarActivity { return; } - result.displayNotify(ImportKeysActivity.this); + result.createNotify(ImportKeysActivity.this).show(); } } }; diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListFragment.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListFragment.java index c8f6b7b1e..5e2e4cb43 100644 --- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListFragment.java +++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/KeyListFragment.java @@ -103,11 +103,8 @@ public class KeyListFragment extends LoaderFragment @Override public void onClick(View v) { - Intent intent = new Intent(getActivity(), EditKeyActivity.class); - intent.setAction(EditKeyActivity.ACTION_CREATE_KEY); - intent.putExtra(EditKeyActivity.EXTRA_GENERATE_DEFAULT_KEYS, true); - intent.putExtra(EditKeyActivity.EXTRA_USER_IDS, ""); // show user id view - startActivityForResult(intent, 0); + Intent intent = new Intent(getActivity(), CreateKeyActivity.class); + startActivity(intent); } }); mButtonEmptyImport = (Button) view.findViewById(R.id.key_list_empty_button_import); diff --git a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyActivity.java b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyActivity.java index b8b2542ce..256526dd9 100644 --- a/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyActivity.java +++ b/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/ViewKeyActivity.java @@ -19,7 +19,6 @@ package org.sufficientlysecure.keychain.ui; import android.annotation.TargetApi; -import android.app.Activity; import android.content.Intent; import android.database.Cursor; import android.net.Uri; @@ -53,7 +52,6 @@ import org.sufficientlysecure.keychain.pgp.PgpKeyHelper; import org.sufficientlysecure.keychain.provider.KeychainContract; import org.sufficientlysecure.keychain.provider.ProviderHelper; import org.sufficientlysecure.keychain.service.OperationResultParcel; -import org.sufficientlysecure.keychain.service.OperationResults.ImportResult; import org.sufficientlysecure.keychain.ui.adapter.PagerTabStripAdapter; import org.sufficientlysecure.keychain.ui.widget.SlidingTabLayout.TabColorizer; import org.sufficientlysecure.keychain.util.Log; diff --git a/OpenKeychain/src/main/res/layout/edit_key_activity.xml b/OpenKeychain/src/main/res/layout/edit_key_activity.xml index b6c5a1c9a..7e71ccf53 100644 --- a/OpenKeychain/src/main/res/layout/edit_key_activity.xml +++ b/OpenKeychain/src/main/res/layout/edit_key_activity.xml @@ -1,46 +1,15 @@ - + - + - + - - -