Refactor ProviderHelper to be non-static using a constructor based on context (first commit to get context out of pgp classes)

This commit is contained in:
Dominik Schürmann
2014-04-11 17:45:52 +02:00
parent bbd97cf800
commit 094fb698de
23 changed files with 266 additions and 228 deletions

View File

@@ -51,7 +51,7 @@ public class ExportHelper {
public void deleteKey(Uri dataUri, Handler deleteHandler) { public void deleteKey(Uri dataUri, Handler deleteHandler) {
try { try {
long masterKeyId = ProviderHelper.extractOrGetMasterKeyId(mActivity, dataUri); long masterKeyId = new ProviderHelper(mActivity).extractOrGetMasterKeyId(dataUri);
// Create a new Messenger for the communication back // Create a new Messenger for the communication back
Messenger messenger = new Messenger(deleteHandler); Messenger messenger = new Messenger(deleteHandler);

View File

@@ -79,6 +79,7 @@ import java.util.Set;
*/ */
public class PgpDecryptVerify { public class PgpDecryptVerify {
private Context mContext; private Context mContext;
private ProviderHelper mProviderHelper;
private InputData mData; private InputData mData;
private OutputStream mOutStream; private OutputStream mOutStream;
@@ -90,6 +91,7 @@ public class PgpDecryptVerify {
private PgpDecryptVerify(Builder builder) { private PgpDecryptVerify(Builder builder) {
// private Constructor can only be called from Builder // private Constructor can only be called from Builder
this.mContext = builder.mContext; this.mContext = builder.mContext;
this.mProviderHelper = new ProviderHelper(mContext);
this.mData = builder.mData; this.mData = builder.mData;
this.mOutStream = builder.mOutStream; this.mOutStream = builder.mOutStream;
@@ -243,11 +245,11 @@ public class PgpDecryptVerify {
PGPSecretKeyRing secretKeyRing = null; PGPSecretKeyRing secretKeyRing = null;
try { try {
// get master key id for this encryption key id // get master key id for this encryption key id
masterKeyId = ProviderHelper.getMasterKeyId(mContext, masterKeyId = mProviderHelper.getMasterKeyId(
KeyRings.buildUnifiedKeyRingsFindBySubkeyUri(Long.toString(encData.getKeyID())) KeyRings.buildUnifiedKeyRingsFindBySubkeyUri(Long.toString(encData.getKeyID()))
); );
// get actual keyring object based on master key id // get actual keyring object based on master key id
secretKeyRing = ProviderHelper.getPGPSecretKeyRing(mContext, masterKeyId); secretKeyRing = mProviderHelper.getPGPSecretKeyRing(masterKeyId);
} catch (ProviderHelper.NotFoundException e) { } catch (ProviderHelper.NotFoundException e) {
// continue with the next packet in the while loop // continue with the next packet in the while loop
continue; continue;
@@ -393,17 +395,17 @@ public class PgpDecryptVerify {
try { try {
Uri uri = KeyRings.buildUnifiedKeyRingsFindBySubkeyUri( Uri uri = KeyRings.buildUnifiedKeyRingsFindBySubkeyUri(
Long.toString(sigList.get(i).getKeyID())); Long.toString(sigList.get(i).getKeyID()));
masterKeyId = ProviderHelper.getMasterKeyId(mContext, uri); masterKeyId = mProviderHelper.getMasterKeyId(uri);
signatureIndex = i; signatureIndex = i;
} catch (ProviderHelper.NotFoundException e) { } catch (ProviderHelper.NotFoundException e) {
Log.d(Constants.TAG, "key not found!"); Log.d(Constants.TAG, "key not found!");
} }
} }
if(masterKeyId == null) { if (masterKeyId == null) {
try { try {
signatureKey = ProviderHelper signatureKey = mProviderHelper
.getPGPPublicKeyRing(mContext, masterKeyId).getPublicKey(); .getPGPPublicKeyRing(masterKeyId).getPublicKey();
} catch (ProviderHelper.NotFoundException e) { } catch (ProviderHelper.NotFoundException e) {
// can't happen // can't happen
} }
@@ -417,7 +419,7 @@ public class PgpDecryptVerify {
signature.init(contentVerifierBuilderProvider, signatureKey); signature.init(contentVerifierBuilderProvider, signatureKey);
} else { } else {
if(!sigList.isEmpty()) { if (!sigList.isEmpty()) {
signatureResult.setKeyId(sigList.get(0).getKeyID()); signatureResult.setKeyId(sigList.get(0).getKeyID());
} }
@@ -489,7 +491,7 @@ public class PgpDecryptVerify {
signatureResult.setSignatureOnly(false); signatureResult.setSignatureOnly(false);
//Now check binding signatures //Now check binding signatures
boolean validKeyBinding = verifyKeyBinding(mContext, messageSignature, signatureKey); boolean validKeyBinding = verifyKeyBinding(messageSignature, signatureKey);
boolean validSignature = signature.verify(messageSignature); boolean validSignature = signature.verify(messageSignature);
// TODO: implement CERTIFIED! // TODO: implement CERTIFIED!
@@ -587,7 +589,7 @@ public class PgpDecryptVerify {
signatureKeyId = signature.getKeyID(); signatureKeyId = signature.getKeyID();
// find data about this subkey // find data about this subkey
HashMap<String, Object> data = ProviderHelper.getGenericData(mContext, HashMap<String, Object> data = mProviderHelper.getGenericData(
KeyRings.buildUnifiedKeyRingsFindBySubkeyUri(Long.toString(signature.getKeyID())), KeyRings.buildUnifiedKeyRingsFindBySubkeyUri(Long.toString(signature.getKeyID())),
new String[]{KeyRings.MASTER_KEY_ID, KeyRings.USER_ID}, new String[]{KeyRings.MASTER_KEY_ID, KeyRings.USER_ID},
new int[]{ProviderHelper.FIELD_TYPE_INTEGER, ProviderHelper.FIELD_TYPE_STRING}); new int[]{ProviderHelper.FIELD_TYPE_INTEGER, ProviderHelper.FIELD_TYPE_STRING});
@@ -600,7 +602,7 @@ public class PgpDecryptVerify {
// this one can't fail now (yay database constraints) // this one can't fail now (yay database constraints)
try { try {
signatureKey = ProviderHelper.getPGPPublicKeyRing(mContext, (Long) data.get(KeyRings.MASTER_KEY_ID)).getPublicKey(); signatureKey = mProviderHelper.getPGPPublicKeyRing((Long) data.get(KeyRings.MASTER_KEY_ID)).getPublicKey();
} catch (ProviderHelper.NotFoundException e) { } catch (ProviderHelper.NotFoundException e) {
Log.e(Constants.TAG, "key not found!", e); Log.e(Constants.TAG, "key not found!", e);
} }
@@ -644,7 +646,7 @@ public class PgpDecryptVerify {
} }
//Now check binding signatures //Now check binding signatures
boolean validKeyBinding = verifyKeyBinding(mContext, signature, signatureKey); boolean validKeyBinding = verifyKeyBinding(signature, signatureKey);
boolean validSignature = signature.verify(); boolean validSignature = signature.verify();
if (validKeyBinding && validSignature) { if (validKeyBinding && validSignature) {
@@ -664,14 +666,13 @@ public class PgpDecryptVerify {
return result; return result;
} }
private static boolean verifyKeyBinding(Context context, private boolean verifyKeyBinding(PGPSignature signature, PGPPublicKey signatureKey) {
PGPSignature signature, PGPPublicKey signatureKey) {
long signatureKeyId = signature.getKeyID(); long signatureKeyId = signature.getKeyID();
boolean validKeyBinding = false; boolean validKeyBinding = false;
PGPPublicKey mKey = null; PGPPublicKey mKey = null;
try { try {
PGPPublicKeyRing signKeyRing = ProviderHelper.getPGPPublicKeyRingWithKeyId(context, PGPPublicKeyRing signKeyRing = mProviderHelper.getPGPPublicKeyRingWithKeyId(
signatureKeyId); signatureKeyId);
mKey = signKeyRing.getPublicKey(); mKey = signKeyRing.getPublicKey();
} catch (ProviderHelper.NotFoundException e) { } catch (ProviderHelper.NotFoundException e) {
@@ -686,7 +687,7 @@ public class PgpDecryptVerify {
return validKeyBinding; return validKeyBinding;
} }
private static boolean verifyKeyBinding(PGPPublicKey masterPublicKey, PGPPublicKey signingPublicKey) { private boolean verifyKeyBinding(PGPPublicKey masterPublicKey, PGPPublicKey signingPublicKey) {
boolean validSubkeyBinding = false; boolean validSubkeyBinding = false;
boolean validTempSubkeyBinding = false; boolean validTempSubkeyBinding = false;
boolean validPrimaryKeyBinding = false; boolean validPrimaryKeyBinding = false;
@@ -734,9 +735,9 @@ public class PgpDecryptVerify {
return (validSubkeyBinding & validPrimaryKeyBinding); return (validSubkeyBinding & validPrimaryKeyBinding);
} }
private static boolean verifyPrimaryKeyBinding(PGPSignatureSubpacketVector pkts, private boolean verifyPrimaryKeyBinding(PGPSignatureSubpacketVector pkts,
PGPPublicKey masterPublicKey, PGPPublicKey masterPublicKey,
PGPPublicKey signingPublicKey) { PGPPublicKey signingPublicKey) {
boolean validPrimaryKeyBinding = false; boolean validPrimaryKeyBinding = false;
JcaPGPContentVerifierBuilderProvider contentVerifierBuilderProvider = JcaPGPContentVerifierBuilderProvider contentVerifierBuilderProvider =
new JcaPGPContentVerifierBuilderProvider() new JcaPGPContentVerifierBuilderProvider()

View File

@@ -57,10 +57,13 @@ public class PgpImportExport {
private KeychainServiceListener mKeychainServiceListener; private KeychainServiceListener mKeychainServiceListener;
private ProviderHelper mProviderHelper;
public PgpImportExport(Context context, ProgressDialogUpdater progress) { public PgpImportExport(Context context, ProgressDialogUpdater progress) {
super(); super();
this.mContext = context; this.mContext = context;
this.mProgress = progress; this.mProgress = progress;
this.mProviderHelper = new ProviderHelper(context);
} }
public PgpImportExport(Context context, public PgpImportExport(Context context,
@@ -68,6 +71,7 @@ public class PgpImportExport {
super(); super();
this.mContext = context; this.mContext = context;
this.mProgress = progress; this.mProgress = progress;
this.mProviderHelper = new ProviderHelper(context);
this.mKeychainServiceListener = keychainListener; this.mKeychainServiceListener = keychainListener;
} }
@@ -196,7 +200,7 @@ public class PgpImportExport {
updateProgress(progress * 100 / masterKeyIdsSize, 100); updateProgress(progress * 100 / masterKeyIdsSize, 100);
try { try {
PGPPublicKeyRing publicKeyRing = ProviderHelper.getPGPPublicKeyRing(mContext, pubKeyMasterId); PGPPublicKeyRing publicKeyRing = mProviderHelper.getPGPPublicKeyRing(pubKeyMasterId);
publicKeyRing.encode(arOutStream); publicKeyRing.encode(arOutStream);
} catch (ProviderHelper.NotFoundException e) { } catch (ProviderHelper.NotFoundException e) {
@@ -222,7 +226,7 @@ public class PgpImportExport {
updateProgress(progress * 100 / masterKeyIdsSize, 100); updateProgress(progress * 100 / masterKeyIdsSize, 100);
try { try {
PGPSecretKeyRing secretKeyRing = ProviderHelper.getPGPSecretKeyRing(mContext, secretKeyMasterId); PGPSecretKeyRing secretKeyRing = mProviderHelper.getPGPSecretKeyRing(secretKeyMasterId);
secretKeyRing.encode(arOutStream); secretKeyRing.encode(arOutStream);
} catch (ProviderHelper.NotFoundException e) { } catch (ProviderHelper.NotFoundException e) {
Log.e(Constants.TAG, "key not found!", e); Log.e(Constants.TAG, "key not found!", e);
@@ -279,15 +283,15 @@ public class PgpImportExport {
newPubRing = PGPPublicKeyRing.insertPublicKey(newPubRing, key); newPubRing = PGPPublicKeyRing.insertPublicKey(newPubRing, key);
} }
if (newPubRing != null) { if (newPubRing != null) {
ProviderHelper.saveKeyRing(mContext, newPubRing); mProviderHelper.saveKeyRing(newPubRing);
} }
ProviderHelper.saveKeyRing(mContext, secretKeyRing); mProviderHelper.saveKeyRing(secretKeyRing);
// TODO: remove status returns, use exceptions! // TODO: remove status returns, use exceptions!
status = Id.return_value.ok; status = Id.return_value.ok;
} }
} else if (keyring instanceof PGPPublicKeyRing) { } else if (keyring instanceof PGPPublicKeyRing) {
PGPPublicKeyRing publicKeyRing = (PGPPublicKeyRing) keyring; PGPPublicKeyRing publicKeyRing = (PGPPublicKeyRing) keyring;
ProviderHelper.saveKeyRing(mContext, publicKeyRing); mProviderHelper.saveKeyRing(publicKeyRing);
// TODO: remove status returns, use exceptions! // TODO: remove status returns, use exceptions!
status = Id.return_value.ok; status = Id.return_value.ok;
} }

View File

@@ -67,6 +67,7 @@ import java.util.Date;
*/ */
public class PgpSignEncrypt { public class PgpSignEncrypt {
private Context mContext; private Context mContext;
private ProviderHelper mProviderHelper;
private InputData mData; private InputData mData;
private OutputStream mOutStream; private OutputStream mOutStream;
@@ -85,6 +86,7 @@ public class PgpSignEncrypt {
private PgpSignEncrypt(Builder builder) { private PgpSignEncrypt(Builder builder) {
// private Constructor can only be called from Builder // private Constructor can only be called from Builder
this.mContext = builder.mContext; this.mContext = builder.mContext;
this.mProviderHelper = new ProviderHelper(mContext);
this.mData = builder.mData; this.mData = builder.mData;
this.mOutStream = builder.mOutStream; this.mOutStream = builder.mOutStream;
@@ -252,7 +254,7 @@ public class PgpSignEncrypt {
PGPPrivateKey signaturePrivateKey = null; PGPPrivateKey signaturePrivateKey = null;
if (enableSignature) { if (enableSignature) {
try { try {
signingKeyRing = ProviderHelper.getPGPSecretKeyRingWithKeyId(mContext, mSignatureMasterKeyId); signingKeyRing = mProviderHelper.getPGPSecretKeyRingWithKeyId(mSignatureMasterKeyId);
} catch (ProviderHelper.NotFoundException e) { } catch (ProviderHelper.NotFoundException e) {
throw new PgpGeneralException(mContext.getString(R.string.error_signature_failed)); throw new PgpGeneralException(mContext.getString(R.string.error_signature_failed));
} }
@@ -300,7 +302,7 @@ public class PgpSignEncrypt {
// Asymmetric encryption // Asymmetric encryption
for (long id : mEncryptionMasterKeyIds) { for (long id : mEncryptionMasterKeyIds) {
try { try {
PGPPublicKeyRing keyRing = ProviderHelper.getPGPPublicKeyRing(mContext, id); PGPPublicKeyRing keyRing = mProviderHelper.getPGPPublicKeyRing(id);
PGPPublicKey key = PgpKeyHelper.getEncryptPublicKey(keyRing); PGPPublicKey key = PgpKeyHelper.getEncryptPublicKey(keyRing);
if (key != null) { if (key != null) {
JcePublicKeyKeyEncryptionMethodGenerator pubKeyEncryptionGenerator = JcePublicKeyKeyEncryptionMethodGenerator pubKeyEncryptionGenerator =
@@ -491,7 +493,7 @@ public class PgpSignEncrypt {
PGPSecretKeyRing signingKeyRing; PGPSecretKeyRing signingKeyRing;
try { try {
signingKeyRing = ProviderHelper.getPGPSecretKeyRingWithKeyId(mContext, mSignatureMasterKeyId); signingKeyRing = mProviderHelper.getPGPSecretKeyRingWithKeyId(mSignatureMasterKeyId);
} catch (ProviderHelper.NotFoundException e) { } catch (ProviderHelper.NotFoundException e) {
throw new PgpGeneralException(mContext.getString(R.string.error_signature_failed)); throw new PgpGeneralException(mContext.getString(R.string.error_signature_failed));
} }

View File

@@ -250,10 +250,11 @@ public class KeychainDatabase extends SQLiteOpenHelper {
c.moveToPosition(i); c.moveToPosition(i);
byte[] data = c.getBlob(0); byte[] data = c.getBlob(0);
PGPKeyRing ring = PgpConversionHelper.BytesToPGPKeyRing(data); PGPKeyRing ring = PgpConversionHelper.BytesToPGPKeyRing(data);
ProviderHelper providerHelper = new ProviderHelper(context);
if(ring instanceof PGPPublicKeyRing) if(ring instanceof PGPPublicKeyRing)
ProviderHelper.saveKeyRing(context, (PGPPublicKeyRing) ring); providerHelper.saveKeyRing((PGPPublicKeyRing) ring);
else if(ring instanceof PGPSecretKeyRing) else if(ring instanceof PGPSecretKeyRing)
ProviderHelper.saveKeyRing(context, (PGPSecretKeyRing) ring); providerHelper.saveKeyRing((PGPSecretKeyRing) ring);
else { else {
Log.e(Constants.TAG, "Unknown blob data type!"); Log.e(Constants.TAG, "Unknown blob data type!");
} }
@@ -271,10 +272,11 @@ public class KeychainDatabase extends SQLiteOpenHelper {
c.moveToPosition(i); c.moveToPosition(i);
byte[] data = c.getBlob(0); byte[] data = c.getBlob(0);
PGPKeyRing ring = PgpConversionHelper.BytesToPGPKeyRing(data); PGPKeyRing ring = PgpConversionHelper.BytesToPGPKeyRing(data);
ProviderHelper providerHelper = new ProviderHelper(context);
if(ring instanceof PGPPublicKeyRing) if(ring instanceof PGPPublicKeyRing)
ProviderHelper.saveKeyRing(context, (PGPPublicKeyRing) ring); providerHelper.saveKeyRing((PGPPublicKeyRing) ring);
else if(ring instanceof PGPSecretKeyRing) else if(ring instanceof PGPSecretKeyRing)
ProviderHelper.saveKeyRing(context, (PGPSecretKeyRing) ring); providerHelper.saveKeyRing((PGPSecretKeyRing) ring);
else { else {
Log.e(Constants.TAG, "Unknown blob data type!"); Log.e(Constants.TAG, "Unknown blob data type!");
} }

View File

@@ -63,6 +63,13 @@ import java.util.Map;
import java.util.Set; import java.util.Set;
public class ProviderHelper { public class ProviderHelper {
private Context mContext;
private ContentResolver mContentResolver;
public ProviderHelper(Context context) {
this.mContext = context;
this.mContentResolver = context.getContentResolver();
}
public static class NotFoundException extends Exception { public static class NotFoundException extends Exception {
public NotFoundException() { public NotFoundException() {
@@ -81,23 +88,33 @@ public class ProviderHelper {
public static final int FIELD_TYPE_STRING = 4; public static final int FIELD_TYPE_STRING = 4;
public static final int FIELD_TYPE_BLOB = 5; public static final int FIELD_TYPE_BLOB = 5;
public static Object getGenericData(Context context, Uri uri, String column, int type) { public Object getGenericData(Uri uri, String column, int type) {
return getGenericData(context, uri, new String[] { column }, new int[] { type }).get(column); return getGenericData(uri, new String[]{column}, new int[]{type}).get(column);
} }
public static HashMap<String,Object> getGenericData(Context context, Uri uri, String[] proj, int[] types) { public HashMap<String, Object> getGenericData(Uri uri, String[] proj, int[] types) {
Cursor cursor = context.getContentResolver().query(uri, proj, null, null, null); Cursor cursor = mContentResolver.query(uri, proj, null, null, null);
HashMap<String, Object> result = new HashMap<String, Object>(proj.length); HashMap<String, Object> result = new HashMap<String, Object>(proj.length);
if (cursor != null && cursor.moveToFirst()) { if (cursor != null && cursor.moveToFirst()) {
int pos = 0; int pos = 0;
for(String p : proj) { for (String p : proj) {
switch(types[pos]) { switch (types[pos]) {
case FIELD_TYPE_NULL: result.put(p, cursor.isNull(pos)); break; case FIELD_TYPE_NULL:
case FIELD_TYPE_INTEGER: result.put(p, cursor.getLong(pos)); break; result.put(p, cursor.isNull(pos));
case FIELD_TYPE_FLOAT: result.put(p, cursor.getFloat(pos)); break; break;
case FIELD_TYPE_STRING: result.put(p, cursor.getString(pos)); break; case FIELD_TYPE_INTEGER:
case FIELD_TYPE_BLOB: result.put(p, cursor.getBlob(pos)); break; result.put(p, cursor.getLong(pos));
break;
case FIELD_TYPE_FLOAT:
result.put(p, cursor.getFloat(pos));
break;
case FIELD_TYPE_STRING:
result.put(p, cursor.getString(pos));
break;
case FIELD_TYPE_BLOB:
result.put(p, cursor.getBlob(pos));
break;
} }
pos += 1; pos += 1;
} }
@@ -110,43 +127,43 @@ public class ProviderHelper {
return result; return result;
} }
public static Object getUnifiedData(Context context, long masterKeyId, String column, int type) { public Object getUnifiedData(long masterKeyId, String column, int type) {
return getUnifiedData(context, masterKeyId, new String[] { column }, new int[] { type }).get(column); return getUnifiedData(masterKeyId, new String[]{column}, new int[]{type}).get(column);
} }
public static HashMap<String,Object> getUnifiedData(Context context, long masterKeyId, String[] proj, int[] types) { public HashMap<String, Object> getUnifiedData(long masterKeyId, String[] proj, int[] types) {
return getGenericData(context, KeyRings.buildUnifiedKeyRingUri(Long.toString(masterKeyId)), proj, types); return getGenericData(KeyRings.buildUnifiedKeyRingUri(Long.toString(masterKeyId)), proj, types);
} }
/** /**
* Find the master key id related to a given query. The id will either be extracted from the * Find the master key id related to a given query. The id will either be extracted from the
* query, which should work for all specific /key_rings/ queries, or will be queried if it can't. * query, which should work for all specific /key_rings/ queries, or will be queried if it can't.
*/ */
public static long extractOrGetMasterKeyId(Context context, Uri queryUri) public long extractOrGetMasterKeyId(Uri queryUri)
throws NotFoundException { throws NotFoundException {
// try extracting from the uri first // try extracting from the uri first
String firstSegment = queryUri.getPathSegments().get(1); String firstSegment = queryUri.getPathSegments().get(1);
if(!firstSegment.equals("find")) try { if (!firstSegment.equals("find")) try {
return Long.parseLong(firstSegment); return Long.parseLong(firstSegment);
} catch(NumberFormatException e) { } catch (NumberFormatException e) {
// didn't work? oh well. // didn't work? oh well.
Log.d(Constants.TAG, "Couldn't get masterKeyId from URI, querying..."); Log.d(Constants.TAG, "Couldn't get masterKeyId from URI, querying...");
} }
return getMasterKeyId(context, queryUri); return getMasterKeyId(queryUri);
} }
public static long getMasterKeyId(Context context, Uri queryUri) throws NotFoundException { public long getMasterKeyId(Uri queryUri) throws NotFoundException {
Object data = getGenericData(context, queryUri, KeyRings.MASTER_KEY_ID, FIELD_TYPE_INTEGER); Object data = getGenericData(queryUri, KeyRings.MASTER_KEY_ID, FIELD_TYPE_INTEGER);
if(data != null) { if (data != null) {
return (Long) data; return (Long) data;
} else { } else {
throw new NotFoundException(); throw new NotFoundException();
} }
} }
public static Map<Long, PGPKeyRing> getPGPKeyRings(Context context, Uri queryUri) { public Map<Long, PGPKeyRing> getPGPKeyRings(Uri queryUri) {
Cursor cursor = context.getContentResolver().query(queryUri, Cursor cursor = mContentResolver.query(queryUri,
new String[]{KeyRingData.MASTER_KEY_ID, KeyRingData.KEY_RING_DATA }, new String[]{KeyRingData.MASTER_KEY_ID, KeyRingData.KEY_RING_DATA},
null, null, null); null, null, null);
Map<Long, PGPKeyRing> result = new HashMap<Long, PGPKeyRing>(cursor.getCount()); Map<Long, PGPKeyRing> result = new HashMap<Long, PGPKeyRing>(cursor.getCount());
@@ -156,7 +173,7 @@ public class ProviderHelper {
if (data != null) { if (data != null) {
result.put(masterKeyId, PgpConversionHelper.BytesToPGPKeyRing(data)); result.put(masterKeyId, PgpConversionHelper.BytesToPGPKeyRing(data));
} }
} while(cursor.moveToNext()); } while (cursor.moveToNext());
if (cursor != null) { if (cursor != null) {
cursor.close(); cursor.close();
@@ -165,66 +182,64 @@ public class ProviderHelper {
return result; return result;
} }
public static PGPKeyRing getPGPKeyRing(Context context, Uri queryUri) throws NotFoundException { public PGPKeyRing getPGPKeyRing(Uri queryUri) throws NotFoundException {
Map<Long, PGPKeyRing> result = getPGPKeyRings(context, queryUri); Map<Long, PGPKeyRing> result = getPGPKeyRings(queryUri);
if(result.isEmpty()) { if (result.isEmpty()) {
throw new NotFoundException("PGPKeyRing object not found!"); throw new NotFoundException("PGPKeyRing object not found!");
} else { } else {
return result.values().iterator().next(); return result.values().iterator().next();
} }
} }
public static PGPPublicKeyRing getPGPPublicKeyRingWithKeyId(Context context, long keyId) public PGPPublicKeyRing getPGPPublicKeyRingWithKeyId(long keyId)
throws NotFoundException { throws NotFoundException {
Uri uri = KeyRings.buildUnifiedKeyRingsFindBySubkeyUri(Long.toString(keyId)); Uri uri = KeyRings.buildUnifiedKeyRingsFindBySubkeyUri(Long.toString(keyId));
long masterKeyId = getMasterKeyId(context, uri); long masterKeyId = getMasterKeyId(uri);
return getPGPPublicKeyRing(context, masterKeyId); return getPGPPublicKeyRing(masterKeyId);
} }
public static PGPSecretKeyRing getPGPSecretKeyRingWithKeyId(Context context, long keyId) public PGPSecretKeyRing getPGPSecretKeyRingWithKeyId(long keyId)
throws NotFoundException { throws NotFoundException {
Uri uri = KeyRings.buildUnifiedKeyRingsFindBySubkeyUri(Long.toString(keyId)); Uri uri = KeyRings.buildUnifiedKeyRingsFindBySubkeyUri(Long.toString(keyId));
long masterKeyId = getMasterKeyId(context, uri); long masterKeyId = getMasterKeyId(uri);
return getPGPSecretKeyRing(context, masterKeyId); return getPGPSecretKeyRing(masterKeyId);
} }
/** /**
* Retrieves the actual PGPPublicKeyRing object from the database blob based on the masterKeyId * Retrieves the actual PGPPublicKeyRing object from the database blob based on the masterKeyId
*/ */
public static PGPPublicKeyRing getPGPPublicKeyRing(Context context, public PGPPublicKeyRing getPGPPublicKeyRing(long masterKeyId) throws NotFoundException {
long masterKeyId) throws NotFoundException {
Uri queryUri = KeyRingData.buildPublicKeyRingUri(Long.toString(masterKeyId)); Uri queryUri = KeyRingData.buildPublicKeyRingUri(Long.toString(masterKeyId));
return (PGPPublicKeyRing) getPGPKeyRing(context, queryUri); return (PGPPublicKeyRing) getPGPKeyRing(queryUri);
} }
/** /**
* Retrieves the actual PGPSecretKeyRing object from the database blob based on the maserKeyId * Retrieves the actual PGPSecretKeyRing object from the database blob based on the maserKeyId
*/ */
public static PGPSecretKeyRing getPGPSecretKeyRing(Context context, public PGPSecretKeyRing getPGPSecretKeyRing(long masterKeyId) throws NotFoundException {
long masterKeyId) throws NotFoundException {
Uri queryUri = KeyRingData.buildSecretKeyRingUri(Long.toString(masterKeyId)); Uri queryUri = KeyRingData.buildSecretKeyRingUri(Long.toString(masterKeyId));
return (PGPSecretKeyRing) getPGPKeyRing(context, queryUri); return (PGPSecretKeyRing) getPGPKeyRing(queryUri);
} }
/** /**
* Saves PGPPublicKeyRing with its keys and userIds in DB * Saves PGPPublicKeyRing with its keys and userIds in DB
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public static void saveKeyRing(Context context, PGPPublicKeyRing keyRing) throws IOException { public void saveKeyRing(PGPPublicKeyRing keyRing) throws IOException {
PGPPublicKey masterKey = keyRing.getPublicKey(); PGPPublicKey masterKey = keyRing.getPublicKey();
long masterKeyId = masterKey.getKeyID(); long masterKeyId = masterKey.getKeyID();
// IF there is a secret key, preserve it! // IF there is a secret key, preserve it!
PGPSecretKeyRing secretRing = null; PGPSecretKeyRing secretRing = null;
try { try {
secretRing = ProviderHelper.getPGPSecretKeyRing(context, masterKeyId); secretRing = getPGPSecretKeyRing(masterKeyId);
} catch (NotFoundException e) { } catch (NotFoundException e) {
Log.e(Constants.TAG, "key not found!"); Log.e(Constants.TAG, "key not found!");
} }
// delete old version of this keyRing, which also deletes all keys and userIds on cascade // delete old version of this keyRing, which also deletes all keys and userIds on cascade
try { try {
context.getContentResolver().delete(KeyRingData.buildPublicKeyRingUri(Long.toString(masterKeyId)), null, null); mContentResolver.delete(KeyRingData.buildPublicKeyRingUri(Long.toString(masterKeyId)), null, null);
} catch (UnsupportedOperationException e) { } catch (UnsupportedOperationException e) {
Log.e(Constants.TAG, "Key could not be deleted! Maybe we are creating a new one!", e); Log.e(Constants.TAG, "Key could not be deleted! Maybe we are creating a new one!", e);
} }
@@ -234,21 +249,21 @@ public class ProviderHelper {
values.put(KeyRingData.MASTER_KEY_ID, masterKeyId); values.put(KeyRingData.MASTER_KEY_ID, masterKeyId);
values.put(KeyRingData.KEY_RING_DATA, keyRing.getEncoded()); values.put(KeyRingData.KEY_RING_DATA, keyRing.getEncoded());
Uri uri = KeyRingData.buildPublicKeyRingUri(Long.toString(masterKeyId)); Uri uri = KeyRingData.buildPublicKeyRingUri(Long.toString(masterKeyId));
context.getContentResolver().insert(uri, values); mContentResolver.insert(uri, values);
// save all keys and userIds included in keyRing object in database // save all keys and userIds included in keyRing object in database
ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>(); ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>();
int rank = 0; int rank = 0;
for (PGPPublicKey key : new IterableIterator<PGPPublicKey>(keyRing.getPublicKeys())) { for (PGPPublicKey key : new IterableIterator<PGPPublicKey>(keyRing.getPublicKeys())) {
operations.add(buildPublicKeyOperations(context, masterKeyId, key, rank)); operations.add(buildPublicKeyOperations(masterKeyId, key, rank));
++rank; ++rank;
} }
// get a list of owned secret keys, for verification filtering // get a list of owned secret keys, for verification filtering
Map<Long, PGPKeyRing> allKeyRings = getPGPKeyRings(context, KeyRingData.buildSecretKeyRingUri()); Map<Long, PGPKeyRing> allKeyRings = getPGPKeyRings(KeyRingData.buildSecretKeyRingUri());
// special case: available secret keys verify themselves! // special case: available secret keys verify themselves!
if(secretRing != null) if (secretRing != null)
allKeyRings.put(secretRing.getSecretKey().getKeyID(), secretRing); allKeyRings.put(secretRing.getSecretKey().getKeyID(), secretRing);
// classify and order user ids. primary are moved to the front, revoked to the back, // classify and order user ids. primary are moved to the front, revoked to the back,
@@ -266,16 +281,16 @@ public class ProviderHelper {
long certId = cert.getKeyID(); long certId = cert.getKeyID();
try { try {
// self signature // self signature
if(certId == masterKeyId) { if (certId == masterKeyId) {
cert.init(new JcaPGPContentVerifierBuilderProvider().setProvider( cert.init(new JcaPGPContentVerifierBuilderProvider().setProvider(
Constants.BOUNCY_CASTLE_PROVIDER_NAME), masterKey); Constants.BOUNCY_CASTLE_PROVIDER_NAME), masterKey);
if(!cert.verifyCertification(userId, masterKey)) { if (!cert.verifyCertification(userId, masterKey)) {
// not verified?! dang! TODO notify user? this is kinda serious... // not verified?! dang! TODO notify user? this is kinda serious...
Log.e(Constants.TAG, "Could not verify self signature for " + userId + "!"); Log.e(Constants.TAG, "Could not verify self signature for " + userId + "!");
continue; continue;
} }
// is this the first, or a more recent certificate? // is this the first, or a more recent certificate?
if(item.selfCert == null || if (item.selfCert == null ||
item.selfCert.getCreationTime().before(cert.getCreationTime())) { item.selfCert.getCreationTime().before(cert.getCreationTime())) {
item.selfCert = cert; item.selfCert = cert;
item.isPrimary = cert.getHashedSubPackets().isPrimaryUserID(); item.isPrimary = cert.getHashedSubPackets().isPrimaryUserID();
@@ -284,21 +299,21 @@ public class ProviderHelper {
} }
} }
// verify signatures from known private keys // verify signatures from known private keys
if(allKeyRings.containsKey(certId)) { if (allKeyRings.containsKey(certId)) {
// mark them as verified // mark them as verified
cert.init(new JcaPGPContentVerifierBuilderProvider().setProvider( cert.init(new JcaPGPContentVerifierBuilderProvider().setProvider(
Constants.BOUNCY_CASTLE_PROVIDER_NAME), Constants.BOUNCY_CASTLE_PROVIDER_NAME),
allKeyRings.get(certId).getPublicKey()); allKeyRings.get(certId).getPublicKey());
if(cert.verifyCertification(userId, masterKey)) { if (cert.verifyCertification(userId, masterKey)) {
item.trustedCerts.add(cert); item.trustedCerts.add(cert);
} }
} }
} catch(SignatureException e) { } catch (SignatureException e) {
Log.e(Constants.TAG, "Signature verification failed! " Log.e(Constants.TAG, "Signature verification failed! "
+ PgpKeyHelper.convertKeyIdToHex(masterKey.getKeyID()) + PgpKeyHelper.convertKeyIdToHex(masterKey.getKeyID())
+ " from " + " from "
+ PgpKeyHelper.convertKeyIdToHex(cert.getKeyID()), e); + PgpKeyHelper.convertKeyIdToHex(cert.getKeyID()), e);
} catch(PGPException e) { } catch (PGPException e) {
Log.e(Constants.TAG, "Signature verification failed! " Log.e(Constants.TAG, "Signature verification failed! "
+ PgpKeyHelper.convertKeyIdToHex(masterKey.getKeyID()) + PgpKeyHelper.convertKeyIdToHex(masterKey.getKeyID())
+ " from " + " from "
@@ -311,26 +326,26 @@ public class ProviderHelper {
// this is a stable sort, so the order of keys is otherwise preserved. // this is a stable sort, so the order of keys is otherwise preserved.
Collections.sort(uids); Collections.sort(uids);
// iterate and put into db // iterate and put into db
for(int userIdRank = 0; userIdRank < uids.size(); userIdRank++) { for (int userIdRank = 0; userIdRank < uids.size(); userIdRank++) {
UserIdItem item = uids.get(userIdRank); UserIdItem item = uids.get(userIdRank);
operations.add(buildUserIdOperations(masterKeyId, item, userIdRank)); operations.add(buildUserIdOperations(masterKeyId, item, userIdRank));
// no self cert is bad, but allowed by the rfc... // no self cert is bad, but allowed by the rfc...
if(item.selfCert != null) { if (item.selfCert != null) {
operations.add(buildCertOperations( operations.add(buildCertOperations(
masterKeyId, userIdRank, item.selfCert, Certs.VERIFIED_SELF)); masterKeyId, userIdRank, item.selfCert, Certs.VERIFIED_SELF));
} }
// don't bother with trusted certs if the uid is revoked, anyways // don't bother with trusted certs if the uid is revoked, anyways
if(item.isRevoked) { if (item.isRevoked) {
continue; continue;
} }
for(int i = 0; i < item.trustedCerts.size(); i++) { for (int i = 0; i < item.trustedCerts.size(); i++) {
operations.add(buildCertOperations( operations.add(buildCertOperations(
masterKeyId, userIdRank, item.trustedCerts.get(i), Certs.VERIFIED_SECRET)); masterKeyId, userIdRank, item.trustedCerts.get(i), Certs.VERIFIED_SECRET));
} }
} }
try { try {
context.getContentResolver().applyBatch(KeychainContract.CONTENT_AUTHORITY, operations); mContentResolver.applyBatch(KeychainContract.CONTENT_AUTHORITY, operations);
} catch (RemoteException e) { } catch (RemoteException e) {
Log.e(Constants.TAG, "applyBatch failed!", e); Log.e(Constants.TAG, "applyBatch failed!", e);
} catch (OperationApplicationException e) { } catch (OperationApplicationException e) {
@@ -338,8 +353,8 @@ public class ProviderHelper {
} }
// Save the saved keyring (if any) // Save the saved keyring (if any)
if(secretRing != null) { if (secretRing != null) {
saveKeyRing(context, secretRing); saveKeyRing(secretRing);
} }
} }
@@ -354,11 +369,13 @@ public class ProviderHelper {
@Override @Override
public int compareTo(UserIdItem o) { public int compareTo(UserIdItem o) {
// if one key is primary but the other isn't, the primary one always comes first // if one key is primary but the other isn't, the primary one always comes first
if(isPrimary != o.isPrimary) if (isPrimary != o.isPrimary) {
return isPrimary ? -1 : 1; return isPrimary ? -1 : 1;
}
// revoked keys always come last! // revoked keys always come last!
if(isRevoked != o.isRevoked) if (isRevoked != o.isRevoked) {
return isRevoked ? 1 : -1; return isRevoked ? 1 : -1;
}
return 0; return 0;
} }
} }
@@ -368,7 +385,7 @@ public class ProviderHelper {
* is already in the database! * is already in the database!
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public static void saveKeyRing(Context context, PGPSecretKeyRing keyRing) throws IOException { public void saveKeyRing(PGPSecretKeyRing keyRing) throws IOException {
long masterKeyId = keyRing.getPublicKey().getKeyID(); long masterKeyId = keyRing.getPublicKey().getKeyID();
// save secret keyring // save secret keyring
@@ -377,30 +394,29 @@ public class ProviderHelper {
values.put(KeyRingData.KEY_RING_DATA, keyRing.getEncoded()); values.put(KeyRingData.KEY_RING_DATA, keyRing.getEncoded());
// insert new version of this keyRing // insert new version of this keyRing
Uri uri = KeyRingData.buildSecretKeyRingUri(Long.toString(masterKeyId)); Uri uri = KeyRingData.buildSecretKeyRingUri(Long.toString(masterKeyId));
context.getContentResolver().insert(uri, values); mContentResolver.insert(uri, values);
} }
/** /**
* Saves (or updates) a pair of public and secret KeyRings in the database * Saves (or updates) a pair of public and secret KeyRings in the database
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public static void saveKeyRing(Context context, PGPPublicKeyRing pubRing, PGPSecretKeyRing privRing) throws IOException { public void saveKeyRing(PGPPublicKeyRing pubRing, PGPSecretKeyRing privRing) throws IOException {
long masterKeyId = pubRing.getPublicKey().getKeyID(); long masterKeyId = pubRing.getPublicKey().getKeyID();
// delete secret keyring (so it isn't unnecessarily saved by public-saveKeyRing below) // delete secret keyring (so it isn't unnecessarily saved by public-saveKeyRing below)
context.getContentResolver().delete(KeyRingData.buildSecretKeyRingUri(Long.toString(masterKeyId)), null, null); mContentResolver.delete(KeyRingData.buildSecretKeyRingUri(Long.toString(masterKeyId)), null, null);
// save public keyring // save public keyring
saveKeyRing(context, pubRing); saveKeyRing(pubRing);
saveKeyRing(context, privRing); saveKeyRing(privRing);
} }
/** /**
* Build ContentProviderOperation to add PGPPublicKey to database corresponding to a keyRing * Build ContentProviderOperation to add PGPPublicKey to database corresponding to a keyRing
*/ */
private static ContentProviderOperation buildPublicKeyOperations(Context context, private ContentProviderOperation
long masterKeyId, PGPPublicKey key, int rank) throws IOException { buildPublicKeyOperations(long masterKeyId, PGPPublicKey key, int rank) throws IOException {
ContentValues values = new ContentValues(); ContentValues values = new ContentValues();
values.put(Keys.MASTER_KEY_ID, masterKeyId); values.put(Keys.MASTER_KEY_ID, masterKeyId);
@@ -430,11 +446,8 @@ public class ProviderHelper {
/** /**
* Build ContentProviderOperation to add PGPPublicKey to database corresponding to a keyRing * Build ContentProviderOperation to add PGPPublicKey to database corresponding to a keyRing
*/ */
private static ContentProviderOperation buildCertOperations(long masterKeyId, private ContentProviderOperation
int rank, buildCertOperations(long masterKeyId, int rank, PGPSignature cert, int verified) throws IOException {
PGPSignature cert,
int verified)
throws IOException {
ContentValues values = new ContentValues(); ContentValues values = new ContentValues();
values.put(Certs.MASTER_KEY_ID, masterKeyId); values.put(Certs.MASTER_KEY_ID, masterKeyId);
values.put(Certs.RANK, rank); values.put(Certs.RANK, rank);
@@ -452,8 +465,8 @@ public class ProviderHelper {
/** /**
* Build ContentProviderOperation to add PublicUserIds to database corresponding to a keyRing * Build ContentProviderOperation to add PublicUserIds to database corresponding to a keyRing
*/ */
private static ContentProviderOperation buildUserIdOperations(long masterKeyId, UserIdItem item, private ContentProviderOperation
int rank) { buildUserIdOperations(long masterKeyId, UserIdItem item, int rank) {
ContentValues values = new ContentValues(); ContentValues values = new ContentValues();
values.put(UserIds.MASTER_KEY_ID, masterKeyId); values.put(UserIds.MASTER_KEY_ID, masterKeyId);
values.put(UserIds.USER_ID, item.userId); values.put(UserIds.USER_ID, item.userId);
@@ -466,7 +479,7 @@ public class ProviderHelper {
return ContentProviderOperation.newInsert(uri).withValues(values).build(); return ContentProviderOperation.newInsert(uri).withValues(values).build();
} }
private static String getKeyRingAsArmoredString(Context context, byte[] data) throws IOException { private String getKeyRingAsArmoredString(byte[] data) throws IOException {
Object keyRing = null; Object keyRing = null;
if (data != null) { if (data != null) {
keyRing = PgpConversionHelper.BytesToPGPKeyRing(data); keyRing = PgpConversionHelper.BytesToPGPKeyRing(data);
@@ -474,7 +487,7 @@ public class ProviderHelper {
ByteArrayOutputStream bos = new ByteArrayOutputStream(); ByteArrayOutputStream bos = new ByteArrayOutputStream();
ArmoredOutputStream aos = new ArmoredOutputStream(bos); ArmoredOutputStream aos = new ArmoredOutputStream(bos);
aos.setHeader("Version", PgpHelper.getFullVersion(context)); aos.setHeader("Version", PgpHelper.getFullVersion(mContext));
if (keyRing instanceof PGPSecretKeyRing) { if (keyRing instanceof PGPSecretKeyRing) {
aos.write(((PGPSecretKeyRing) keyRing).getEncoded()); aos.write(((PGPSecretKeyRing) keyRing).getEncoded());
@@ -490,15 +503,15 @@ public class ProviderHelper {
return armoredKey; return armoredKey;
} }
public static String getKeyRingAsArmoredString(Context context, Uri uri) public String getKeyRingAsArmoredString(Uri uri)
throws NotFoundException, IOException { throws NotFoundException, IOException {
byte[] data = (byte[]) ProviderHelper.getGenericData( byte[] data = (byte[]) getGenericData(
context, uri, KeyRingData.KEY_RING_DATA, ProviderHelper.FIELD_TYPE_BLOB); uri, KeyRingData.KEY_RING_DATA, ProviderHelper.FIELD_TYPE_BLOB);
return getKeyRingAsArmoredString(context, data); return getKeyRingAsArmoredString(data);
} }
// TODO This method is NOT ACTUALLY USED. Is this preparation for something, or just dead code? // TODO This method is NOT ACTUALLY USED. Is this preparation for something, or just dead code?
public static ArrayList<String> getKeyRingsAsArmoredString(Context context, long[] masterKeyIds) public ArrayList<String> getKeyRingsAsArmoredString(Context context, long[] masterKeyIds)
throws IOException { throws IOException {
ArrayList<String> output = new ArrayList<String>(); ArrayList<String> output = new ArrayList<String>();
@@ -508,7 +521,8 @@ public class ProviderHelper {
} }
// Build a cursor for the selected masterKeyIds // Build a cursor for the selected masterKeyIds
Cursor cursor = null; { Cursor cursor = null;
{
String inMasterKeyList = KeyRingData.MASTER_KEY_ID + " IN ("; String inMasterKeyList = KeyRingData.MASTER_KEY_ID + " IN (";
for (int i = 0; i < masterKeyIds.length; ++i) { for (int i = 0; i < masterKeyIds.length; ++i) {
if (i != 0) { if (i != 0) {
@@ -518,7 +532,7 @@ public class ProviderHelper {
} }
inMasterKeyList += ")"; inMasterKeyList += ")";
cursor = context.getContentResolver().query(KeyRingData.buildPublicKeyRingUri(), new String[] { cursor = context.getContentResolver().query(KeyRingData.buildPublicKeyRingUri(), new String[]{
KeyRingData._ID, KeyRingData.MASTER_KEY_ID, KeyRingData.KEY_RING_DATA KeyRingData._ID, KeyRingData.MASTER_KEY_ID, KeyRingData.KEY_RING_DATA
}, inMasterKeyList, null, null); }, inMasterKeyList, null, null);
} }
@@ -534,7 +548,7 @@ public class ProviderHelper {
// get actual keyring data blob and write it to ByteArrayOutputStream // get actual keyring data blob and write it to ByteArrayOutputStream
try { try {
output.add(getKeyRingAsArmoredString(context, data)); output.add(getKeyRingAsArmoredString(data));
} catch (IOException e) { } catch (IOException e) {
Log.e(Constants.TAG, "IOException", e); Log.e(Constants.TAG, "IOException", e);
} }
@@ -553,9 +567,8 @@ public class ProviderHelper {
} }
} }
public static ArrayList<String> getRegisteredApiApps(Context context) { public ArrayList<String> getRegisteredApiApps() {
Cursor cursor = context.getContentResolver().query(ApiApps.CONTENT_URI, null, null, null, Cursor cursor = mContentResolver.query(ApiApps.CONTENT_URI, null, null, null, null);
null);
ArrayList<String> packageNames = new ArrayList<String>(); ArrayList<String> packageNames = new ArrayList<String>();
if (cursor != null) { if (cursor != null) {
@@ -574,14 +587,14 @@ public class ProviderHelper {
return packageNames; return packageNames;
} }
private static ContentValues contentValueForApiApps(AppSettings appSettings) { private ContentValues contentValueForApiApps(AppSettings appSettings) {
ContentValues values = new ContentValues(); ContentValues values = new ContentValues();
values.put(ApiApps.PACKAGE_NAME, appSettings.getPackageName()); values.put(ApiApps.PACKAGE_NAME, appSettings.getPackageName());
values.put(ApiApps.PACKAGE_SIGNATURE, appSettings.getPackageSignature()); values.put(ApiApps.PACKAGE_SIGNATURE, appSettings.getPackageSignature());
return values; return values;
} }
private static ContentValues contentValueForApiAccounts(AccountSettings accSettings) { private ContentValues contentValueForApiAccounts(AccountSettings accSettings) {
ContentValues values = new ContentValues(); ContentValues values = new ContentValues();
values.put(KeychainContract.ApiAccounts.ACCOUNT_NAME, accSettings.getAccountName()); values.put(KeychainContract.ApiAccounts.ACCOUNT_NAME, accSettings.getAccountName());
values.put(KeychainContract.ApiAccounts.KEY_ID, accSettings.getKeyId()); values.put(KeychainContract.ApiAccounts.KEY_ID, accSettings.getKeyId());
@@ -591,24 +604,24 @@ public class ProviderHelper {
return values; return values;
} }
public static void insertApiApp(Context context, AppSettings appSettings) { public void insertApiApp(AppSettings appSettings) {
context.getContentResolver().insert(KeychainContract.ApiApps.CONTENT_URI, mContentResolver.insert(KeychainContract.ApiApps.CONTENT_URI,
contentValueForApiApps(appSettings)); contentValueForApiApps(appSettings));
} }
public static void insertApiAccount(Context context, Uri uri, AccountSettings accSettings) { public void insertApiAccount(Uri uri, AccountSettings accSettings) {
context.getContentResolver().insert(uri, contentValueForApiAccounts(accSettings)); mContentResolver.insert(uri, contentValueForApiAccounts(accSettings));
} }
public static void updateApiApp(Context context, AppSettings appSettings, Uri uri) { public void updateApiApp(AppSettings appSettings, Uri uri) {
if (context.getContentResolver().update(uri, contentValueForApiApps(appSettings), null, if (mContentResolver.update(uri, contentValueForApiApps(appSettings), null,
null) <= 0) { null) <= 0) {
throw new RuntimeException(); throw new RuntimeException();
} }
} }
public static void updateApiAccount(Context context, AccountSettings accSettings, Uri uri) { public void updateApiAccount(AccountSettings accSettings, Uri uri) {
if (context.getContentResolver().update(uri, contentValueForApiAccounts(accSettings), null, if (mContentResolver.update(uri, contentValueForApiAccounts(accSettings), null,
null) <= 0) { null) <= 0) {
throw new RuntimeException(); throw new RuntimeException();
} }
@@ -617,14 +630,13 @@ public class ProviderHelper {
/** /**
* Must be an uri pointing to an account * Must be an uri pointing to an account
* *
* @param context
* @param uri * @param uri
* @return * @return
*/ */
public static AppSettings getApiAppSettings(Context context, Uri uri) { public AppSettings getApiAppSettings(Uri uri) {
AppSettings settings = null; AppSettings settings = null;
Cursor cur = context.getContentResolver().query(uri, null, null, null, null); Cursor cur = mContentResolver.query(uri, null, null, null, null);
if (cur != null && cur.moveToFirst()) { if (cur != null && cur.moveToFirst()) {
settings = new AppSettings(); settings = new AppSettings();
settings.setPackageName(cur.getString( settings.setPackageName(cur.getString(
@@ -636,10 +648,10 @@ public class ProviderHelper {
return settings; return settings;
} }
public static AccountSettings getApiAccountSettings(Context context, Uri accountUri) { public AccountSettings getApiAccountSettings(Uri accountUri) {
AccountSettings settings = null; AccountSettings settings = null;
Cursor cur = context.getContentResolver().query(accountUri, null, null, null, null); Cursor cur = mContentResolver.query(accountUri, null, null, null, null);
if (cur != null && cur.moveToFirst()) { if (cur != null && cur.moveToFirst()) {
settings = new AccountSettings(); settings = new AccountSettings();
@@ -658,10 +670,10 @@ public class ProviderHelper {
return settings; return settings;
} }
public static Set<Long> getAllKeyIdsForApp(Context context, Uri uri) { public Set<Long> getAllKeyIdsForApp(Uri uri) {
Set<Long> keyIds = new HashSet<Long>(); Set<Long> keyIds = new HashSet<Long>();
Cursor cursor = context.getContentResolver().query(uri, null, null, null, null); Cursor cursor = mContentResolver.query(uri, null, null, null, null);
if (cursor != null) { if (cursor != null) {
int keyIdColumn = cursor.getColumnIndex(KeychainContract.ApiAccounts.KEY_ID); int keyIdColumn = cursor.getColumnIndex(KeychainContract.ApiAccounts.KEY_ID);
while (cursor.moveToNext()) { while (cursor.moveToNext()) {
@@ -672,13 +684,12 @@ public class ProviderHelper {
return keyIds; return keyIds;
} }
public static byte[] getApiAppSignature(Context context, String packageName) { public byte[] getApiAppSignature(String packageName) {
Uri queryUri = ApiApps.buildByPackageNameUri(packageName); Uri queryUri = ApiApps.buildByPackageNameUri(packageName);
String[] projection = new String[]{ApiApps.PACKAGE_SIGNATURE}; String[] projection = new String[]{ApiApps.PACKAGE_SIGNATURE};
ContentResolver cr = context.getContentResolver(); Cursor cursor = mContentResolver.query(queryUri, projection, null, null, null);
Cursor cursor = cr.query(queryUri, projection, null, null, null);
byte[] signature = null; byte[] signature = null;
if (cursor != null && cursor.moveToFirst()) { if (cursor != null && cursor.moveToFirst()) {

View File

@@ -296,7 +296,7 @@ public class OpenPgpService extends RemoteService {
PgpDecryptVerify.Builder builder = new PgpDecryptVerify.Builder(this, inputData, os); PgpDecryptVerify.Builder builder = new PgpDecryptVerify.Builder(this, inputData, os);
builder.allowSymmetricDecryption(false) // no support for symmetric encryption builder.allowSymmetricDecryption(false) // no support for symmetric encryption
.allowedKeyIds(allowedKeyIds) // allow only private keys associated with .allowedKeyIds(allowedKeyIds) // allow only private keys associated with
// accounts of this app // accounts of this app
.passphrase(passphrase); .passphrase(passphrase);
// TODO: currently does not support binary signed-only content // TODO: currently does not support binary signed-only content
@@ -305,10 +305,10 @@ public class OpenPgpService extends RemoteService {
if (PgpDecryptVerifyResult.KEY_PASSHRASE_NEEDED == decryptVerifyResult.getStatus()) { if (PgpDecryptVerifyResult.KEY_PASSHRASE_NEEDED == decryptVerifyResult.getStatus()) {
// get PendingIntent for passphrase input, add it to given params and return to client // get PendingIntent for passphrase input, add it to given params and return to client
Intent passphraseBundle = Intent passphraseBundle =
getPassphraseBundleIntent(data, decryptVerifyResult.getKeyIdPassphraseNeeded()); getPassphraseBundleIntent(data, decryptVerifyResult.getKeyIdPassphraseNeeded());
return passphraseBundle; return passphraseBundle;
} else if (PgpDecryptVerifyResult.SYMMETRIC_PASSHRASE_NEEDED == } else if (PgpDecryptVerifyResult.SYMMETRIC_PASSHRASE_NEEDED ==
decryptVerifyResult.getStatus()) { decryptVerifyResult.getStatus()) {
throw new PgpGeneralException("Decryption of symmetric content not supported by API!"); throw new PgpGeneralException("Decryption of symmetric content not supported by API!");
} }
@@ -352,7 +352,7 @@ public class OpenPgpService extends RemoteService {
try { try {
long keyId = data.getLongExtra(OpenPgpApi.EXTRA_KEY_ID, 0); long keyId = data.getLongExtra(OpenPgpApi.EXTRA_KEY_ID, 0);
if (ProviderHelper.getPGPPublicKeyRing(this, keyId) == null) { if (mProviderHelper.getPGPPublicKeyRing(keyId) == null) {
Intent result = new Intent(); Intent result = new Intent();
// If keys are not in db we return an additional PendingIntent // If keys are not in db we return an additional PendingIntent
@@ -462,8 +462,8 @@ public class OpenPgpService extends RemoteService {
} else if (OpenPgpApi.ACTION_DECRYPT_VERIFY.equals(action)) { } else if (OpenPgpApi.ACTION_DECRYPT_VERIFY.equals(action)) {
String currentPkg = getCurrentCallingPackage(); String currentPkg = getCurrentCallingPackage();
Set<Long> allowedKeyIds = Set<Long> allowedKeyIds =
ProviderHelper.getAllKeyIdsForApp(mContext, mProviderHelper.getAllKeyIdsForApp(
ApiAccounts.buildBaseUri(currentPkg)); ApiAccounts.buildBaseUri(currentPkg));
return decryptAndVerifyImpl(data, input, output, allowedKeyIds); return decryptAndVerifyImpl(data, input, output, allowedKeyIds);
} else if (OpenPgpApi.ACTION_GET_KEY.equals(action)) { } else if (OpenPgpApi.ACTION_GET_KEY.equals(action)) {
return getKeyImpl(data); return getKeyImpl(data);

View File

@@ -45,6 +45,7 @@ import java.util.Arrays;
*/ */
public abstract class RemoteService extends Service { public abstract class RemoteService extends Service {
Context mContext; Context mContext;
ProviderHelper mProviderHelper;
public Context getContext() { public Context getContext() {
return mContext; return mContext;
@@ -148,7 +149,7 @@ public abstract class RemoteService extends Service {
Uri uri = KeychainContract.ApiAccounts.buildByPackageAndAccountUri(currentPkg, accountName); Uri uri = KeychainContract.ApiAccounts.buildByPackageAndAccountUri(currentPkg, accountName);
AccountSettings settings = ProviderHelper.getApiAccountSettings(this, uri); AccountSettings settings = mProviderHelper.getApiAccountSettings(uri);
return settings; // can be null! return settings; // can be null!
} }
@@ -221,7 +222,7 @@ public abstract class RemoteService extends Service {
private boolean isPackageAllowed(String packageName) throws WrongPackageSignatureException { private boolean isPackageAllowed(String packageName) throws WrongPackageSignatureException {
Log.d(Constants.TAG, "isPackageAllowed packageName: " + packageName); Log.d(Constants.TAG, "isPackageAllowed packageName: " + packageName);
ArrayList<String> allowedPkgs = ProviderHelper.getRegisteredApiApps(this); ArrayList<String> allowedPkgs = mProviderHelper.getRegisteredApiApps();
Log.d(Constants.TAG, "allowed: " + allowedPkgs); Log.d(Constants.TAG, "allowed: " + allowedPkgs);
// check if package is allowed to use our service // check if package is allowed to use our service
@@ -236,7 +237,7 @@ public abstract class RemoteService extends Service {
throw new WrongPackageSignatureException(e.getMessage()); throw new WrongPackageSignatureException(e.getMessage());
} }
byte[] storedSig = ProviderHelper.getApiAppSignature(this, packageName); byte[] storedSig = mProviderHelper.getApiAppSignature(packageName);
if (Arrays.equals(currentSig, storedSig)) { if (Arrays.equals(currentSig, storedSig)) {
Log.d(Constants.TAG, Log.d(Constants.TAG,
"Package signature is correct! (equals signature from database)"); "Package signature is correct! (equals signature from database)");
@@ -244,7 +245,7 @@ public abstract class RemoteService extends Service {
} else { } else {
throw new WrongPackageSignatureException( throw new WrongPackageSignatureException(
"PACKAGE NOT ALLOWED! Signature wrong! (Signature not " + "PACKAGE NOT ALLOWED! Signature wrong! (Signature not " +
"equals signature from database)"); "equals signature from database)");
} }
} }
@@ -256,6 +257,7 @@ public abstract class RemoteService extends Service {
public void onCreate() { public void onCreate() {
super.onCreate(); super.onCreate();
mContext = this; mContext = this;
mProviderHelper = new ProviderHelper(this);
} }
} }

View File

@@ -90,7 +90,7 @@ public class AccountSettingsActivity extends ActionBarActivity {
} }
private void loadData(Uri accountUri) { private void loadData(Uri accountUri) {
AccountSettings settings = ProviderHelper.getApiAccountSettings(this, accountUri); AccountSettings settings = new ProviderHelper(this).getApiAccountSettings(accountUri);
mAccountSettingsFragment.setAccSettings(settings); mAccountSettingsFragment.setAccSettings(settings);
} }
@@ -102,7 +102,7 @@ public class AccountSettingsActivity extends ActionBarActivity {
} }
private void save() { private void save() {
ProviderHelper.updateApiAccount(this, mAccountSettingsFragment.getAccSettings(), mAccountUri); new ProviderHelper(this).updateApiAccount(mAccountSettingsFragment.getAccSettings(), mAccountUri);
finish(); finish();
} }

View File

@@ -180,8 +180,8 @@ public class AccountSettingsFragment extends Fragment implements
if (resultCode == Activity.RESULT_OK) { if (resultCode == Activity.RESULT_OK) {
// select newly created key // select newly created key
try { try {
long masterKeyId = ProviderHelper.extractOrGetMasterKeyId( long masterKeyId = new ProviderHelper(getActivity())
getActivity(), data.getData()); .extractOrGetMasterKeyId(data.getData());
mSelectKeyFragment.selectKey(masterKeyId); mSelectKeyFragment.selectKey(masterKeyId);
} catch (ProviderHelper.NotFoundException e) { } catch (ProviderHelper.NotFoundException e) {
Log.e(Constants.TAG, "key not found!", e); Log.e(Constants.TAG, "key not found!", e);

View File

@@ -85,7 +85,7 @@ public class AppSettingsActivity extends ActionBarActivity {
} }
private void loadData(Bundle savedInstanceState, Uri appUri) { private void loadData(Bundle savedInstanceState, Uri appUri) {
AppSettings settings = ProviderHelper.getApiAppSettings(this, appUri); AppSettings settings = new ProviderHelper(this).getApiAppSettings(appUri);
mSettingsFragment.setAppSettings(settings); mSettingsFragment.setAppSettings(settings);
String appName; String appName;

View File

@@ -103,7 +103,7 @@ public class RemoteServiceActivity extends ActionBarActivity {
public void onClick(View v) { public void onClick(View v) {
// Allow // Allow
ProviderHelper.insertApiApp(RemoteServiceActivity.this, new ProviderHelper(RemoteServiceActivity.this).insertApiApp(
mAppSettingsFragment.getAppSettings()); mAppSettingsFragment.getAppSettings());
// give data through for new service call // give data through for new service call
@@ -146,7 +146,7 @@ public class RemoteServiceActivity extends ActionBarActivity {
mAccSettingsFragment.setErrorOnSelectKeyFragment( mAccSettingsFragment.setErrorOnSelectKeyFragment(
getString(R.string.api_register_error_select_key)); getString(R.string.api_register_error_select_key));
} else { } else {
ProviderHelper.insertApiAccount(RemoteServiceActivity.this, new ProviderHelper(RemoteServiceActivity.this).insertApiAccount(
KeychainContract.ApiAccounts.buildBaseUri(packageName), KeychainContract.ApiAccounts.buildBaseUri(packageName),
mAccSettingsFragment.getAccSettings()); mAccSettingsFragment.getAccSettings());
@@ -179,19 +179,19 @@ public class RemoteServiceActivity extends ActionBarActivity {
final Intent resultData = extras.getParcelable(EXTRA_DATA); final Intent resultData = extras.getParcelable(EXTRA_DATA);
PassphraseDialogFragment.show(this, secretKeyId, PassphraseDialogFragment.show(this, secretKeyId,
new Handler() { new Handler() {
@Override @Override
public void handleMessage(Message message) { public void handleMessage(Message message) {
if (message.what == PassphraseDialogFragment.MESSAGE_OKAY) { if (message.what == PassphraseDialogFragment.MESSAGE_OKAY) {
// return given params again, for calling the service method again // return given params again, for calling the service method again
RemoteServiceActivity.this.setResult(RESULT_OK, resultData); RemoteServiceActivity.this.setResult(RESULT_OK, resultData);
} else { } else {
RemoteServiceActivity.this.setResult(RESULT_CANCELED); RemoteServiceActivity.this.setResult(RESULT_CANCELED);
} }
RemoteServiceActivity.this.finish(); RemoteServiceActivity.this.finish();
} }
}); });
} else if (ACTION_SELECT_PUB_KEYS.equals(action)) { } else if (ACTION_SELECT_PUB_KEYS.equals(action)) {
long[] selectedMasterKeyIds = intent.getLongArrayExtra(EXTRA_SELECTED_MASTER_KEY_IDS); long[] selectedMasterKeyIds = intent.getLongArrayExtra(EXTRA_SELECTED_MASTER_KEY_IDS);

View File

@@ -496,20 +496,21 @@ public class KeychainIntentService extends IntentService
long masterKeyId = saveParcel.keys.get(0).getKeyID(); long masterKeyId = saveParcel.keys.get(0).getKeyID();
/* Operation */ /* Operation */
ProviderHelper providerHelper = new ProviderHelper(this);
if (!canSign) { if (!canSign) {
PgpKeyOperation keyOperations = new PgpKeyOperation(new ProgressScaler(this, 0, 50, 100)); PgpKeyOperation keyOperations = new PgpKeyOperation(new ProgressScaler(this, 0, 50, 100));
PGPSecretKeyRing keyRing = ProviderHelper.getPGPSecretKeyRing(this, masterKeyId); PGPSecretKeyRing keyRing = providerHelper.getPGPSecretKeyRing(masterKeyId);
keyRing = keyOperations.changeSecretKeyPassphrase(keyRing, keyRing = keyOperations.changeSecretKeyPassphrase(keyRing,
oldPassphrase, newPassphrase); oldPassphrase, newPassphrase);
setProgress(R.string.progress_saving_key_ring, 50, 100); setProgress(R.string.progress_saving_key_ring, 50, 100);
ProviderHelper.saveKeyRing(this, keyRing); providerHelper.saveKeyRing(keyRing);
setProgress(R.string.progress_done, 100, 100); setProgress(R.string.progress_done, 100, 100);
} else { } else {
PgpKeyOperation keyOperations = new PgpKeyOperation(new ProgressScaler(this, 0, 90, 100)); PgpKeyOperation keyOperations = new PgpKeyOperation(new ProgressScaler(this, 0, 90, 100));
PgpKeyOperation.Pair<PGPSecretKeyRing, PGPPublicKeyRing> pair; PgpKeyOperation.Pair<PGPSecretKeyRing, PGPPublicKeyRing> pair;
try { try {
PGPSecretKeyRing privkey = ProviderHelper.getPGPSecretKeyRing(this, masterKeyId); PGPSecretKeyRing privkey = providerHelper.getPGPSecretKeyRing(masterKeyId);
PGPPublicKeyRing pubkey = ProviderHelper.getPGPPublicKeyRing(this, masterKeyId); PGPPublicKeyRing pubkey = providerHelper.getPGPPublicKeyRing(masterKeyId);
pair = keyOperations.buildSecretKey(privkey, pubkey, saveParcel); // edit existing pair = keyOperations.buildSecretKey(privkey, pubkey, saveParcel); // edit existing
} catch (ProviderHelper.NotFoundException e) { } catch (ProviderHelper.NotFoundException e) {
@@ -518,7 +519,7 @@ public class KeychainIntentService extends IntentService
setProgress(R.string.progress_saving_key_ring, 90, 100); setProgress(R.string.progress_saving_key_ring, 90, 100);
// save the pair // save the pair
ProviderHelper.saveKeyRing(this, pair.second, pair.first); providerHelper.saveKeyRing(pair.second, pair.first);
setProgress(R.string.progress_done, 100, 100); setProgress(R.string.progress_done, 100, 100);
} }
PassphraseCacheService.addCachedPassphrase(this, masterKeyId, newPassphrase); PassphraseCacheService.addCachedPassphrase(this, masterKeyId, newPassphrase);
@@ -707,7 +708,8 @@ public class KeychainIntentService extends IntentService
/* Operation */ /* Operation */
HkpKeyServer server = new HkpKeyServer(keyServer); HkpKeyServer server = new HkpKeyServer(keyServer);
PGPPublicKeyRing keyring = (PGPPublicKeyRing) ProviderHelper.getPGPKeyRing(this, dataUri); ProviderHelper providerHelper = new ProviderHelper(this);
PGPPublicKeyRing keyring = (PGPPublicKeyRing) providerHelper.getPGPKeyRing(dataUri);
if (keyring != null) { if (keyring != null) {
PgpImportExport pgpImportExport = new PgpImportExport(this, null); PgpImportExport pgpImportExport = new PgpImportExport(this, null);
@@ -808,12 +810,13 @@ public class KeychainIntentService extends IntentService
throw new PgpGeneralException("Unable to obtain passphrase"); throw new PgpGeneralException("Unable to obtain passphrase");
} }
ProviderHelper providerHelper = new ProviderHelper(this);
PgpKeyOperation keyOperation = new PgpKeyOperation(new ProgressScaler(this, 0, 100, 100)); PgpKeyOperation keyOperation = new PgpKeyOperation(new ProgressScaler(this, 0, 100, 100));
PGPPublicKeyRing publicRing = ProviderHelper.getPGPPublicKeyRing(this, pubKeyId); PGPPublicKeyRing publicRing = providerHelper.getPGPPublicKeyRing(pubKeyId);
PGPPublicKey publicKey = publicRing.getPublicKey(pubKeyId); PGPPublicKey publicKey = publicRing.getPublicKey(pubKeyId);
PGPSecretKeyRing secretKeyRing = null; PGPSecretKeyRing secretKeyRing = null;
try { try {
secretKeyRing = ProviderHelper.getPGPSecretKeyRing(this, masterKeyId); secretKeyRing = providerHelper.getPGPSecretKeyRing(masterKeyId);
} catch (ProviderHelper.NotFoundException e) { } catch (ProviderHelper.NotFoundException e) {
Log.e(Constants.TAG, "key not found!", e); Log.e(Constants.TAG, "key not found!", e);
// TODO: throw exception here! // TODO: throw exception here!

View File

@@ -172,7 +172,7 @@ public class PassphraseCacheService extends Service {
long masterKeyId = keyId; long masterKeyId = keyId;
if (masterKeyId != Id.key.symmetric) { if (masterKeyId != Id.key.symmetric) {
try { try {
masterKeyId = ProviderHelper.getMasterKeyId(this, masterKeyId = new ProviderHelper(this).getMasterKeyId(
KeychainContract.KeyRings.buildUnifiedKeyRingsFindBySubkeyUri(Long.toString(keyId))); KeychainContract.KeyRings.buildUnifiedKeyRingsFindBySubkeyUri(Long.toString(keyId)));
} catch (ProviderHelper.NotFoundException e) { } catch (ProviderHelper.NotFoundException e) {
return null; return null;
@@ -234,7 +234,7 @@ public class PassphraseCacheService extends Service {
public static boolean hasPassphrase(Context context, long secretKeyId) { public static boolean hasPassphrase(Context context, long secretKeyId) {
// check if the key has no passphrase // check if the key has no passphrase
try { try {
PGPSecretKeyRing secRing = ProviderHelper.getPGPSecretKeyRing(context, secretKeyId); PGPSecretKeyRing secRing = new ProviderHelper(context).getPGPSecretKeyRing(secretKeyId);
return hasPassphrase(secRing); return hasPassphrase(secRing);
} catch (ProviderHelper.NotFoundException e) { } catch (ProviderHelper.NotFoundException e) {
Log.e(Constants.TAG, "key not found!", e); Log.e(Constants.TAG, "key not found!", e);

View File

@@ -39,6 +39,7 @@ import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ListView; import android.widget.ListView;
import android.widget.Spinner; import android.widget.Spinner;
import android.widget.TextView; import android.widget.TextView;
import com.beardedhen.androidbootstrap.BootstrapButton; import com.beardedhen.androidbootstrap.BootstrapButton;
import com.devspark.appmsg.AppMsg; import com.devspark.appmsg.AppMsg;
@@ -159,7 +160,7 @@ public class CertifyKeyActivity extends ActionBarActivity implements
static final String USER_IDS_SELECTION = UserIds.IS_REVOKED + " = 0"; static final String USER_IDS_SELECTION = UserIds.IS_REVOKED + " = 0";
static final String[] KEYRING_PROJECTION = static final String[] KEYRING_PROJECTION =
new String[] { new String[]{
KeyRings._ID, KeyRings._ID,
KeyRings.MASTER_KEY_ID, KeyRings.MASTER_KEY_ID,
KeyRings.FINGERPRINT, KeyRings.FINGERPRINT,
@@ -171,7 +172,7 @@ public class CertifyKeyActivity extends ActionBarActivity implements
@Override @Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) { public Loader<Cursor> onCreateLoader(int id, Bundle args) {
switch(id) { switch (id) {
case LOADER_ID_KEYRING: { case LOADER_ID_KEYRING: {
Uri uri = KeyRings.buildUnifiedKeyRingUri(mDataUri); Uri uri = KeyRings.buildUnifiedKeyRingUri(mDataUri);
return new CursorLoader(this, uri, KEYRING_PROJECTION, null, null, null); return new CursorLoader(this, uri, KEYRING_PROJECTION, null, null, null);
@@ -187,7 +188,7 @@ public class CertifyKeyActivity extends ActionBarActivity implements
@Override @Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) { public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
switch(loader.getId()) { switch (loader.getId()) {
case LOADER_ID_KEYRING: case LOADER_ID_KEYRING:
// the first key here is our master key // the first key here is our master key
if (data.moveToFirst()) { if (data.moveToFirst()) {
@@ -202,7 +203,7 @@ public class CertifyKeyActivity extends ActionBarActivity implements
byte[] fingerprintBlob = data.getBlob(INDEX_FINGERPRINT); byte[] fingerprintBlob = data.getBlob(INDEX_FINGERPRINT);
String fingerprint = PgpKeyHelper.convertFingerprintToHex(fingerprintBlob); String fingerprint = PgpKeyHelper.convertFingerprintToHex(fingerprintBlob);
((TextView) findViewById(R.id.fingerprint)) ((TextView) findViewById(R.id.fingerprint))
.setText(PgpKeyHelper.colorizeFingerprint(fingerprint)); .setText(PgpKeyHelper.colorizeFingerprint(fingerprint));
} }
break; break;
case LOADER_ID_USER_IDS: case LOADER_ID_USER_IDS:
@@ -213,7 +214,7 @@ public class CertifyKeyActivity extends ActionBarActivity implements
@Override @Override
public void onLoaderReset(Loader<Cursor> loader) { public void onLoaderReset(Loader<Cursor> loader) {
switch(loader.getId()) { switch (loader.getId()) {
case LOADER_ID_USER_IDS: case LOADER_ID_USER_IDS:
mUserIdsAdapter.swapCursor(null); mUserIdsAdapter.swapCursor(null);
break; break;
@@ -225,7 +226,7 @@ public class CertifyKeyActivity extends ActionBarActivity implements
*/ */
private void initiateSigning() { private void initiateSigning() {
try { try {
PGPPublicKeyRing pubring = ProviderHelper.getPGPPublicKeyRing(this, mPubKeyId); PGPPublicKeyRing pubring = new ProviderHelper(this).getPGPPublicKeyRing(mPubKeyId);
// if we have already signed this key, dont bother doing it again // if we have already signed this key, dont bother doing it again
boolean alreadySigned = false; boolean alreadySigned = false;

View File

@@ -290,7 +290,7 @@ public class EditKeyActivity extends ActionBarActivity implements EditorListener
try { try {
Uri secretUri = KeychainContract.KeyRingData.buildSecretKeyRingUri(mDataUri); Uri secretUri = KeychainContract.KeyRingData.buildSecretKeyRingUri(mDataUri);
mKeyRing = (PGPSecretKeyRing) ProviderHelper.getPGPKeyRing(this, secretUri); mKeyRing = (PGPSecretKeyRing) new ProviderHelper(this).getPGPKeyRing(secretUri);
PGPSecretKey masterKey = mKeyRing.getSecretKey(); PGPSecretKey masterKey = mKeyRing.getSecretKey();
mMasterCanSign = PgpKeyHelper.isCertificationKey(mKeyRing.getSecretKey()); mMasterCanSign = PgpKeyHelper.isCertificationKey(mKeyRing.getSecretKey());

View File

@@ -53,6 +53,8 @@ public class EncryptAsymmetricFragment extends Fragment {
public static final int RESULT_CODE_PUBLIC_KEYS = 0x00007001; public static final int RESULT_CODE_PUBLIC_KEYS = 0x00007001;
public static final int RESULT_CODE_SECRET_KEYS = 0x00007002; public static final int RESULT_CODE_SECRET_KEYS = 0x00007002;
ProviderHelper mProviderHelper;
OnAsymmetricKeySelection mKeySelectionListener; OnAsymmetricKeySelection mKeySelectionListener;
// view // view
@@ -133,8 +135,10 @@ public class EncryptAsymmetricFragment extends Fragment {
long signatureKeyId = getArguments().getLong(ARG_SIGNATURE_KEY_ID); long signatureKeyId = getArguments().getLong(ARG_SIGNATURE_KEY_ID);
long[] encryptionKeyIds = getArguments().getLongArray(ARG_ENCRYPTION_KEY_IDS); long[] encryptionKeyIds = getArguments().getLongArray(ARG_ENCRYPTION_KEY_IDS);
mProviderHelper = new ProviderHelper(getActivity());
// preselect keys given by arguments (given by Intent to EncryptActivity) // preselect keys given by arguments (given by Intent to EncryptActivity)
preselectKeys(signatureKeyId, encryptionKeyIds); preselectKeys(signatureKeyId, encryptionKeyIds, mProviderHelper);
} }
/** /**
@@ -143,11 +147,12 @@ public class EncryptAsymmetricFragment extends Fragment {
* @param preselectedSignatureKeyId * @param preselectedSignatureKeyId
* @param preselectedEncryptionKeyIds * @param preselectedEncryptionKeyIds
*/ */
private void preselectKeys(long preselectedSignatureKeyId, long[] preselectedEncryptionKeyIds) { private void preselectKeys(long preselectedSignatureKeyId, long[] preselectedEncryptionKeyIds,
ProviderHelper providerHelper) {
if (preselectedSignatureKeyId != 0) { if (preselectedSignatureKeyId != 0) {
// TODO: don't use bouncy castle objects! // TODO: don't use bouncy castle objects!
try { try {
PGPSecretKeyRing keyRing = ProviderHelper.getPGPSecretKeyRingWithKeyId(getActivity(), PGPSecretKeyRing keyRing = providerHelper.getPGPSecretKeyRingWithKeyId(
preselectedSignatureKeyId); preselectedSignatureKeyId);
PGPSecretKey masterKey = keyRing.getSecretKey(); PGPSecretKey masterKey = keyRing.getSecretKey();
@@ -167,7 +172,7 @@ public class EncryptAsymmetricFragment extends Fragment {
for (int i = 0; i < preselectedEncryptionKeyIds.length; ++i) { for (int i = 0; i < preselectedEncryptionKeyIds.length; ++i) {
// TODO One query per selected key?! wtf // TODO One query per selected key?! wtf
try { try {
long id = ProviderHelper.getMasterKeyId(getActivity(), long id = providerHelper.getMasterKeyId(
KeyRings.buildUnifiedKeyRingsFindBySubkeyUri( KeyRings.buildUnifiedKeyRingsFindBySubkeyUri(
Long.toString(preselectedEncryptionKeyIds[i])) Long.toString(preselectedEncryptionKeyIds[i]))
); );
@@ -201,8 +206,8 @@ public class EncryptAsymmetricFragment extends Fragment {
mMainUserIdRest.setText(""); mMainUserIdRest.setText("");
} else { } else {
// See if we can get a user_id from a unified query // See if we can get a user_id from a unified query
String userIdResult = (String) ProviderHelper.getUnifiedData( String userIdResult = (String) mProviderHelper.getUnifiedData(
getActivity(), mSecretKeyId, KeyRings.USER_ID, ProviderHelper.FIELD_TYPE_STRING); mSecretKeyId, KeyRings.USER_ID, ProviderHelper.FIELD_TYPE_STRING);
String[] userId = PgpKeyHelper.splitUserId(userIdResult); String[] userId = PgpKeyHelper.splitUserId(userIdResult);
if (userId[0] != null) { if (userId[0] != null) {
mMainUserId.setText(userId[0]); mMainUserId.setText(userId[0]);

View File

@@ -145,10 +145,11 @@ public class ViewCertActivity extends ActionBarActivity
PGPSignature sig = PgpConversionHelper.BytesToPGPSignature(data.getBlob(INDEX_DATA)); PGPSignature sig = PgpConversionHelper.BytesToPGPSignature(data.getBlob(INDEX_DATA));
try { try {
PGPKeyRing signeeRing = ProviderHelper.getPGPKeyRing(this, ProviderHelper providerHelper = new ProviderHelper(this);
PGPKeyRing signeeRing = providerHelper.getPGPKeyRing(
KeychainContract.KeyRingData.buildPublicKeyRingUri( KeychainContract.KeyRingData.buildPublicKeyRingUri(
Long.toString(data.getLong(INDEX_MASTER_KEY_ID)))); Long.toString(data.getLong(INDEX_MASTER_KEY_ID))));
PGPKeyRing signerRing = ProviderHelper.getPGPKeyRing(this, PGPKeyRing signerRing = providerHelper.getPGPKeyRing(
KeychainContract.KeyRingData.buildPublicKeyRingUri( KeychainContract.KeyRingData.buildPublicKeyRingUri(
Long.toString(sig.getKeyID()))); Long.toString(sig.getKeyID())));
@@ -230,7 +231,8 @@ public class ViewCertActivity extends ActionBarActivity
Intent viewIntent = new Intent(this, ViewKeyActivity.class); Intent viewIntent = new Intent(this, ViewKeyActivity.class);
try { try {
long signerMasterKeyId = ProviderHelper.getMasterKeyId(this, ProviderHelper providerHelper = new ProviderHelper(this);
long signerMasterKeyId = providerHelper.getMasterKeyId(
KeyRings.buildUnifiedKeyRingsFindBySubkeyUri(Long.toString(mSignerKeyId)) KeyRings.buildUnifiedKeyRingsFindBySubkeyUri(Long.toString(mSignerKeyId))
); );
viewIntent.setData(KeyRings.buildGenericKeyRingUri( viewIntent.setData(KeyRings.buildGenericKeyRingUri(

View File

@@ -54,12 +54,14 @@ import org.sufficientlysecure.keychain.ui.dialog.ShareQrCodeDialogFragment;
import org.sufficientlysecure.keychain.util.Log; import org.sufficientlysecure.keychain.util.Log;
import java.io.IOException; import java.io.IOException;
import java.security.Provider;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
public class ViewKeyActivity extends ActionBarActivity { public class ViewKeyActivity extends ActionBarActivity {
ExportHelper mExportHelper; ExportHelper mExportHelper;
ProviderHelper mProviderHelper;
protected Uri mDataUri; protected Uri mDataUri;
@@ -83,6 +85,7 @@ public class ViewKeyActivity extends ActionBarActivity {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
mExportHelper = new ExportHelper(this); mExportHelper = new ExportHelper(this);
mProviderHelper = new ProviderHelper(this);
// let the actionbar look like Android's contact app // let the actionbar look like Android's contact app
ActionBar actionBar = getSupportActionBar(); ActionBar actionBar = getSupportActionBar();
@@ -134,19 +137,19 @@ public class ViewKeyActivity extends ActionBarActivity {
startActivity(homeIntent); startActivity(homeIntent);
return true; return true;
case R.id.menu_key_view_update: case R.id.menu_key_view_update:
updateFromKeyserver(mDataUri); updateFromKeyserver(mDataUri, mProviderHelper);
return true; return true;
case R.id.menu_key_view_export_keyserver: case R.id.menu_key_view_export_keyserver:
uploadToKeyserver(mDataUri); uploadToKeyserver(mDataUri);
return true; return true;
case R.id.menu_key_view_export_file: case R.id.menu_key_view_export_file:
exportToFile(mDataUri, mExportHelper); exportToFile(mDataUri, mExportHelper, mProviderHelper);
return true; return true;
case R.id.menu_key_view_share_default_fingerprint: case R.id.menu_key_view_share_default_fingerprint:
shareKey(mDataUri, true); shareKey(mDataUri, true, mProviderHelper);
return true; return true;
case R.id.menu_key_view_share_default: case R.id.menu_key_view_share_default:
shareKey(mDataUri, false); shareKey(mDataUri, false, mProviderHelper);
return true; return true;
case R.id.menu_key_view_share_qr_code_fingerprint: case R.id.menu_key_view_share_qr_code_fingerprint:
shareKeyQrCode(mDataUri, true); shareKeyQrCode(mDataUri, true);
@@ -158,7 +161,7 @@ public class ViewKeyActivity extends ActionBarActivity {
shareNfc(); shareNfc();
return true; return true;
case R.id.menu_key_view_share_clipboard: case R.id.menu_key_view_share_clipboard:
copyToClipboard(mDataUri); copyToClipboard(mDataUri, mProviderHelper);
return true; return true;
case R.id.menu_key_view_delete: { case R.id.menu_key_view_delete: {
deleteKey(mDataUri, mExportHelper); deleteKey(mDataUri, mExportHelper);
@@ -168,10 +171,10 @@ public class ViewKeyActivity extends ActionBarActivity {
return super.onOptionsItemSelected(item); return super.onOptionsItemSelected(item);
} }
private void exportToFile(Uri dataUri, ExportHelper exportHelper) { private void exportToFile(Uri dataUri, ExportHelper exportHelper, ProviderHelper providerHelper) {
Uri baseUri = KeychainContract.KeyRings.buildUnifiedKeyRingUri(dataUri); Uri baseUri = KeychainContract.KeyRings.buildUnifiedKeyRingUri(dataUri);
HashMap<String, Object> data = ProviderHelper.getGenericData(this, HashMap<String, Object> data = providerHelper.getGenericData(
baseUri, baseUri,
new String[]{KeychainContract.Keys.MASTER_KEY_ID, KeychainContract.KeyRings.HAS_SECRET}, new String[]{KeychainContract.Keys.MASTER_KEY_ID, KeychainContract.KeyRings.HAS_SECRET},
new int[]{ProviderHelper.FIELD_TYPE_INTEGER, ProviderHelper.FIELD_TYPE_INTEGER}); new int[]{ProviderHelper.FIELD_TYPE_INTEGER, ProviderHelper.FIELD_TYPE_INTEGER});
@@ -189,9 +192,9 @@ public class ViewKeyActivity extends ActionBarActivity {
startActivityForResult(uploadIntent, Id.request.export_to_server); startActivityForResult(uploadIntent, Id.request.export_to_server);
} }
private void updateFromKeyserver(Uri dataUri) { private void updateFromKeyserver(Uri dataUri, ProviderHelper providerHelper) {
byte[] blob = (byte[]) ProviderHelper.getGenericData( byte[] blob = (byte[]) providerHelper.getGenericData(
this, KeychainContract.KeyRings.buildUnifiedKeyRingUri(dataUri), KeychainContract.KeyRings.buildUnifiedKeyRingUri(dataUri),
KeychainContract.Keys.FINGERPRINT, ProviderHelper.FIELD_TYPE_BLOB); KeychainContract.Keys.FINGERPRINT, ProviderHelper.FIELD_TYPE_BLOB);
String fingerprint = PgpKeyHelper.convertFingerprintToHex(blob); String fingerprint = PgpKeyHelper.convertFingerprintToHex(blob);
@@ -202,11 +205,11 @@ public class ViewKeyActivity extends ActionBarActivity {
startActivityForResult(queryIntent, RESULT_CODE_LOOKUP_KEY); startActivityForResult(queryIntent, RESULT_CODE_LOOKUP_KEY);
} }
private void shareKey(Uri dataUri, boolean fingerprintOnly) { private void shareKey(Uri dataUri, boolean fingerprintOnly, ProviderHelper providerHelper) {
String content = null; String content = null;
if (fingerprintOnly) { if (fingerprintOnly) {
byte[] data = (byte[]) ProviderHelper.getGenericData( byte[] data = (byte[]) providerHelper.getGenericData(
this, KeychainContract.KeyRings.buildUnifiedKeyRingUri(dataUri), KeychainContract.KeyRings.buildUnifiedKeyRingUri(dataUri),
KeychainContract.Keys.FINGERPRINT, ProviderHelper.FIELD_TYPE_BLOB); KeychainContract.Keys.FINGERPRINT, ProviderHelper.FIELD_TYPE_BLOB);
if (data != null) { if (data != null) {
String fingerprint = PgpKeyHelper.convertFingerprintToHex(data); String fingerprint = PgpKeyHelper.convertFingerprintToHex(data);
@@ -220,7 +223,7 @@ public class ViewKeyActivity extends ActionBarActivity {
// get public keyring as ascii armored string // get public keyring as ascii armored string
try { try {
Uri uri = KeychainContract.KeyRingData.buildPublicKeyRingUri(dataUri); Uri uri = KeychainContract.KeyRingData.buildPublicKeyRingUri(dataUri);
content = ProviderHelper.getKeyRingAsArmoredString(this, uri); content = providerHelper.getKeyRingAsArmoredString(uri);
// Android will fail with android.os.TransactionTooLargeException if key is too big // Android will fail with android.os.TransactionTooLargeException if key is too big
// see http://www.lonestarprod.com/?p=34 // see http://www.lonestarprod.com/?p=34
@@ -256,11 +259,11 @@ public class ViewKeyActivity extends ActionBarActivity {
dialog.show(getSupportFragmentManager(), "shareQrCodeDialog"); dialog.show(getSupportFragmentManager(), "shareQrCodeDialog");
} }
private void copyToClipboard(Uri dataUri) { private void copyToClipboard(Uri dataUri, ProviderHelper providerHelper) {
// get public keyring as ascii armored string // get public keyring as ascii armored string
try { try {
Uri uri = KeychainContract.KeyRingData.buildPublicKeyRingUri(dataUri); Uri uri = KeychainContract.KeyRingData.buildPublicKeyRingUri(dataUri);
String keyringArmored = ProviderHelper.getKeyRingAsArmoredString(this, uri); String keyringArmored = providerHelper.getKeyRingAsArmoredString(uri);
ClipboardReflection.copyToClipboard(this, keyringArmored); ClipboardReflection.copyToClipboard(this, keyringArmored);
AppMsg.makeText(this, R.string.key_copied_to_clipboard, AppMsg.STYLE_INFO) AppMsg.makeText(this, R.string.key_copied_to_clipboard, AppMsg.STYLE_INFO)
@@ -359,8 +362,8 @@ public class ViewKeyActivity extends ActionBarActivity {
try { try {
Uri blobUri = Uri blobUri =
KeychainContract.KeyRingData.buildPublicKeyRingUri(dataUri); KeychainContract.KeyRingData.buildPublicKeyRingUri(dataUri);
mNfcKeyringBytes = ProviderHelper.getPGPKeyRing( mNfcKeyringBytes = mProviderHelper.getPGPKeyRing(
ViewKeyActivity.this, blobUri).getEncoded(); blobUri).getEncoded();
} catch (IOException e) { } catch (IOException e) {
Log.e(Constants.TAG, "Error parsing keyring", e); Log.e(Constants.TAG, "Error parsing keyring", e);
} catch (ProviderHelper.NotFoundException e) { } catch (ProviderHelper.NotFoundException e) {

View File

@@ -332,7 +332,7 @@ public class ViewKeyMainFragment extends Fragment implements
private void encryptToContact(Uri dataUri) { private void encryptToContact(Uri dataUri) {
try { try {
long keyId = ProviderHelper.extractOrGetMasterKeyId(getActivity(), dataUri); long keyId = new ProviderHelper(getActivity()).extractOrGetMasterKeyId(dataUri);
long[] encryptionKeyIds = new long[]{ keyId }; long[] encryptionKeyIds = new long[]{ keyId };
Intent intent = new Intent(getActivity(), EncryptActivity.class); Intent intent = new Intent(getActivity(), EncryptActivity.class);
intent.setAction(EncryptActivity.ACTION_ENCRYPT); intent.setAction(EncryptActivity.ACTION_ENCRYPT);

View File

@@ -102,7 +102,7 @@ public class DeleteKeyDialogFragment extends DialogFragment {
long masterKeyId = masterKeyIds[0]; long masterKeyId = masterKeyIds[0];
HashMap<String, Object> data = ProviderHelper.getUnifiedData(activity, masterKeyId, new String[]{ HashMap<String, Object> data = new ProviderHelper(activity).getUnifiedData(masterKeyId, new String[]{
KeyRings.USER_ID, KeyRings.USER_ID,
KeyRings.HAS_SECRET KeyRings.HAS_SECRET
}, new int[] { ProviderHelper.FIELD_TYPE_STRING, ProviderHelper.FIELD_TYPE_INTEGER }); }, new int[] { ProviderHelper.FIELD_TYPE_STRING, ProviderHelper.FIELD_TYPE_INTEGER });

View File

@@ -140,7 +140,7 @@ public class PassphraseDialogFragment extends DialogFragment implements OnEditor
alert.setMessage(R.string.passphrase_for_symmetric_encryption); alert.setMessage(R.string.passphrase_for_symmetric_encryption);
} else { } else {
try { try {
secretKey = ProviderHelper.getPGPSecretKeyRing(activity, secretKeyId).getSecretKey(); secretKey = new ProviderHelper(activity).getPGPSecretKeyRing(secretKeyId).getSecretKey();
} catch (ProviderHelper.NotFoundException e) { } catch (ProviderHelper.NotFoundException e) {
alert.setTitle(R.string.title_key_not_found); alert.setTitle(R.string.title_key_not_found);
alert.setMessage(getString(R.string.key_not_found, secretKeyId)); alert.setMessage(getString(R.string.key_not_found, secretKeyId));
@@ -196,8 +196,8 @@ public class PassphraseDialogFragment extends DialogFragment implements OnEditor
return; return;
} else { } else {
try { try {
clickSecretKey = PgpKeyHelper.getKeyNum(ProviderHelper clickSecretKey = PgpKeyHelper.getKeyNum(new ProviderHelper(activity)
.getPGPSecretKeyRingWithKeyId(activity, secretKeyId), .getPGPSecretKeyRingWithKeyId(secretKeyId),
curKeyIndex); curKeyIndex);
} catch (ProviderHelper.NotFoundException e) { } catch (ProviderHelper.NotFoundException e) {
Log.e(Constants.TAG, "key not found!", e); Log.e(Constants.TAG, "key not found!", e);

View File

@@ -41,6 +41,7 @@ import org.sufficientlysecure.keychain.util.Log;
import org.sufficientlysecure.keychain.util.QrCodeUtils; import org.sufficientlysecure.keychain.util.QrCodeUtils;
import java.io.IOException; import java.io.IOException;
import java.security.Provider;
import java.util.ArrayList; import java.util.ArrayList;
public class ShareQrCodeDialogFragment extends DialogFragment { public class ShareQrCodeDialogFragment extends DialogFragment {
@@ -91,14 +92,15 @@ public class ShareQrCodeDialogFragment extends DialogFragment {
mImage = (ImageView) view.findViewById(R.id.share_qr_code_dialog_image); mImage = (ImageView) view.findViewById(R.id.share_qr_code_dialog_image);
mText = (TextView) view.findViewById(R.id.share_qr_code_dialog_text); mText = (TextView) view.findViewById(R.id.share_qr_code_dialog_text);
ProviderHelper providerHelper = new ProviderHelper(getActivity());
String content = null; String content = null;
if (mFingerprintOnly) { if (mFingerprintOnly) {
alert.setPositiveButton(R.string.btn_okay, null); alert.setPositiveButton(R.string.btn_okay, null);
byte[] blob = (byte[]) ProviderHelper.getGenericData( byte[] blob = (byte[]) providerHelper.getGenericData(
getActivity(), KeyRings.buildUnifiedKeyRingUri(dataUri), KeyRings.buildUnifiedKeyRingUri(dataUri),
KeyRings.FINGERPRINT, ProviderHelper.FIELD_TYPE_BLOB); KeyRings.FINGERPRINT, ProviderHelper.FIELD_TYPE_BLOB);
if(blob == null) { if (blob == null) {
Log.e(Constants.TAG, "key not found!"); Log.e(Constants.TAG, "key not found!");
AppMsg.makeText(getActivity(), R.string.error_key_not_found, AppMsg.STYLE_ALERT).show(); AppMsg.makeText(getActivity(), R.string.error_key_not_found, AppMsg.STYLE_ALERT).show();
return null; return null;
@@ -113,7 +115,7 @@ public class ShareQrCodeDialogFragment extends DialogFragment {
try { try {
Uri uri = KeychainContract.KeyRingData.buildPublicKeyRingUri(dataUri); Uri uri = KeychainContract.KeyRingData.buildPublicKeyRingUri(dataUri);
content = ProviderHelper.getKeyRingAsArmoredString(getActivity(), uri); content = providerHelper.getKeyRingAsArmoredString(uri);
} catch (IOException e) { } catch (IOException e) {
Log.e(Constants.TAG, "error processing key!", e); Log.e(Constants.TAG, "error processing key!", e);
AppMsg.makeText(getActivity(), R.string.error_invalid_data, AppMsg.STYLE_ALERT).show(); AppMsg.makeText(getActivity(), R.string.error_invalid_data, AppMsg.STYLE_ALERT).show();