fixed <unknown> user id bug, restructured code

This commit is contained in:
Dominik 2012-09-13 18:24:10 +02:00
parent cbc3b8ae4e
commit 66cab704e7
7 changed files with 224 additions and 282 deletions

View File

@ -37,7 +37,7 @@ public class PGPConversionHelper {
* @param keys
* @return
*/
public static byte[] PGPSecretKeyListToBytes(Vector<PGPSecretKey> keys) {
public static byte[] PGPSecretKeyListToBytes(ArrayList<PGPSecretKey> keys) {
ByteArrayOutputStream os = new ByteArrayOutputStream();
for (PGPSecretKey key : keys) {
try {

View File

@ -220,6 +220,19 @@ public class PGPMain {
return mEditPassPhrase;
}
public static void updateProgress(ProgressDialogUpdater progress, int message, int current,
int total) {
if (progress != null) {
progress.setProgress(message, current, total);
}
}
public static void updateProgress(ProgressDialogUpdater progress, int current, int total) {
if (progress != null) {
progress.setProgress(current, total);
}
}
/**
* Creates new secret key. The returned PGPSecretKeyRing contains only one newly generated key
* when this key is the new masterkey. If a masterkey is supplied in the parameters
@ -309,7 +322,6 @@ public class PGPMain {
PGPKeyRingGenerator ringGen = null;
if (masterSecretKey == null) {
// build keyRing with only this one master key in it!
ringGen = new PGPKeyRingGenerator(PGPSignature.DEFAULT_CERTIFICATION, keyPair, "",
sha1Calc, null, null, certificationSignerBuilder, keyEncryptor);
@ -336,71 +348,16 @@ public class PGPMain {
throws PGPMain.GeneralException, NoSuchProviderException, PGPException,
NoSuchAlgorithmException, SignatureException, IOException, Database.GeneralException {
if (progress != null)
progress.setProgress(R.string.progress_buildingKey, 0, 100);
updateProgress(progress, R.string.progress_buildingKey, 0, 100);
if (oldPassPhrase == null || oldPassPhrase.equals("")) {
oldPassPhrase = "";
}
if (newPassPhrase == null || newPassPhrase.equals("")) {
newPassPhrase = "";
}
// TODO: What is with this code?
// Vector<String> userIds = new Vector<String>();
// Vector<PGPSecretKey> keys = new Vector<PGPSecretKey>();
// ViewGroup userIdEditors = userIdsView.getEditors();
// ViewGroup keyEditors = keysView.getEditors();
//
// boolean gotMainUserId = false;
// for (int i = 0; i < userIdEditors.getChildCount(); ++i) {
// UserIdEditor editor = (UserIdEditor) userIdEditors.getChildAt(i);
// String userId = null;
// try {
// userId = editor.getValue();
// } catch (UserIdEditor.NoNameException e) {
// throw new Apg.GeneralException(context.getString(R.string.error_userIdNeedsAName));
// } catch (UserIdEditor.NoEmailException e) {
// throw new Apg.GeneralException(
// context.getString(R.string.error_userIdNeedsAnEmailAddress));
// } catch (UserIdEditor.InvalidEmailException e) {
// throw new Apg.GeneralException("" + e);
// }
//
// if (userId.equals("")) {
// continue;
// }
//
// if (editor.isMainUserId()) {
// userIds.insertElementAt(userId, 0);
// gotMainUserId = true;
// } else {
// userIds.add(userId);
// }
// }
// if (userIds.size() == 0) {
// throw new Apg.GeneralException(context.getString(R.string.error_keyNeedsAUserId));
// }
//
// if (!gotMainUserId) {
// throw new Apg.GeneralException(
// context.getString(R.string.error_mainUserIdMustNotBeEmpty));
// }
// if (keyEditors.getChildCount() == 0) {
// throw new Apg.GeneralException(context.getString(R.string.error_keyNeedsMasterKey));
// }
//
// for (int i = 0; i < keyEditors.getChildCount(); ++i) {
// KeyEditor editor = (KeyEditor) keyEditors.getChildAt(i);
// keys.add(editor.getValue());
// }
if (progress != null)
progress.setProgress(R.string.progress_preparingMasterKey, 10, 100);
updateProgress(progress, R.string.progress_preparingMasterKey, 10, 100);
int usageId = keysUsages.get(0);
boolean canSign = (usageId == Id.choice.usage.sign_only || usageId == Id.choice.usage.sign_and_encrypt);
@ -411,20 +368,17 @@ public class PGPMain {
PGPSecretKey masterKey = keys.get(0);
PGPPublicKey masterPublicKey = masterKey.getPublicKey();
// TODO: why was this done?:
// PGPPublicKey tmpKey = masterKey.getPublicKey();
// PGPPublicKey masterPublicKey = new PGPPublicKey(tmpKey.getAlgorithm(),
// tmpKey.getKey(new BouncyCastleProvider()), tmpKey.getCreationTime());
// Somehow, the PGPPublicKey already has an empty certification attached to it, we remove
// that now before adding the new ones
masterPublicKey = PGPPublicKey.removeCertification(masterPublicKey, "");
PBESecretKeyDecryptor keyDecryptor = new JcePBESecretKeyDecryptorBuilder().setProvider(
BOUNCY_CASTLE_PROVIDER_NAME).build(oldPassPhrase.toCharArray());
PGPPrivateKey masterPrivateKey = masterKey.extractPrivateKey(keyDecryptor);
if (progress != null)
progress.setProgress(R.string.progress_certifyingMasterKey, 20, 100);
for (int i = 0; i < userIds.size(); ++i) {
String userId = userIds.get(i);
updateProgress(progress, R.string.progress_certifyingMasterKey, 20, 100);
for (String userId : userIds) {
PGPContentSignerBuilder signerBuilder = new JcaPGPContentSignerBuilder(
masterPublicKey.getAlgorithm(), HashAlgorithmTags.SHA1)
.setProvider(BOUNCY_CASTLE_PROVIDER_NAME);
@ -437,7 +391,7 @@ public class PGPMain {
masterPublicKey = PGPPublicKey.addCertification(masterPublicKey, userId, certification);
}
// TODO: cross-certify the master key with every sub key
// TODO: cross-certify the master key with every sub key (APG 1)
PGPKeyPair masterKeyPair = new PGPKeyPair(masterPublicKey, masterPrivateKey);
@ -454,7 +408,7 @@ public class PGPMain {
hashedPacketsGen.setPreferredHashAlgorithms(true, PREFERRED_HASH_ALGORITHMS);
hashedPacketsGen.setPreferredCompressionAlgorithms(true, PREFERRED_COMPRESSION_ALGORITHMS);
// TODO: this doesn't work quite right yet
// TODO: this doesn't work quite right yet (APG 1)
// if (keyEditor.getExpiryDate() != null) {
// GregorianCalendar creationDate = new GregorianCalendar();
// creationDate.setTime(getCreationDate(masterKey));
@ -467,9 +421,7 @@ public class PGPMain {
// hashedPacketsGen.setKeyExpirationTime(true, numDays * 86400);
// }
if (progress != null) {
progress.setProgress(R.string.progress_buildingMasterKeyRing, 30, 100);
}
updateProgress(progress, R.string.progress_buildingMasterKeyRing, 30, 100);
// define hashing and signing algos
PGPDigestCalculator sha1Calc = new JcaPGPDigestCalculatorProviderBuilder().build().get(
@ -486,11 +438,11 @@ public class PGPMain {
masterKeyPair, mainUserId, sha1Calc, hashedPacketsGen.generate(),
unhashedPacketsGen.generate(), certificationSignerBuilder, keyEncryptor);
if (progress != null)
progress.setProgress(R.string.progress_addingSubKeys, 40, 100);
updateProgress(progress, R.string.progress_addingSubKeys, 40, 100);
for (int i = 1; i < keys.size(); ++i) {
if (progress != null)
progress.setProgress(40 + 50 * (i - 1) / (keys.size() - 1), 100);
updateProgress(progress, 40 + 50 * (i - 1) / (keys.size() - 1), 100);
PGPSecretKey subKey = keys.get(i);
PGPPublicKey subPublicKey = subKey.getPublicKey();
@ -498,7 +450,7 @@ public class PGPMain {
.setProvider(BOUNCY_CASTLE_PROVIDER_NAME).build(oldPassPhrase.toCharArray());
PGPPrivateKey subPrivateKey = subKey.extractPrivateKey(keyDecryptor2);
// TODO: now used without algorithm and creation time?!
// TODO: now used without algorithm and creation time?! (APG 1)
PGPKeyPair subKeyPair = new PGPKeyPair(subPublicKey, subPrivateKey);
hashedPacketsGen = new PGPSignatureSubpacketGenerator();
@ -517,7 +469,7 @@ public class PGPMain {
}
hashedPacketsGen.setKeyFlags(true, keyFlags);
// TODO: this doesn't work quite right yet
// TODO: this doesn't work quite right yet (APG 1)
// if (keyEditor.getExpiryDate() != null) {
// GregorianCalendar creationDate = new GregorianCalendar();
// creationDate.setTime(getCreationDate(masterKey));
@ -536,13 +488,12 @@ public class PGPMain {
PGPSecretKeyRing secretKeyRing = keyGen.generateSecretKeyRing();
PGPPublicKeyRing publicKeyRing = keyGen.generatePublicKeyRing();
if (progress != null)
progress.setProgress(R.string.progress_savingKeyRing, 90, 100);
updateProgress(progress, R.string.progress_savingKeyRing, 90, 100);
mDatabase.saveKeyRing(secretKeyRing);
mDatabase.saveKeyRing(publicKeyRing);
if (progress != null)
progress.setProgress(R.string.progress_done, 100, 100);
updateProgress(progress, R.string.progress_done, 100, 100);
}
public static int storeKeyRingInCache(PGPKeyRing keyring) {
@ -655,9 +606,8 @@ public class PGPMain {
++badKeys;
}
if (progress != null) {
progress.setProgress((int) (100 * progressIn.position() / data.getSize()), 100);
}
updateProgress(progress, (int) (100 * progressIn.position() / data.getSize()), 100);
// TODO: needed?
// obj = objectFactory.nextObject();
@ -671,8 +621,7 @@ public class PGPMain {
returnData.putInt(ApgService.RESULT_IMPORT_UPDATED, oldKeys);
returnData.putInt(ApgService.RESULT_IMPORT_BAD, badKeys);
if (progress != null)
progress.setProgress(R.string.progress_done, 100, 100);
updateProgress(progress, R.string.progress_done, 100, 100);
return returnData;
}
@ -683,11 +632,9 @@ public class PGPMain {
Bundle returnData = new Bundle();
if (keyRingIds.size() == 1) {
if (progress != null)
progress.setProgress(R.string.progress_exportingKey, 0, 100);
updateProgress(progress, R.string.progress_exportingKey, 0, 100);
} else {
if (progress != null)
progress.setProgress(R.string.progress_exportingKeys, 0, 100);
updateProgress(progress, R.string.progress_exportingKeys, 0, 100);
}
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
@ -698,8 +645,7 @@ public class PGPMain {
int numKeys = 0;
for (int i = 0; i < keyRingIds.size(); ++i) {
if (progress != null)
progress.setProgress(i * 100 / keyRingIds.size(), 100);
updateProgress(progress, i * 100 / keyRingIds.size(), 100);
Object obj = mDatabase.getKeyRing(keyRingIds.get(i));
PGPPublicKeyRing publicKeyRing;
PGPSecretKeyRing secretKeyRing;
@ -718,8 +664,7 @@ public class PGPMain {
out.close();
returnData.putInt(ApgService.RESULT_EXPORT, numKeys);
if (progress != null)
progress.setProgress(R.string.progress_done, 100, 100);
updateProgress(progress, R.string.progress_done, 100, 100);
return returnData;
}
@ -859,8 +804,7 @@ public class PGPMain {
context.getString(R.string.error_couldNotExtractPrivateKey));
}
}
if (progress != null)
progress.setProgress(R.string.progress_preparingStreams, 5, 100);
updateProgress(progress, R.string.progress_preparingStreams, 5, 100);
// encrypt and compress input file content
JcePGPDataEncryptorBuilder encryptorBuilder = new JcePGPDataEncryptorBuilder(
@ -934,8 +878,7 @@ public class PGPMain {
// file name not needed, so empty string
OutputStream pOut = literalGen.open(bcpgOut, PGPLiteralData.BINARY, "", new Date(),
new byte[1 << 16]);
if (progress != null)
progress.setProgress(R.string.progress_encrypting, 20, 100);
updateProgress(progress, R.string.progress_encrypting, 20, 100);
long done = 0;
int n = 0;
@ -952,16 +895,14 @@ public class PGPMain {
}
done += n;
if (data.getSize() != 0) {
if (progress != null)
progress.setProgress((int) (20 + (95 - 20) * done / data.getSize()), 100);
updateProgress(progress, (int) (20 + (95 - 20) * done / data.getSize()), 100);
}
}
literalGen.close();
if (signatureKeyId != Id.key.none) {
if (progress != null)
progress.setProgress(R.string.progress_generatingSignature, 95, 100);
updateProgress(progress, R.string.progress_generatingSignature, 95, 100);
if (forceV3Signature) {
signatureV3Generator.generate().encode(pOut);
} else {
@ -976,8 +917,7 @@ public class PGPMain {
armorOut.close();
}
if (progress != null)
progress.setProgress(R.string.progress_done, 100, 100);
updateProgress(progress, R.string.progress_done, 100, 100);
}
public static void signText(Context context, InputData data, OutputStream outStream,
@ -1015,11 +955,9 @@ public class PGPMain {
armorOut.close();
throw new GeneralException(context.getString(R.string.error_couldNotExtractPrivateKey));
}
if (progress != null)
progress.setProgress(R.string.progress_preparingStreams, 0, 100);
updateProgress(progress, R.string.progress_preparingStreams, 0, 100);
if (progress != null)
progress.setProgress(R.string.progress_preparingSignature, 30, 100);
updateProgress(progress, R.string.progress_preparingSignature, 30, 100);
PGPSignatureGenerator signatureGenerator = null;
PGPV3SignatureGenerator signatureV3Generator = null;
@ -1042,8 +980,7 @@ public class PGPMain {
signatureGenerator.setHashedSubpackets(spGen.generate());
}
if (progress != null)
progress.setProgress(R.string.progress_signing, 40, 100);
updateProgress(progress, R.string.progress_signing, 40, 100);
armorOut.beginClearText(hashAlgorithm);
@ -1086,8 +1023,7 @@ public class PGPMain {
}
armorOut.close();
if (progress != null)
progress.setProgress(R.string.progress_done, 100, 100);
updateProgress(progress, R.string.progress_done, 100, 100);
}
public static void generateSignature(Context context, InputData data, OutputStream outStream,
@ -1132,11 +1068,9 @@ public class PGPMain {
if (signaturePrivateKey == null) {
throw new GeneralException(context.getString(R.string.error_couldNotExtractPrivateKey));
}
if (progress != null)
progress.setProgress(R.string.progress_preparingStreams, 0, 100);
updateProgress(progress, R.string.progress_preparingStreams, 0, 100);
if (progress != null)
progress.setProgress(R.string.progress_preparingSignature, 30, 100);
updateProgress(progress, R.string.progress_preparingSignature, 30, 100);
PGPSignatureGenerator signatureGenerator = null;
PGPV3SignatureGenerator signatureV3Generator = null;
@ -1164,8 +1098,7 @@ public class PGPMain {
signatureGenerator.setHashedSubpackets(spGen.generate());
}
if (progress != null)
progress.setProgress(R.string.progress_signing, 40, 100);
updateProgress(progress, R.string.progress_signing, 40, 100);
InputStream inStream = data.getInputStream();
if (binary) {
@ -1382,8 +1315,7 @@ public class PGPMain {
context.getString(R.string.error_noSymmetricEncryptionPacket));
}
if (progress != null)
progress.setProgress(R.string.progress_preparingStreams, currentProgress, 100);
updateProgress(progress, R.string.progress_preparingStreams, currentProgress, 100);
PGPDigestCalculatorProvider digestCalcProvider = new JcaPGPDigestCalculatorProviderBuilder()
.setProvider(BOUNCY_CASTLE_PROVIDER_NAME).build();
@ -1419,8 +1351,7 @@ public class PGPMain {
}
currentProgress += 5;
if (progress != null)
progress.setProgress(R.string.progress_extractingKey, currentProgress, 100);
updateProgress(progress, R.string.progress_extractingKey, currentProgress, 100);
PGPPrivateKey privateKey = null;
try {
PBESecretKeyDecryptor keyDecryptor = new JcePBESecretKeyDecryptorBuilder()
@ -1434,8 +1365,7 @@ public class PGPMain {
context.getString(R.string.error_couldNotExtractPrivateKey));
}
currentProgress += 5;
if (progress != null)
progress.setProgress(R.string.progress_preparingStreams, currentProgress, 100);
updateProgress(progress, R.string.progress_preparingStreams, currentProgress, 100);
PublicKeyDataDecryptorFactory decryptorFactory = new JcePublicKeyDataDecryptorFactoryBuilder()
.setProvider(BOUNCY_CASTLE_PROVIDER_NAME).build(privateKey);
@ -1546,8 +1476,7 @@ public class PGPMain {
currentProgress = (int) (startProgress + (endProgress - startProgress)
* (data.getStreamPosition() - startPos) / (data.getSize() - startPos));
}
if (progress != null)
progress.setProgress(currentProgress, 100);
updateProgress(progress, currentProgress, 100);
}
if (signature != null) {
@ -1576,8 +1505,7 @@ public class PGPMain {
// no integrity check
}
if (progress != null)
progress.setProgress(R.string.progress_done, 100, 100);
updateProgress(progress, R.string.progress_done, 100, 100);
return returnData;
}
@ -1589,8 +1517,7 @@ public class PGPMain {
ByteArrayOutputStream out = new ByteArrayOutputStream();
ArmoredInputStream aIn = new ArmoredInputStream(data.getInputStream());
if (progress != null)
progress.setProgress(R.string.progress_done, 0, 100);
updateProgress(progress, R.string.progress_done, 0, 100);
// mostly taken from ClearSignedFileProcessor
ByteArrayOutputStream lineOut = new ByteArrayOutputStream();
@ -1615,8 +1542,7 @@ public class PGPMain {
returnData.putBoolean(ApgService.RESULT_SIGNATURE, true);
if (progress != null)
progress.setProgress(R.string.progress_processingSignature, 60, 100);
updateProgress(progress, R.string.progress_processingSignature, 60, 100);
PGPObjectFactory pgpFact = new PGPObjectFactory(aIn);
PGPSignatureList sigList = (PGPSignatureList) pgpFact.nextObject();
@ -1690,8 +1616,7 @@ public class PGPMain {
returnData.putBoolean(ApgService.RESULT_SIGNATURE_SUCCESS, signature.verify());
if (progress != null)
progress.setProgress(R.string.progress_done, 100, 100);
updateProgress(progress, R.string.progress_done, 100, 100);
return returnData;
}

View File

@ -149,6 +149,7 @@ public class Database extends SQLiteOpenHelper {
KeyRings.WHO_ID + " " + KeyRings.WHO_ID_type + ", " +
KeyRings.KEY_RING_DATA + " " + KeyRings.KEY_RING_DATA_type + ");");
db.execSQL("CREATE TABLE " + Keys.TABLE_NAME + " (" +
Keys._ID + " " + Keys._ID_type + "," +
Keys.KEY_ID + " " + Keys.KEY_ID_type + ", " +

View File

@ -529,13 +529,10 @@ public class ApgService extends IntentService implements ProgressDialogUpdater {
if (newPassPhrase == null) {
newPassPhrase = oldPassPhrase;
}
@SuppressWarnings("unchecked")
ArrayList<String> userIds = (ArrayList<String>) data.getSerializable(USER_IDS);
ArrayList<String> userIds = data.getStringArrayList(USER_IDS);
ArrayList<PGPSecretKey> keys = PGPConversionHelper.BytesToPGPSecretKeyList(data
.getByteArray(KEYS));
@SuppressWarnings("unchecked")
ArrayList<Integer> keysUsages = (ArrayList<Integer>) data
.getSerializable(KEYS_USAGES);
ArrayList<Integer> keysUsages = data.getIntegerArrayList(KEYS_USAGES);
long masterKeyId = data.getLong(MASTER_KEY_ID);
/* Operation */

View File

@ -58,6 +58,7 @@ import android.widget.LinearLayout;
import android.widget.Toast;
import android.widget.CompoundButton.OnCheckedChangeListener;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Vector;
@ -73,7 +74,6 @@ public class EditKeyActivity extends SherlockFragmentActivity {
public static final String EXTRA_GENERATE_DEFAULT_KEYS = "generateDefaultKeys";
public static final String EXTRA_KEY_ID = "keyId";
private Intent mIntent = null;
private ActionBar mActionBar;
private PGPSecretKeyRing mKeyRing = null;
@ -150,136 +150,12 @@ public class EditKeyActivity extends SherlockFragmentActivity {
mKeysUsages = new Vector<Integer>();
// Catch Intents opened from other apps
mIntent = getIntent();
// Handle intents
Bundle extras = mIntent.getExtras();
if (ACTION_CREATE_KEY.equals(mIntent.getAction())) {
mActionBar.setTitle(R.string.title_createKey);
mCurrentPassPhrase = "";
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) {
// build layout in handler after generating keys not directly in onCreate
mBuildLayout = false;
// Send all information needed to service generate keys in other thread
Intent intent = new Intent(this, ApgService.class);
intent.putExtra(ApgService.EXTRA_ACTION,
ApgService.ACTION_GENERATE_DEFAULT_RSA_KEYS);
// fill values for this action
Bundle data = new Bundle();
data.putString(ApgService.SYMMETRIC_PASSPHRASE, mCurrentPassPhrase);
intent.putExtra(ApgService.EXTRA_DATA, data);
// Message is received after generating is done in ApgService
ApgServiceHandler saveHandler = new ApgServiceHandler(this,
R.string.progress_generating, ProgressDialog.STYLE_SPINNER) {
public void handleMessage(Message message) {
// handle messages by standard ApgHandler first
super.handleMessage(message);
if (message.arg1 == ApgServiceHandler.MESSAGE_OKAY) {
// get new key from data bundle returned from service
Bundle data = message.getData();
PGPSecretKeyRing masterKeyRing = PGPConversionHelper
.BytesToPGPSecretKeyRing(data
.getByteArray(ApgService.RESULT_NEW_KEY));
PGPSecretKeyRing subKeyRing = PGPConversionHelper
.BytesToPGPSecretKeyRing(data
.getByteArray(ApgService.RESULT_NEW_KEY2));
// add master key
@SuppressWarnings("unchecked")
Iterator<PGPSecretKey> masterIt = masterKeyRing.getSecretKeys();
mKeys.add(masterIt.next());
mKeysUsages.add(Id.choice.usage.sign_only);
// add sub key
@SuppressWarnings("unchecked")
Iterator<PGPSecretKey> subIt = subKeyRing.getSecretKeys();
subIt.next(); // masterkey
mKeys.add(subIt.next());
mKeysUsages.add(Id.choice.usage.encrypt_only);
buildLayout();
}
};
};
// Create a new Messenger for the communication back
Messenger messenger = new Messenger(saveHandler);
intent.putExtra(ApgService.EXTRA_MESSENGER, messenger);
saveHandler.showProgressDialog(this);
// start service with intent
startService(intent);
}
}
}
} else if (ACTION_EDIT_KEY.equals(mIntent.getAction())) {
mActionBar.setTitle(R.string.title_editKey);
mCurrentPassPhrase = PGPMain.getEditPassPhrase();
if (mCurrentPassPhrase == null) {
mCurrentPassPhrase = "";
}
if (mCurrentPassPhrase.equals("")) {
// check "no passphrase" checkbox and remove button
mNoPassphrase.setChecked(true);
mChangePassPhrase.setVisibility(View.GONE);
}
if (extras != null) {
if (extras.containsKey(EXTRA_KEY_ID)) {
long keyId = mIntent.getExtras().getLong(EXTRA_KEY_ID);
if (keyId != 0) {
PGPSecretKey masterKey = null;
mKeyRing = PGPMain.getSecretKeyRing(keyId);
if (mKeyRing != null) {
masterKey = PGPHelper.getMasterKey(mKeyRing);
for (PGPSecretKey key : new IterableIterator<PGPSecretKey>(
mKeyRing.getSecretKeys())) {
mKeys.add(key);
mKeysUsages.add(-1); // get usage when view is created
}
}
if (masterKey != null) {
for (String userId : new IterableIterator<String>(
masterKey.getUserIDs())) {
mUserIds.add(userId);
}
}
}
}
}
Intent intent = getIntent();
String action = intent.getAction();
if (ACTION_CREATE_KEY.equals(action)) {
handleActionCreateKey(intent);
} else if (ACTION_EDIT_KEY.equals(action)) {
handleActionEditKey(intent);
}
mChangePassPhrase.setOnClickListener(new OnClickListener() {
@ -309,6 +185,149 @@ public class EditKeyActivity extends SherlockFragmentActivity {
}
}
/**
* Handle intent action to create new key
*
* @param intent
*/
private void handleActionCreateKey(Intent intent) {
Bundle extras = intent.getExtras();
mActionBar.setTitle(R.string.title_createKey);
mCurrentPassPhrase = "";
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) {
// build layout in handler after generating keys not directly in onCreate
mBuildLayout = false;
// Send all information needed to service generate keys in other thread
Intent serviceIntent = new Intent(this, ApgService.class);
serviceIntent.putExtra(ApgService.EXTRA_ACTION,
ApgService.ACTION_GENERATE_DEFAULT_RSA_KEYS);
// fill values for this action
Bundle data = new Bundle();
data.putString(ApgService.SYMMETRIC_PASSPHRASE, mCurrentPassPhrase);
serviceIntent.putExtra(ApgService.EXTRA_DATA, data);
// Message is received after generating is done in ApgService
ApgServiceHandler saveHandler = new ApgServiceHandler(this,
R.string.progress_generating, ProgressDialog.STYLE_SPINNER) {
public void handleMessage(Message message) {
// handle messages by standard ApgHandler first
super.handleMessage(message);
if (message.arg1 == ApgServiceHandler.MESSAGE_OKAY) {
// get new key from data bundle returned from service
Bundle data = message.getData();
PGPSecretKeyRing masterKeyRing = PGPConversionHelper
.BytesToPGPSecretKeyRing(data
.getByteArray(ApgService.RESULT_NEW_KEY));
PGPSecretKeyRing subKeyRing = PGPConversionHelper
.BytesToPGPSecretKeyRing(data
.getByteArray(ApgService.RESULT_NEW_KEY2));
// add master key
@SuppressWarnings("unchecked")
Iterator<PGPSecretKey> masterIt = masterKeyRing.getSecretKeys();
mKeys.add(masterIt.next());
mKeysUsages.add(Id.choice.usage.sign_only);
// add sub key
@SuppressWarnings("unchecked")
Iterator<PGPSecretKey> subIt = subKeyRing.getSecretKeys();
subIt.next(); // masterkey
mKeys.add(subIt.next());
mKeysUsages.add(Id.choice.usage.encrypt_only);
buildLayout();
}
};
};
// Create a new Messenger for the communication back
Messenger messenger = new Messenger(saveHandler);
serviceIntent.putExtra(ApgService.EXTRA_MESSENGER, messenger);
saveHandler.showProgressDialog(this);
// start service with intent
startService(serviceIntent);
}
}
}
}
/**
* Handle intent action to edit existing key
*
* @param intent
*/
private void handleActionEditKey(Intent intent) {
Bundle extras = intent.getExtras();
mActionBar.setTitle(R.string.title_editKey);
mCurrentPassPhrase = PGPMain.getEditPassPhrase();
if (mCurrentPassPhrase == null) {
mCurrentPassPhrase = "";
}
if (mCurrentPassPhrase.equals("")) {
// check "no passphrase" checkbox and remove button
mNoPassphrase.setChecked(true);
mChangePassPhrase.setVisibility(View.GONE);
}
if (extras != null) {
if (extras.containsKey(EXTRA_KEY_ID)) {
long keyId = extras.getLong(EXTRA_KEY_ID);
if (keyId != 0) {
PGPSecretKey masterKey = null;
mKeyRing = PGPMain.getSecretKeyRing(keyId);
if (mKeyRing != null) {
masterKey = PGPHelper.getMasterKey(mKeyRing);
for (PGPSecretKey key : new IterableIterator<PGPSecretKey>(
mKeyRing.getSecretKeys())) {
mKeys.add(key);
mKeysUsages.add(-1); // get usage when view is created
}
}
if (masterKey != null) {
for (String userId : new IterableIterator<String>(masterKey.getUserIDs())) {
Log.d(Constants.TAG, "Added userId " + userId);
mUserIds.add(userId);
}
}
}
}
}
}
/**
* Shows the dialog to set a new passphrase
*/
@ -400,10 +419,10 @@ public class EditKeyActivity extends SherlockFragmentActivity {
Bundle data = new Bundle();
data.putString(ApgService.CURRENT_PASSPHRASE, mCurrentPassPhrase);
data.putString(ApgService.NEW_PASSPHRASE, mNewPassPhrase);
data.putSerializable(ApgService.USER_IDS, getUserIds(mUserIdsView));
Vector<PGPSecretKey> keys = getKeys(mKeysView);
data.putStringArrayList(ApgService.USER_IDS, getUserIds(mUserIdsView));
ArrayList<PGPSecretKey> keys = getKeys(mKeysView);
data.putByteArray(ApgService.KEYS, PGPConversionHelper.PGPSecretKeyListToBytes(keys));
data.putSerializable(ApgService.KEYS_USAGES, getKeysUsages(mKeysView));
data.putIntegerArrayList(ApgService.KEYS_USAGES, getKeysUsages(mKeysView));
data.putLong(ApgService.MASTER_KEY_ID, getMasterKeyId());
intent.putExtra(ApgService.EXTRA_DATA, data);
@ -441,8 +460,8 @@ public class EditKeyActivity extends SherlockFragmentActivity {
* @param userIdsView
* @return
*/
private Vector<String> getUserIds(SectionView userIdsView) throws PGPMain.GeneralException {
Vector<String> userIds = new Vector<String>();
private ArrayList<String> getUserIds(SectionView userIdsView) throws PGPMain.GeneralException {
ArrayList<String> userIds = new ArrayList<String>();
ViewGroup userIdEditors = userIdsView.getEditors();
@ -466,7 +485,7 @@ public class EditKeyActivity extends SherlockFragmentActivity {
}
if (editor.isMainUserId()) {
userIds.insertElementAt(userId, 0);
userIds.add(0, userId);
gotMainUserId = true;
} else {
userIds.add(userId);
@ -490,8 +509,8 @@ public class EditKeyActivity extends SherlockFragmentActivity {
* @param keysView
* @return
*/
private Vector<PGPSecretKey> getKeys(SectionView keysView) throws PGPMain.GeneralException {
Vector<PGPSecretKey> keys = new Vector<PGPSecretKey>();
private ArrayList<PGPSecretKey> getKeys(SectionView keysView) throws PGPMain.GeneralException {
ArrayList<PGPSecretKey> keys = new ArrayList<PGPSecretKey>();
ViewGroup keyEditors = keysView.getEditors();
@ -513,8 +532,8 @@ public class EditKeyActivity extends SherlockFragmentActivity {
* @param keysView
* @return
*/
private Vector<Integer> getKeysUsages(SectionView keysView) throws PGPMain.GeneralException {
Vector<Integer> getKeysUsages = new Vector<Integer>();
private ArrayList<Integer> getKeysUsages(SectionView keysView) throws PGPMain.GeneralException {
ArrayList<Integer> getKeysUsages = new ArrayList<Integer>();
ViewGroup keyEditors = keysView.getEditors();

View File

@ -19,7 +19,6 @@ package org.thialfihar.android.apg.ui.widget;
import org.spongycastle.openpgp.PGPSecretKey;
import org.spongycastle.openpgp.PGPSecretKeyRing;
import org.thialfihar.android.apg.Id;
import org.thialfihar.android.apg.helper.PGPMain;
import org.thialfihar.android.apg.helper.PGPConversionHelper;
import org.thialfihar.android.apg.service.ApgServiceHandler;
import org.thialfihar.android.apg.service.ApgService;

View File

@ -42,6 +42,7 @@ public class UserIdEditor extends LinearLayout implements Editor, OnClickListene
// see http://www.regular-expressions.info/email.html
// RFC 2822 if we omit the syntax using double quotes and square brackets
// android.util.Patterns.EMAIL_ADDRESS is only available as of Android 2.2+
private static final Pattern EMAIL_PATTERN = Pattern
.compile(
"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?",