Many API fixes for GET_KEY and GET_KEY_IDS

This commit is contained in:
Dominik Schürmann 2014-04-28 20:13:46 +02:00
parent 3538bf8202
commit 0963efc78b
8 changed files with 209 additions and 70 deletions

View file

@ -34,11 +34,13 @@ import org.openintents.openpgp.OpenPgpError;
import org.openintents.openpgp.OpenPgpSignatureResult;
import org.openintents.openpgp.util.OpenPgpApi;
import org.openintents.openpgp.util.OpenPgpServiceConnection;
import org.openintents.openpgp.util.OpenPgpUtils;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
public class OpenPgpProviderActivity extends Activity {
private EditText mMessage;
@ -49,6 +51,10 @@ public class OpenPgpProviderActivity extends Activity {
private Button mSignAndEncrypt;
private Button mDecryptAndVerify;
private EditText mAccount;
private EditText mGetKeyEdit;
private EditText mGetKeyIdsEdit;
private Button mGetKey;
private Button mGetKeyIds;
private OpenPgpServiceConnection mServiceConnection;
@ -56,6 +62,8 @@ public class OpenPgpProviderActivity extends Activity {
public static final int REQUEST_CODE_ENCRYPT = 9911;
public static final int REQUEST_CODE_SIGN_AND_ENCRYPT = 9912;
public static final int REQUEST_CODE_DECRYPT_AND_VERIFY = 9913;
public static final int REQUEST_CODE_GET_KEY = 9914;
public static final int REQUEST_CODE_GET_KEY_IDS = 9915;
@Override
public void onCreate(Bundle savedInstanceState) {
@ -70,6 +78,10 @@ public class OpenPgpProviderActivity extends Activity {
mSignAndEncrypt = (Button) findViewById(R.id.crypto_provider_demo_sign_and_encrypt);
mDecryptAndVerify = (Button) findViewById(R.id.crypto_provider_demo_decrypt_and_verify);
mAccount = (EditText) findViewById(R.id.crypto_provider_demo_account);
mGetKeyEdit = (EditText) findViewById(R.id.crypto_provider_demo_get_key_edit);
mGetKeyIdsEdit = (EditText) findViewById(R.id.crypto_provider_demo_get_key_ids_edit);
mGetKey = (Button) findViewById(R.id.crypto_provider_demo_get_key);
mGetKeyIds = (Button) findViewById(R.id.crypto_provider_demo_get_key_ids);
mSign.setOnClickListener(new View.OnClickListener() {
@Override
@ -95,6 +107,18 @@ public class OpenPgpProviderActivity extends Activity {
decryptAndVerify(new Intent());
}
});
mGetKey.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getKey(new Intent());
}
});
mGetKeyIds.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getKeyIds(new Intent());
}
});
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
String providerPackageName = settings.getString("openpgp_provider_list", "");
@ -123,14 +147,14 @@ public class OpenPgpProviderActivity extends Activity {
});
}
private void handleSignature(final OpenPgpSignatureResult sigResult) {
private void showToast(final String message) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(OpenPgpProviderActivity.this,
sigResult.toString(),
Toast.LENGTH_LONG).show();
message,
Toast.LENGTH_SHORT).show();
}
});
}
@ -173,27 +197,46 @@ public class OpenPgpProviderActivity extends Activity {
public void onReturn(Intent result) {
switch (result.getIntExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_ERROR)) {
case OpenPgpApi.RESULT_CODE_SUCCESS: {
try {
Log.d(OpenPgpApi.TAG, "result: " + os.toByteArray().length
+ " str=" + os.toString("UTF-8"));
showToast("RESULT_CODE_SUCCESS");
if (returnToCiphertextField) {
mCiphertext.setText(os.toString("UTF-8"));
} else {
mMessage.setText(os.toString("UTF-8"));
// encrypt/decrypt/sign/verify
if (os != null) {
try {
Log.d(OpenPgpApi.TAG, "result: " + os.toByteArray().length
+ " str=" + os.toString("UTF-8"));
if (returnToCiphertextField) {
mCiphertext.setText(os.toString("UTF-8"));
} else {
mMessage.setText(os.toString("UTF-8"));
}
} catch (UnsupportedEncodingException e) {
Log.e(Constants.TAG, "UnsupportedEncodingException", e);
}
} catch (UnsupportedEncodingException e) {
Log.e(Constants.TAG, "UnsupportedEncodingException", e);
}
// verify
if (result.hasExtra(OpenPgpApi.RESULT_SIGNATURE)) {
OpenPgpSignatureResult sigResult
= result.getParcelableExtra(OpenPgpApi.RESULT_SIGNATURE);
handleSignature(sigResult);
showToast(sigResult.toString());
}
// get key ids
if (result.hasExtra(OpenPgpApi.RESULT_KEY_IDS)) {
long[] keyIds = result.getLongArrayExtra(OpenPgpApi.RESULT_KEY_IDS);
String out = "keyIds: ";
for (int i = 0; i < keyIds.length; i++) {
out += OpenPgpUtils.convertKeyIdToHex(keyIds[i]) + ", ";
}
showToast(out);
}
break;
}
case OpenPgpApi.RESULT_CODE_USER_INTERACTION_REQUIRED: {
showToast("RESULT_CODE_USER_INTERACTION_REQUIRED");
PendingIntent pi = result.getParcelableExtra(OpenPgpApi.RESULT_INTENT);
try {
OpenPgpProviderActivity.this.startIntentSenderForResult(pi.getIntentSender(),
@ -204,6 +247,8 @@ public class OpenPgpProviderActivity extends Activity {
break;
}
case OpenPgpApi.RESULT_CODE_ERROR: {
showToast("RESULT_CODE_ERROR");
OpenPgpError error = result.getParcelableExtra(OpenPgpApi.RESULT_ERROR);
handleError(error);
break;
@ -262,6 +307,24 @@ public class OpenPgpProviderActivity extends Activity {
api.executeApiAsync(data, is, os, new MyCallback(false, os, REQUEST_CODE_DECRYPT_AND_VERIFY));
}
public void getKey(Intent data) {
data.setAction(OpenPgpApi.ACTION_GET_KEY);
data.putExtra(OpenPgpApi.EXTRA_ACCOUNT_NAME, mAccount.getText().toString());
data.putExtra(OpenPgpApi.EXTRA_KEY_ID, Long.decode(mGetKeyEdit.getText().toString()));
OpenPgpApi api = new OpenPgpApi(this, mServiceConnection.getService());
api.executeApiAsync(data, null, null, new MyCallback(false, null, REQUEST_CODE_GET_KEY));
}
public void getKeyIds(Intent data) {
data.setAction(OpenPgpApi.ACTION_GET_KEY_IDS);
data.putExtra(OpenPgpApi.EXTRA_ACCOUNT_NAME, mAccount.getText().toString());
data.putExtra(OpenPgpApi.EXTRA_USER_IDS, mGetKeyIdsEdit.getText().toString().split(","));
OpenPgpApi api = new OpenPgpApi(this, mServiceConnection.getService());
api.executeApiAsync(data, null, null, new MyCallback(false, null, REQUEST_CODE_GET_KEY_IDS));
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
@ -292,6 +355,14 @@ public class OpenPgpProviderActivity extends Activity {
decryptAndVerify(data);
break;
}
case REQUEST_CODE_GET_KEY: {
getKey(data);
break;
}
case REQUEST_CODE_GET_KEY_IDS: {
getKeyIds(data);
break;
}
}
}
}

View file

@ -110,8 +110,7 @@
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Account ID:"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="@+id/textView" />
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:layout_width="match_parent"
@ -119,5 +118,41 @@
android:text="Alice &lt;alice@example.com&gt;"
android:id="@+id/crypto_provider_demo_account" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get key:"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="0x718c070100012282"
android:id="@+id/crypto_provider_demo_get_key_edit" />
<Button
android:id="@+id/crypto_provider_demo_get_key"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Get key" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get key ids:"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="dominik@dominikschuermann.de"
android:id="@+id/crypto_provider_demo_get_key_ids_edit" />
<Button
android:id="@+id/crypto_provider_demo_get_key_ids"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Get key ids" />
</LinearLayout>
</ScrollView>

View file

@ -19,6 +19,10 @@ package org.openintents.openpgp;
import android.os.Parcel;
import android.os.Parcelable;
import org.openintents.openpgp.util.OpenPgpUtils;
import java.util.Locale;
/**
* Parcelable versioning has been copied from Dashclock Widget
* https://code.google.com/p/dashclock/source/browse/api/src/main/java/com/google/android/apps/dashclock/api/ExtensionData.java
@ -152,7 +156,7 @@ public class OpenPgpSignatureResult implements Parcelable {
out += "\nstatus: " + status;
out += "\nuserId: " + userId;
out += "\nsignatureOnly: " + signatureOnly;
out += "\nkeyId: " + keyId;
out += "\nkeyId: " + OpenPgpUtils.convertKeyIdToHex(keyId);
return out;
}

View file

@ -23,8 +23,10 @@ import android.os.AsyncTask;
import android.os.Build;
import android.os.ParcelFileDescriptor;
import android.util.Log;
import org.openintents.openpgp.IOpenPgpService;
import org.openintents.openpgp.OpenPgpError;
import java.io.InputStream;
import java.io.OutputStream;
@ -34,7 +36,7 @@ public class OpenPgpApi {
public static final int API_VERSION = 3;
public static final String SERVICE_INTENT = "org.openintents.openpgp.IOpenPgpService";
/**
* General extras
* --------------
@ -50,7 +52,7 @@ public class OpenPgpApi {
/**
* Sign only
*
* <p/>
* optional extras:
* boolean EXTRA_REQUEST_ASCII_ARMOR (request ascii armor for ouput)
* String EXTRA_PASSPHRASE (key passphrase)
@ -59,12 +61,12 @@ public class OpenPgpApi {
/**
* Encrypt
*
* <p/>
* required extras:
* String[] EXTRA_USER_IDS (=emails of recipients, if more than one key has a user_id, a PendingIntent is returned via RESULT_INTENT)
* or
* long[] EXTRA_KEY_IDS
*
* <p/>
* optional extras:
* boolean EXTRA_REQUEST_ASCII_ARMOR (request ascii armor for ouput)
* String EXTRA_PASSPHRASE (key passphrase)
@ -73,12 +75,12 @@ public class OpenPgpApi {
/**
* Sign and encrypt
*
* <p/>
* required extras:
* String[] EXTRA_USER_IDS (=emails of recipients, if more than one key has a user_id, a PendingIntent is returned via RESULT_INTENT)
* or
* long[] EXTRA_KEY_IDS
*
* <p/>
* optional extras:
* boolean EXTRA_REQUEST_ASCII_ARMOR (request ascii armor for ouput)
* String EXTRA_PASSPHRASE (key passphrase)
@ -88,13 +90,13 @@ public class OpenPgpApi {
/**
* Decrypts and verifies given input stream. This methods handles encrypted-only, signed-and-encrypted,
* and also signed-only input.
*
* <p/>
* If OpenPgpSignatureResult.getStatus() == OpenPgpSignatureResult.SIGNATURE_UNKNOWN_PUB_KEY
* in addition a PendingIntent is returned via RESULT_INTENT to download missing keys.
*
* <p/>
* optional extras:
* boolean EXTRA_REQUEST_ASCII_ARMOR (request ascii armor for ouput)
*
* <p/>
* returned extras:
* OpenPgpSignatureResult RESULT_SIGNATURE
*/
@ -102,22 +104,22 @@ public class OpenPgpApi {
/**
* Get key ids based on given user ids (=emails)
*
* <p/>
* required extras:
* String[] EXTRA_USER_IDS
*
* <p/>
* returned extras:
* long[] EXTRA_KEY_IDS
* long[] RESULT_KEY_IDS
*/
public static final String ACTION_GET_KEY_IDS = "org.openintents.openpgp.action.GET_KEY_IDS";
/**
* This action returns RESULT_CODE_SUCCESS if the OpenPGP Provider already has the key
* corresponding to the given key id in its database.
*
* <p/>
* It returns RESULT_CODE_USER_INTERACTION_REQUIRED if the Provider does not have the key.
* The PendingIntent from RESULT_INTENT can be used to retrieve those from a keyserver.
*
* <p/>
* required extras:
* long EXTRA_KEY_ID
*/
@ -141,6 +143,7 @@ public class OpenPgpApi {
// GET_KEY
public static final String EXTRA_KEY_ID = "key_id";
public static final String RESULT_KEY_IDS = "key_ids";
/* Service Intent returns */
public static final String RESULT_CODE = "result_code";
@ -212,44 +215,50 @@ public class OpenPgpApi {
try {
data.putExtra(EXTRA_API_VERSION, OpenPgpApi.API_VERSION);
Intent result = null;
Intent result;
if (ACTION_GET_KEY_IDS.equals(data.getAction())) {
result = mService.execute(data, null, null);
return result;
} else {
// pipe the input and output
ParcelFileDescriptor input = ParcelFileDescriptorUtil.pipeFrom(is,
// pipe the input and output
ParcelFileDescriptor input = null;
if (is != null) {
input = ParcelFileDescriptorUtil.pipeFrom(is,
new ParcelFileDescriptorUtil.IThreadListener() {
@Override
public void onThreadFinished(Thread thread) {
//Log.d(OpenPgpApi.TAG, "Copy to service finished");
}
});
ParcelFileDescriptor output = ParcelFileDescriptorUtil.pipeTo(os,
}
);
}
ParcelFileDescriptor output = null;
if (os != null) {
output = ParcelFileDescriptorUtil.pipeTo(os,
new ParcelFileDescriptorUtil.IThreadListener() {
@Override
public void onThreadFinished(Thread thread) {
//Log.d(OpenPgpApi.TAG, "Service finished writing!");
}
});
// blocks until result is ready
result = mService.execute(data, input, output);
// close() is required to halt the TransferThread
output.close();
// set class loader to current context to allow unparcelling
// of OpenPgpError and OpenPgpSignatureResult
// http://stackoverflow.com/a/3806769
result.setExtrasClassLoader(mContext.getClassLoader());
return result;
}
);
}
// blocks until result is ready
result = mService.execute(data, input, output);
// close() is required to halt the TransferThread
if (output != null) {
output.close();
}
// TODO: close input?
// set class loader to current context to allow unparcelling
// of OpenPgpError and OpenPgpSignatureResult
// http://stackoverflow.com/a/3806769
result.setExtrasClassLoader(mContext.getClassLoader());
return result;
} catch (Exception e) {
Log.e(OpenPgpApi.TAG, "Exception", e);
Log.e(OpenPgpApi.TAG, "Exception in executeApi call", e);
Intent result = new Intent();
result.putExtra(RESULT_CODE, RESULT_CODE_ERROR);
result.putExtra(RESULT_ERROR,

View file

@ -17,6 +17,7 @@
package org.openintents.openpgp.util;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@ -61,4 +62,15 @@ public class OpenPgpUtils {
}
}
public static String convertKeyIdToHex(long keyId) {
return "0x" + convertKeyIdToHex32bit(keyId >> 32) + convertKeyIdToHex32bit(keyId);
}
private static String convertKeyIdToHex32bit(long keyId) {
String hexString = Long.toHexString(keyId & 0xffffffffL).toLowerCase(Locale.US);
while (hexString.length() < 8) {
hexString = "0" + hexString;
}
return hexString;
}
}

View file

@ -691,12 +691,6 @@ public class PgpDecryptVerify {
if (signature != null) {
updateProgress(R.string.progress_verifying_signature, 90, 100);
JcaPGPContentVerifierBuilderProvider contentVerifierBuilderProvider =
new JcaPGPContentVerifierBuilderProvider()
.setProvider(Constants.BOUNCY_CASTLE_PROVIDER_NAME);
signature.init(contentVerifierBuilderProvider, signatureKey);
InputStream sigIn = new BufferedInputStream(new ByteArrayInputStream(clearText));
lookAhead = readInputLine(lineOut, sigIn);

View file

@ -117,7 +117,7 @@ public class OpenPgpService extends RemoteService {
}
Intent result = new Intent();
result.putExtra(OpenPgpApi.EXTRA_KEY_IDS, keyIdsArray);
result.putExtra(OpenPgpApi.RESULT_KEY_IDS, keyIdsArray);
result.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_SUCCESS);
return result;
}
@ -223,7 +223,7 @@ public class OpenPgpService extends RemoteService {
Intent result = getKeyIdsFromEmails(data, userIds);
if (result.getIntExtra(OpenPgpApi.RESULT_CODE, 0) == OpenPgpApi.RESULT_CODE_SUCCESS) {
keyIds = result.getLongArrayExtra(OpenPgpApi.EXTRA_KEY_IDS);
keyIds = result.getLongArrayExtra(OpenPgpApi.RESULT_KEY_IDS);
} else {
// if not success -> result contains a PendingIntent for user interaction
return result;
@ -232,7 +232,8 @@ public class OpenPgpService extends RemoteService {
Intent result = new Intent();
result.putExtra(OpenPgpApi.RESULT_ERROR,
new OpenPgpError(OpenPgpError.GENERIC_ERROR,
"Missing parameter user_ids or key_ids!"));
"Missing parameter user_ids or key_ids!")
);
result.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_ERROR);
return result;
}
@ -334,7 +335,8 @@ public class OpenPgpService extends RemoteService {
OpenPgpService.this, masterKeyId);
}
},
inputData, os);
inputData, os
);
builder.allowSymmetricDecryption(false) // no support for symmetric encryption
.allowedKeyIds(allowedKeyIds) // allow only private keys associated with
// accounts of this app
@ -408,7 +410,7 @@ public class OpenPgpService extends RemoteService {
try {
long keyId = data.getLongExtra(OpenPgpApi.EXTRA_KEY_ID, 0);
if (mProviderHelper.getPGPPublicKeyRing(keyId) == null) {
if (mProviderHelper.getPGPPublicKeyRingWithKeyId(keyId) == null) {
Intent result = new Intent();
// If keys are not in db we return an additional PendingIntent
@ -443,10 +445,22 @@ public class OpenPgpService extends RemoteService {
}
private Intent getKeyIdsImpl(Intent data) {
// get key ids based on given user ids
String[] userIds = data.getStringArrayExtra(OpenPgpApi.EXTRA_USER_IDS);
Intent result = getKeyIdsFromEmails(data, userIds);
return result;
// if data already contains key ids extra GET_KEY_IDS has been executed again
// after user interaction. Then, we just need to return the array again!
if (data.hasExtra(OpenPgpApi.EXTRA_KEY_IDS)) {
long[] keyIdsArray = data.getLongArrayExtra(OpenPgpApi.EXTRA_KEY_IDS);
Intent result = new Intent();
result.putExtra(OpenPgpApi.RESULT_KEY_IDS, keyIdsArray);
result.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_SUCCESS);
return result;
} else {
// get key ids based on given user ids
String[] userIds = data.getStringArrayExtra(OpenPgpApi.EXTRA_USER_IDS);
Intent result = getKeyIdsFromEmails(data, userIds);
return result;
}
}
/**

View file

@ -125,7 +125,7 @@ public class ViewKeyMainFragment extends Fragment implements
return;
}
getActivity().setProgressBarIndeterminateVisibility(Boolean.TRUE);
getActivity().setProgressBarIndeterminateVisibility(true);
mContainer.setVisibility(View.GONE);
mDataUri = dataUri;
@ -314,7 +314,7 @@ public class ViewKeyMainFragment extends Fragment implements
mKeysAdapter.swapCursor(data);
break;
}
getActivity().setProgressBarIndeterminateVisibility(Boolean.FALSE);
getActivity().setProgressBarIndeterminateVisibility(false);
mContainer.setVisibility(View.VISIBLE);
}