conversion of other methods

This commit is contained in:
Dominik Schürmann 2014-02-14 17:01:17 +01:00
parent acad2ba957
commit d695374581
25 changed files with 504 additions and 1248 deletions

View File

@ -25,11 +25,11 @@ import android.content.IntentSender;
import android.content.pm.ResolveInfo;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.TaskStackBuilder;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.TextView;
@ -54,13 +54,17 @@ public class OpenPgpProviderActivity extends Activity {
EditText mMessage;
EditText mCiphertext;
EditText mEncryptUserIds;
Button mSign;
Button mEncrypt;
Button mSignAndEncrypt;
Button mDecryptAndVerify;
private OpenPgpServiceConnection mCryptoServiceConnection;
public static final int REQUEST_CODE_SIGN = 9910;
public static final int REQUEST_CODE_ENCRYPT = 9911;
public static final int REQUEST_CODE_SIGN_AND_ENC = 9912;
public static final int REQUEST_CODE_DECRYPT = 9913;
public static final int REQUEST_CODE_SIGN_AND_ENCRYPT = 9912;
public static final int REQUEST_CODE_DECRYPT_AND_VERIFY = 9913;
@Override
public void onCreate(Bundle icicle) {
@ -73,127 +77,38 @@ public class OpenPgpProviderActivity extends Activity {
mCiphertext = (EditText) findViewById(R.id.crypto_provider_demo_ciphertext);
mEncryptUserIds = (EditText) findViewById(R.id.crypto_provider_demo_encrypt_user_id);
mSign = (Button) findViewById(R.id.crypto_provider_demo_sign);
mEncrypt = (Button) findViewById(R.id.crypto_provider_demo_encrypt);
mSignAndEncrypt = (Button) findViewById(R.id.crypto_provider_demo_sign_and_encrypt);
mDecryptAndVerify = (Button) findViewById(R.id.crypto_provider_demo_decrypt_and_verify);
mSign.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sign(new Bundle());
}
});
mEncrypt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
encrypt(new Bundle());
}
});
mSignAndEncrypt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
signAndEncrypt(new Bundle());
}
});
mDecryptAndVerify.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
decryptAndVerify(new Bundle());
}
});
selectCryptoProvider();
}
// /**
// * Callback from remote openpgp service
// */
// final IOpenPgpKeyIdsCallback.Stub getKeysEncryptCallback = new IOpenPgpKeyIdsCallback.Stub() {
//
// @Override
// public void onSuccess(final long[] keyIds) throws RemoteException {
// Log.d(Constants.TAG, "getKeysEncryptCallback keyId " + keyIds[0]);
// mActivity.runOnUiThread(new Runnable() {
//
// @Override
// public void run() {
// // encrypt after getting key ids
// String inputStr = mMessage.getText().toString();
// OpenPgpData input = new OpenPgpData(inputStr);
//
// Log.d(Constants.TAG, "getKeysEncryptCallback inputStr " + inputStr);
//
// try {
// mCryptoServiceConnection.getService().encrypt(input,
// new OpenPgpData(OpenPgpData.TYPE_STRING), keyIds, encryptCallback);
// } catch (RemoteException e) {
// Log.e(Constants.TAG, "CryptoProviderDemo", e);
// }
// }
// });
// }
//
// @Override
// public void onError(OpenPgpError error) throws RemoteException {
// handleError(error);
// }
//
// };
//
// final IOpenPgpKeyIdsCallback.Stub getKeysSignAndEncryptCallback = new IOpenPgpKeyIdsCallback.Stub() {
//
// @Override
// public void onSuccess(final long[] keyIds) throws RemoteException {
// Log.d(Constants.TAG, "getKeysSignAndEncryptCallback keyId " + keyIds[0]);
//
// mActivity.runOnUiThread(new Runnable() {
//
// @Override
// public void run() {
// // encrypt after getting key ids
// String inputStr = mMessage.getText().toString();
// OpenPgpData input = new OpenPgpData(inputStr);
//
// try {
// mCryptoServiceConnection.getService().signAndEncrypt(input,
// new OpenPgpData(OpenPgpData.TYPE_STRING), keyIds, encryptCallback);
// } catch (RemoteException e) {
// Log.e(Constants.TAG, "CryptoProviderDemo", e);
// }
// }
// });
// }
//
// @Override
// public void onError(OpenPgpError error) throws RemoteException {
// handleError(error);
// }
//
// };
//
// final IOpenPgpCallback.Stub encryptCallback = new IOpenPgpCallback.Stub() {
//
// @Override
// public void onSuccess(final OpenPgpData output, OpenPgpSignatureResult signatureResult)
// throws RemoteException {
// Log.d(Constants.TAG, "encryptCallback");
//
// runOnUiThread(new Runnable() {
//
// @Override
// public void run() {
// mCiphertext.setText(output.getString());
// }
// });
// }
//
// @Override
// public void onError(OpenPgpError error) throws RemoteException {
// handleError(error);
// }
//
// };
//
// final IOpenPgpCallback.Stub decryptAndVerifyCallback = new IOpenPgpCallback.Stub() {
//
// @Override
// public void onSuccess(final OpenPgpData output, final OpenPgpSignatureResult signatureResult)
// throws RemoteException {
// Log.d(Constants.TAG, "decryptAndVerifyCallback");
//
// runOnUiThread(new Runnable() {
//
// @Override
// public void run() {
// mMessage.setText(output.getString());
// if (signatureResult != null) {
// Toast.makeText(OpenPgpProviderActivity.this,
// "signature result:\n" + signatureResult.toString(),
// Toast.LENGTH_LONG).show();
// }
// }
// });
//
// }
//
// @Override
// public void onError(OpenPgpError error) throws RemoteException {
// handleError(error);
// }
//
// };
private void handleError(final OpenPgpError error) {
mActivity.runOnUiThread(new Runnable() {
@ -208,28 +123,30 @@ public class OpenPgpProviderActivity extends Activity {
});
}
public void encryptOnClick(View view) {
// try {
// mCryptoServiceConnection.getService().getKeyIds(
// mEncryptUserIds.getText().toString().split(","), true, getKeysEncryptCallback);
// } catch (RemoteException e) {
// Log.e(Constants.TAG, "CryptoProviderDemo", e);
// }
}
public void signOnClick(View view) {
private InputStream getInputstream(boolean ciphertext) {
InputStream is = null;
try {
String inputStr = mMessage.getText().toString();
String inputStr = null;
if (ciphertext) {
inputStr = mCiphertext.getText().toString();
} else {
inputStr = mMessage.getText().toString();
}
is = new ByteArrayInputStream(inputStr.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return is;
}
public void sign(Bundle params) {
InputStream is = getInputstream(false);
final ByteArrayOutputStream os = new ByteArrayOutputStream();
OpenPgpApi api = new OpenPgpApi(mCryptoServiceConnection.getService());
api.sign(new Bundle(), is, os, new OpenPgpApi.IOpenPgpCallback() {
api.sign(params, is, os, new OpenPgpApi.IOpenPgpCallback() {
@Override
public void onReturn(Bundle result) {
switch (result.getInt(OpenPgpConstants.RESULT_CODE)) {
@ -248,52 +165,128 @@ public class OpenPgpProviderActivity extends Activity {
PendingIntent pi = result.getParcelable(OpenPgpConstants.RESULT_INTENT);
try {
OpenPgpProviderActivity.this.startIntentSenderForResult(pi.getIntentSender(),
REQUEST_CODE_SIGN, null, // or new Intent() (in billing)
REQUEST_CODE_SIGN, null,
0, 0, 0);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
// try {
// pi.send(OpenPgpProviderActivity.this, 42, null, new PendingIntent.OnFinished() {
//
// @Override
// public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode, String resultData, Bundle resultExtras) {
// Log.d(Constants.TAG, "onSendFinished");
// Log.d(Constants.TAG, "resultCode: " + resultCode);
//
// }
// }, null);
// } catch (PendingIntent.CanceledException e) {
// e.printStackTrace();
// }
break;
}
}
}
});
}
public void signAndEncryptOnClick(View view) {
// try {
// mCryptoServiceConnection.getService().getKeyIds(
// mEncryptUserIds.getText().toString().split(","), true,
// getKeysSignAndEncryptCallback);
// } catch (RemoteException e) {
// Log.e(Constants.TAG, "CryptoProviderDemo", e);
// }
public void encrypt(Bundle params) {
params.putStringArray(OpenPgpConstants.PARAMS_USER_IDS, mEncryptUserIds.getText().toString().split(","));
InputStream is = getInputstream(false);
final ByteArrayOutputStream os = new ByteArrayOutputStream();
OpenPgpApi api = new OpenPgpApi(mCryptoServiceConnection.getService());
api.encrypt(params, is, os, new OpenPgpApi.IOpenPgpCallback() {
@Override
public void onReturn(Bundle result) {
switch (result.getInt(OpenPgpConstants.RESULT_CODE)) {
case OpenPgpConstants.RESULT_CODE_SUCCESS: {
try {
Log.d(OpenPgpConstants.TAG, "result: " + os.toByteArray().length
+ " str=" + os.toString("UTF-8"));
mCiphertext.setText(os.toString("UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
break;
}
case OpenPgpConstants.RESULT_CODE_USER_INTERACTION_REQUIRED: {
PendingIntent pi = result.getParcelable(OpenPgpConstants.RESULT_INTENT);
try {
OpenPgpProviderActivity.this.startIntentSenderForResult(pi.getIntentSender(),
REQUEST_CODE_ENCRYPT, null,
0, 0, 0);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
break;
}
}
}
});
}
public void decryptAndVerifyOnClick(View view) {
// String inputStr = mCiphertext.getText().toString();
// OpenPgpData input = new OpenPgpData(inputStr);
//
// try {
// mCryptoServiceConnection.getService().decryptAndVerify(input,
// new OpenPgpData(OpenPgpData.TYPE_STRING), decryptAndVerifyCallback);
// } catch (RemoteException e) {
// Log.e(Constants.TAG, "CryptoProviderDemo", e);
// }
public void signAndEncrypt(Bundle params) {
params.putStringArray(OpenPgpConstants.PARAMS_USER_IDS, mEncryptUserIds.getText().toString().split(","));
InputStream is = getInputstream(false);
final ByteArrayOutputStream os = new ByteArrayOutputStream();
OpenPgpApi api = new OpenPgpApi(mCryptoServiceConnection.getService());
api.signAndEncrypt(params, is, os, new OpenPgpApi.IOpenPgpCallback() {
@Override
public void onReturn(Bundle result) {
switch (result.getInt(OpenPgpConstants.RESULT_CODE)) {
case OpenPgpConstants.RESULT_CODE_SUCCESS: {
try {
Log.d(OpenPgpConstants.TAG, "result: " + os.toByteArray().length
+ " str=" + os.toString("UTF-8"));
mCiphertext.setText(os.toString("UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
break;
}
case OpenPgpConstants.RESULT_CODE_USER_INTERACTION_REQUIRED: {
PendingIntent pi = result.getParcelable(OpenPgpConstants.RESULT_INTENT);
try {
OpenPgpProviderActivity.this.startIntentSenderForResult(pi.getIntentSender(),
REQUEST_CODE_SIGN_AND_ENCRYPT, null,
0, 0, 0);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
break;
}
}
}
});
}
public void decryptAndVerify(Bundle params) {
InputStream is = getInputstream(true);
final ByteArrayOutputStream os = new ByteArrayOutputStream();
OpenPgpApi api = new OpenPgpApi(mCryptoServiceConnection.getService());
api.decryptAndVerify(params, is, os, new OpenPgpApi.IOpenPgpCallback() {
@Override
public void onReturn(Bundle result) {
switch (result.getInt(OpenPgpConstants.RESULT_CODE)) {
case OpenPgpConstants.RESULT_CODE_SUCCESS: {
try {
Log.d(OpenPgpConstants.TAG, "result: " + os.toByteArray().length
+ " str=" + os.toString("UTF-8"));
mCiphertext.setText(os.toString("UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
break;
}
case OpenPgpConstants.RESULT_CODE_USER_INTERACTION_REQUIRED: {
PendingIntent pi = result.getParcelable(OpenPgpConstants.RESULT_INTENT);
try {
OpenPgpProviderActivity.this.startIntentSenderForResult(pi.getIntentSender(),
REQUEST_CODE_DECRYPT_AND_VERIFY, null,
0, 0, 0);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
break;
}
}
}
});
}
@Override
@ -304,8 +297,34 @@ public class OpenPgpProviderActivity extends Activity {
case REQUEST_CODE_SIGN: {
Log.d(Constants.TAG, "resultCode: " + resultCode);
// try to sign again after password caching
if (resultCode == RESULT_OK) {
signOnClick(null);
sign(new Bundle());
}
}
case REQUEST_CODE_ENCRYPT: {
Log.d(Constants.TAG, "resultCode: " + resultCode);
// try to sign again after password caching
if (resultCode == RESULT_OK) {
// use data extras now as params for call (they now include key ids!
encrypt(data.getExtras());
}
}
case REQUEST_CODE_SIGN_AND_ENCRYPT: {
Log.d(Constants.TAG, "resultCode: " + resultCode);
// try to sign again after password caching
if (resultCode == RESULT_OK) {
signAndEncrypt(data.getExtras());
}
}
case REQUEST_CODE_DECRYPT_AND_VERIFY: {
Log.d(Constants.TAG, "resultCode: " + resultCode);
// try to sign again after password caching
if (resultCode == RESULT_OK) {
decryptAndVerify(new Bundle());
}
}
}

View File

@ -54,7 +54,6 @@
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="encryptOnClick"
android:text="Encrypt" />
<Button
@ -62,14 +61,12 @@
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="signOnClick"
android:text="Sign" />
<Button
android:id="@+id/crypto_provider_demo_encrypt_and_sign"
android:id="@+id/crypto_provider_demo_sign_and_encrypt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="signAndEncryptOnClick"
android:text="Sign and Encrypt" />
</LinearLayout>
@ -77,7 +74,6 @@
android:id="@+id/crypto_provider_demo_decrypt_and_verify"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="decryptAndVerifyOnClick"
android:text="Decrypt and Verify" />
</LinearLayout>

View File

@ -12,7 +12,7 @@
android:id="@+id/Button02"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="encryptOnClick"
android:onClick="encrypt"
android:text="Encrypt" />
<Button
@ -54,7 +54,7 @@
android:id="@+id/intent_demo_encrypt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="encryptOnClick"
android:onClick="encrypt"
android:text="Encrypt" />
<Button

View File

@ -1,45 +0,0 @@
/*
* Copyright (C) 2013 Dominik Schürmann <dominik@dominikschuermann.de>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openintents.openpgp;
import org.openintents.openpgp.OpenPgpData;
import org.openintents.openpgp.OpenPgpSignatureResult;
import org.openintents.openpgp.OpenPgpError;
interface IOpenPgpCallback {
/**
* onSuccess returns on successful OpenPGP operations.
*
* @param output
* contains resulting output (decrypted content (when input was encrypted)
* or content without signature (when input was signed-only))
* @param signatureResult
* signatureResult is only non-null if decryptAndVerify() was called and the content
* was encrypted or signed-and-encrypted.
*/
oneway void onSuccess(in OpenPgpData output, in OpenPgpSignatureResult signatureResult);
/**
* onError returns on errors or when allowUserInteraction was set to false, but user interaction
* was required execute an OpenPGP operation.
*
* @param error
* See OpenPgpError class for more information.
*/
oneway void onError(in OpenPgpError error);
}

View File

@ -1,39 +0,0 @@
/*
* Copyright (C) 2014 Dominik Schürmann <dominik@dominikschuermann.de>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openintents.openpgp;
import org.openintents.openpgp.OpenPgpError;
interface IOpenPgpKeyIdsCallback {
/**
* onSuccess returns on successful getKeyIds operations.
*
* @param keyIds
* returned key ids
*/
oneway void onSuccess(in long[] keyIds);
/**
* onError returns on errors or when allowUserInteraction was set to false, but user interaction
* was required execute an OpenPGP operation.
*
* @param error
* See OpenPgpError class for more information.
*/
oneway void onError(in OpenPgpError error);
}

View File

@ -16,10 +16,6 @@
package org.openintents.openpgp;
import org.openintents.openpgp.OpenPgpData;
import org.openintents.openpgp.IOpenPgpCallback;
import org.openintents.openpgp.IOpenPgpKeyIdsCallback;
interface IOpenPgpService {
/**
@ -29,7 +25,7 @@ interface IOpenPgpService {
* params:
* int api_version (current: 1)
* boolean ascii_armor true/false (for output)
*
* String passphrase (for key, optional)
*
* Bundle return:
* int result_code 0,1, or 2 (see OpenPgpConstants)
@ -41,9 +37,6 @@ interface IOpenPgpService {
/**
* sign only
*
* params:
* String passphrase (optional)
*/
Bundle sign(in Bundle params, in ParcelFileDescriptor input, in ParcelFileDescriptor output);

View File

@ -1,20 +0,0 @@
/*
* Copyright (C) 2013 Dominik Schürmann <dominik@dominikschuermann.de>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openintents.openpgp;
// Declare OpenPgpData so AIDL can find it and knows that it implements the parcelable protocol.
parcelable OpenPgpData;

View File

@ -1,127 +0,0 @@
/*
* Copyright (C) 2013 Dominik Schürmann <dominik@dominikschuermann.de>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openintents.openpgp;
import android.net.Uri;
import android.os.Parcel;
import android.os.ParcelFileDescriptor;
import android.os.Parcelable;
public class OpenPgpData implements Parcelable {
public static final int TYPE_STRING = 0;
public static final int TYPE_BYTE_ARRAY = 1;
public static final int TYPE_FILE_DESCRIPTOR = 2;
public static final int TYPE_URI = 3;
int type;
String string;
byte[] bytes = new byte[0];
ParcelFileDescriptor fileDescriptor;
Uri uri;
public int getType() {
return type;
}
public String getString() {
return string;
}
public byte[] getBytes() {
return bytes;
}
public ParcelFileDescriptor getFileDescriptor() {
return fileDescriptor;
}
public Uri getUri() {
return uri;
}
public OpenPgpData() {
}
/**
* Not a real constructor. This can be used to define requested output type.
*
* @param type
*/
public OpenPgpData(int type) {
this.type = type;
}
public OpenPgpData(String string) {
this.string = string;
this.type = TYPE_STRING;
}
public OpenPgpData(byte[] bytes) {
this.bytes = bytes;
this.type = TYPE_BYTE_ARRAY;
}
public OpenPgpData(ParcelFileDescriptor fileDescriptor) {
this.fileDescriptor = fileDescriptor;
this.type = TYPE_FILE_DESCRIPTOR;
}
public OpenPgpData(Uri uri) {
this.uri = uri;
this.type = TYPE_URI;
}
public OpenPgpData(OpenPgpData b) {
this.string = b.string;
this.bytes = b.bytes;
this.fileDescriptor = b.fileDescriptor;
this.uri = b.uri;
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(type);
dest.writeString(string);
dest.writeInt(bytes.length);
dest.writeByteArray(bytes);
dest.writeParcelable(fileDescriptor, 0);
dest.writeParcelable(uri, 0);
}
public static final Creator<OpenPgpData> CREATOR = new Creator<OpenPgpData>() {
public OpenPgpData createFromParcel(final Parcel source) {
OpenPgpData vr = new OpenPgpData();
vr.type = source.readInt();
vr.string = source.readString();
vr.bytes = new byte[source.readInt()];
source.readByteArray(vr.bytes);
vr.fileDescriptor = source.readParcelable(ParcelFileDescriptor.class.getClassLoader());
vr.fileDescriptor = source.readParcelable(Uri.class.getClassLoader());
return vr;
}
public OpenPgpData[] newArray(final int size) {
return new OpenPgpData[size];
}
};
}

View File

@ -22,14 +22,14 @@ import android.os.Parcelable;
public class OpenPgpSignatureResult implements Parcelable {
// generic error on signature verification
public static final int SIGNATURE_ERROR = 0;
// successfully verified signature, with trusted public key
public static final int SIGNATURE_SUCCESS_TRUSTED = 1;
// successfully verified signature, with certified public key
public static final int SIGNATURE_SUCCESS_CERTIFIED = 1;
// no public key was found for this signature verification
// you can retrieve the key with
// getKeys(new String[] {String.valueOf(signatureResult.getKeyId)}, true, callback)
public static final int SIGNATURE_UNKNOWN_PUB_KEY = 2;
// successfully verified signature, but with untrusted public key
public static final int SIGNATURE_SUCCESS_UNTRUSTED = 3;
// successfully verified signature, but with certified public key
public static final int SIGNATURE_SUCCESS_UNCERTIFIED = 3;
int status;
boolean signatureOnly;

View File

@ -30,6 +30,7 @@ public class OpenPgpConstants {
// OpenPGP Radix-64, 33 percent overhead compared to binary, see http://tools.ietf.org/html/rfc4880#page-53)
public static final String PARAMS_REQUEST_ASCII_ARMOR = "ascii_armor";
// (for encrypt method)
public static final String PARAMS_USER_IDS = "user_ids";
public static final String PARAMS_KEY_IDS = "key_ids";
/* Bundle return */

View File

@ -391,19 +391,19 @@
</service>
<!-- Extended Remote API -->
<service
android:name="org.sufficientlysecure.keychain.service.remote.ExtendedApiService"
android:enabled="true"
android:exported="true"
android:process=":remote_api">
<intent-filter>
<action android:name="org.sufficientlysecure.keychain.service.remote.IExtendedApiService" />
</intent-filter>
<!--<service-->
<!--android:name="org.sufficientlysecure.keychain.service.remote.ExtendedApiService"-->
<!--android:enabled="true"-->
<!--android:exported="true"-->
<!--android:process=":remote_api">-->
<!--<intent-filter>-->
<!--<action android:name="org.sufficientlysecure.keychain.service.remote.IExtendedApiService" />-->
<!--</intent-filter>-->
<meta-data
android:name="api_version"
android:value="1" />
</service>
<!--<meta-data-->
<!--android:name="api_version"-->
<!--android:value="1" />-->
<!--</service>-->
<!-- TODO: authority! Make this API with content provider uris -->
<!-- <provider -->

View File

@ -1,10 +0,0 @@
package org.sufficientlysecure.keychain.service.exception;
public class NoUserIdsException extends Exception {
private static final long serialVersionUID = 7009311527126696207L;
public NoUserIdsException(String message) {
super(message);
}
}

View File

@ -1,10 +0,0 @@
package org.sufficientlysecure.keychain.service.exception;
public class UserInteractionRequiredException extends Exception {
private static final long serialVersionUID = -60128148603511936L;
public UserInteractionRequiredException(String message) {
super(message);
}
}

View File

@ -1,10 +0,0 @@
package org.sufficientlysecure.keychain.service.exception;
public class WrongPassphraseException extends Exception {
private static final long serialVersionUID = -5309689232853485740L;
public WrongPassphraseException(String message) {
super(message);
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2013 Dominik Schürmann <dominik@dominikschuermann.de>
* Copyright (C) 2013-2014 Dominik Schürmann <dominik@dominikschuermann.de>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@ -17,106 +17,35 @@
package org.sufficientlysecure.keychain.service.remote;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.regex.Matcher;
import android.app.PendingIntent;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.os.ParcelFileDescriptor;
import org.openintents.openpgp.IOpenPgpCallback;
import org.openintents.openpgp.IOpenPgpKeyIdsCallback;
import org.openintents.openpgp.IOpenPgpService;
import org.openintents.openpgp.OpenPgpData;
import org.openintents.openpgp.OpenPgpError;
import org.openintents.openpgp.OpenPgpSignatureResult;
import org.openintents.openpgp.util.OpenPgpConstants;
import org.spongycastle.util.Arrays;
import org.sufficientlysecure.keychain.Constants;
import org.sufficientlysecure.keychain.Id;
import org.sufficientlysecure.keychain.R;
import org.sufficientlysecure.keychain.helper.Preferences;
import org.sufficientlysecure.keychain.pgp.PgpHelper;
import org.sufficientlysecure.keychain.pgp.PgpOperation;
import org.sufficientlysecure.keychain.pgp.exception.NoAsymmetricEncryptionException;
import org.sufficientlysecure.keychain.pgp.exception.PgpGeneralException;
import org.sufficientlysecure.keychain.provider.KeychainContract;
import org.sufficientlysecure.keychain.service.KeychainIntentService;
import org.sufficientlysecure.keychain.service.PassphraseCacheService;
import org.sufficientlysecure.keychain.service.exception.NoUserIdsException;
import org.sufficientlysecure.keychain.service.exception.UserInteractionRequiredException;
import org.sufficientlysecure.keychain.service.exception.WrongPassphraseException;
import org.sufficientlysecure.keychain.util.InputData;
import org.sufficientlysecure.keychain.util.Log;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Message;
import android.os.ParcelFileDescriptor;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
public class OpenPgpService extends RemoteService {
private String getCachedPassphrase(long keyId, boolean allowUserInteraction)
throws UserInteractionRequiredException {
String passphrase = PassphraseCacheService.getCachedPassphrase(getContext(), keyId);
if (passphrase == null) {
if (!allowUserInteraction) {
throw new UserInteractionRequiredException(
"Passphrase not found in cache, please enter your passphrase!");
}
Log.d(Constants.TAG, "No passphrase! Activity required!");
// start passphrase dialog
PassphraseActivityCallback callback = new PassphraseActivityCallback();
Bundle extras = new Bundle();
extras.putLong(RemoteServiceActivity.EXTRA_SECRET_KEY_ID, keyId);
pauseAndStartUserInteraction(RemoteServiceActivity.ACTION_CACHE_PASSPHRASE, callback,
extras);
if (callback.isSuccess()) {
Log.d(Constants.TAG, "New passphrase entered!");
// get again after it was entered
passphrase = PassphraseCacheService.getCachedPassphrase(getContext(), keyId);
} else {
Log.d(Constants.TAG, "Passphrase dialog canceled!");
return null;
}
}
return passphrase;
}
public class PassphraseActivityCallback extends UserInputCallback {
private boolean success = false;
public boolean isSuccess() {
return success;
}
@Override
public void handleUserInput(Message msg) {
if (msg.arg1 == OKAY) {
success = true;
} else {
success = false;
}
}
}
;
/**
* Search database for key ids based on emails.
@ -124,8 +53,7 @@ public class OpenPgpService extends RemoteService {
* @param encryptionUserIds
* @return
*/
private long[] getKeyIdsFromEmails(String[] encryptionUserIds, boolean allowUserInteraction)
throws UserInteractionRequiredException {
private Bundle getKeyIdsFromEmails(String[] encryptionUserIds) {
// find key ids to given emails in database
ArrayList<Long> keyIds = new ArrayList<Long>();
@ -159,98 +87,70 @@ public class OpenPgpService extends RemoteService {
}
// allow the user to verify pub key selection
if (allowUserInteraction && (missingUserIdsCheck || dublicateUserIdsCheck)) {
SelectPubKeysActivityCallback callback = new SelectPubKeysActivityCallback();
if (missingUserIdsCheck || dublicateUserIdsCheck) {
// build PendingIntent for passphrase input
Intent intent = new Intent(getBaseContext(), RemoteServiceActivity.class);
intent.setAction(RemoteServiceActivity.ACTION_SELECT_PUB_KEYS);
intent.putExtra(RemoteServiceActivity.EXTRA_SELECTED_MASTER_KEY_IDS, keyIdsArray);
intent.putExtra(RemoteServiceActivity.EXTRA_MISSING_USER_IDS, missingUserIds);
intent.putExtra(RemoteServiceActivity.EXTRA_DUBLICATE_USER_IDS, dublicateUserIds);
Bundle extras = new Bundle();
extras.putLongArray(RemoteServiceActivity.EXTRA_SELECTED_MASTER_KEY_IDS, keyIdsArray);
extras.putStringArrayList(RemoteServiceActivity.EXTRA_MISSING_USER_IDS, missingUserIds);
extras.putStringArrayList(RemoteServiceActivity.EXTRA_DUBLICATE_USER_IDS,
dublicateUserIds);
PendingIntent pi = PendingIntent.getActivity(getBaseContext(), 42, intent, 0);
pauseAndStartUserInteraction(RemoteServiceActivity.ACTION_SELECT_PUB_KEYS, callback,
extras);
// return PendingIntent to be executed by client
Bundle result = new Bundle();
result.putInt(OpenPgpConstants.RESULT_CODE, OpenPgpConstants.RESULT_CODE_USER_INTERACTION_REQUIRED);
result.putParcelable(OpenPgpConstants.RESULT_INTENT, pi);
if (callback.isSuccess()) {
Log.d(Constants.TAG, "New selection of pub keys!");
keyIdsArray = callback.getPubKeyIds();
} else {
Log.d(Constants.TAG, "Pub key selection canceled!");
return null;
}
}
// if no user interaction is allow throw exceptions on duplicate or missing pub keys
if (!allowUserInteraction) {
if (missingUserIdsCheck)
throw new UserInteractionRequiredException(
"Pub keys for these user ids are missing:" + missingUserIds.toString());
if (dublicateUserIdsCheck)
throw new UserInteractionRequiredException(
"More than one pub key with these user ids exist:"
+ dublicateUserIds.toString());
return result;
}
if (keyIdsArray.length == 0) {
return null;
}
return keyIdsArray;
Bundle result = new Bundle();
result.putInt(OpenPgpConstants.RESULT_CODE, OpenPgpConstants.RESULT_CODE_SUCCESS);
result.putLongArray(OpenPgpConstants.PARAMS_KEY_IDS, keyIdsArray);
return result;
}
public class SelectPubKeysActivityCallback extends UserInputCallback {
public static final String PUB_KEY_IDS = "pub_key_ids";
private Bundle getPassphraseBundleIntent(long keyId) {
// build PendingIntent for passphrase input
Intent intent = new Intent(getBaseContext(), RemoteServiceActivity.class);
intent.setAction(RemoteServiceActivity.ACTION_CACHE_PASSPHRASE);
intent.putExtra(RemoteServiceActivity.EXTRA_SECRET_KEY_ID, keyId);
PendingIntent pi = PendingIntent.getActivity(getBaseContext(), 42, intent, 0);
private boolean success = false;
private long[] pubKeyIds;
// return PendingIntent to be executed by client
Bundle result = new Bundle();
result.putInt(OpenPgpConstants.RESULT_CODE, OpenPgpConstants.RESULT_CODE_USER_INTERACTION_REQUIRED);
result.putParcelable(OpenPgpConstants.RESULT_INTENT, pi);
public boolean isSuccess() {
return success;
}
return result;
}
public long[] getPubKeyIds() {
return pubKeyIds;
}
private Bundle encryptAndSignImpl(Bundle params, ParcelFileDescriptor input,
ParcelFileDescriptor output, AppSettings appSettings,
boolean sign) {
try {
boolean asciiArmor = params.getBoolean(OpenPgpConstants.PARAMS_REQUEST_ASCII_ARMOR, false);
@Override
public void handleUserInput(Message msg) {
if (msg.arg1 == OKAY) {
success = true;
pubKeyIds = msg.getData().getLongArray(PUB_KEY_IDS);
long[] keyIds;
if (params.containsKey(OpenPgpConstants.PARAMS_KEY_IDS)) {
keyIds = params.getLongArray(OpenPgpConstants.PARAMS_KEY_IDS);
} else {
success = false;
}
}
}
// get key ids based on given user ids
String[] userIds = params.getStringArray(OpenPgpConstants.PARAMS_USER_IDS);
Bundle result = getKeyIdsFromEmails(userIds);
result.putInt(OpenPgpConstants.RESULT_CODE, OpenPgpConstants.RESULT_CODE_USER_INTERACTION_REQUIRED);
;
private synchronized void getKeyIdsSafe(String[] userIds, boolean allowUserInteraction,
IOpenPgpKeyIdsCallback callback, AppSettings appSettings) {
try {
long[] keyIds = getKeyIdsFromEmails(userIds, allowUserInteraction);
if (keyIds == null) {
throw new NoUserIdsException("No user ids!");
}
callback.onSuccess(keyIds);
} catch (UserInteractionRequiredException e) {
// callbackOpenPgpError(callback, OpenPgpError.USER_INTERACTION_REQUIRED, e.getMessage());
} catch (NoUserIdsException e) {
callbackOpenPgpError(callback, OpenPgpError.NO_USER_IDS, e.getMessage());
} catch (Exception e) {
callbackOpenPgpError(callback, OpenPgpError.GENERIC_ERROR, e.getMessage());
}
}
private synchronized void encryptAndSignSafe(OpenPgpData inputData,
final OpenPgpData outputData, long[] keyIds, boolean allowUserInteraction,
IOpenPgpCallback callback, AppSettings appSettings, boolean sign) {
try {
// TODO: other options of OpenPgpData!
byte[] inputBytes = getInput(inputData);
boolean asciiArmor = false;
if (outputData.getType() == OpenPgpData.TYPE_STRING) {
asciiArmor = true;
if (result.getInt(OpenPgpConstants.RESULT_CODE, 0) == OpenPgpConstants.RESULT_CODE_SUCCESS) {
keyIds = result.getLongArray(OpenPgpConstants.PARAMS_KEY_IDS);
} else {
// non-unique result, we need user interaction!
return result;
}
}
// add own key for encryption
@ -258,103 +158,32 @@ public class OpenPgpService extends RemoteService {
keyIds[keyIds.length - 1] = appSettings.getKeyId();
// build InputData and write into OutputStream
InputStream inputStream = new ByteArrayInputStream(inputBytes);
long inputLength = inputBytes.length;
InputData inputDt = new InputData(inputStream, inputLength);
OutputStream outputStream = new ByteArrayOutputStream();
PgpOperation operation = new PgpOperation(getContext(), null, inputDt, outputStream);
if (sign) {
String passphrase = getCachedPassphrase(appSettings.getKeyId(),
allowUserInteraction);
if (passphrase == null) {
throw new WrongPassphraseException("No or wrong passphrase!");
}
operation.signAndEncrypt(asciiArmor, appSettings.getCompression(), keyIds, null,
appSettings.getEncryptionAlgorithm(), appSettings.getKeyId(),
appSettings.getHashAlgorithm(), true, passphrase);
} else {
operation.signAndEncrypt(asciiArmor, appSettings.getCompression(), keyIds, null,
appSettings.getEncryptionAlgorithm(), Id.key.none,
appSettings.getHashAlgorithm(), true, null);
}
outputStream.close();
byte[] outputBytes = ((ByteArrayOutputStream) outputStream).toByteArray();
OpenPgpData output = null;
if (asciiArmor) {
output = new OpenPgpData(new String(outputBytes));
} else {
output = new OpenPgpData(outputBytes);
}
// return over handler on client side
callback.onSuccess(output, null);
} catch (UserInteractionRequiredException e) {
// callbackOpenPgpError(callback, OpenPgpError.USER_INTERACTION_REQUIRED, e.getMessage());
} catch (WrongPassphraseException e) {
callbackOpenPgpError(callback, OpenPgpError.NO_OR_WRONG_PASSPHRASE, e.getMessage());
} catch (Exception e) {
callbackOpenPgpError(callback, OpenPgpError.GENERIC_ERROR, e.getMessage());
}
}
// TODO: asciiArmor?!
private Bundle signImpl(ParcelFileDescriptor input, ParcelFileDescriptor output, AppSettings appSettings) {
try {
// get passphrase from cache, if key has "no" passphrase, this returns an empty String
String passphrase = PassphraseCacheService.getCachedPassphrase(getContext(), appSettings.getKeyId());
if (passphrase == null) {
// TODO: we need to abort and return a passphrase Intent!
Intent intent = new Intent(getBaseContext(), RemoteServiceActivity.class);
// TODO: setComponent really needed for security?
// intent.setComponent(new ComponentName(Constants.PACKAGE_NAME,
// "org.sufficientlysecure.keychain.service.remote.RemoteServiceActivity"));
// intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(RemoteServiceActivity.ACTION_CACHE_PASSPHRASE);
intent.putExtra(RemoteServiceActivity.EXTRA_SECRET_KEY_ID, appSettings.getKeyId());
PendingIntent pi = PendingIntent.getActivity(getBaseContext(), 42, intent, 0);
Bundle result = new Bundle();
result.putInt(OpenPgpConstants.RESULT_CODE, OpenPgpConstants.RESULT_CODE_USER_INTERACTION_REQUIRED);
result.putParcelable(OpenPgpConstants.RESULT_INTENT, pi);
return result;
}
// INPUT
// Get Input- and OutputStream from ParcelFileDescriptor
InputStream is = new ParcelFileDescriptor.AutoCloseInputStream(input);
// OUTPUT
OutputStream os = new ParcelFileDescriptor.AutoCloseOutputStream(output);
try {
long inputLength = is.available();
InputData inputData = new InputData(is, inputLength);
PgpOperation operation = new PgpOperation(getContext(), null, inputData, os);
operation.signText(appSettings.getKeyId(), passphrase, appSettings.getHashAlgorithm(),
Preferences.getPreferences(this).getForceV3Signatures());
if (sign) {
String passphrase = PassphraseCacheService.getCachedPassphrase(getContext(),
appSettings.getKeyId());
if (passphrase == null) {
return getPassphraseBundleIntent(appSettings.getKeyId());
}
operation.signAndEncrypt(asciiArmor, appSettings.getCompression(), keyIds, null,
appSettings.getEncryptionAlgorithm(), appSettings.getKeyId(),
appSettings.getHashAlgorithm(), true, passphrase);
} else {
operation.signAndEncrypt(asciiArmor, appSettings.getCompression(), keyIds, null,
appSettings.getEncryptionAlgorithm(), Id.key.none,
appSettings.getHashAlgorithm(), true, null);
}
} finally {
is.close();
os.close();
// } catch (IOException e) {
// Log.e(Constants.TAG, "Fail", e);
} finally {
// try {
is.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
// try {
os.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
}
Bundle result = new Bundle();
@ -369,164 +198,195 @@ public class OpenPgpService extends RemoteService {
}
}
private synchronized void decryptAndVerifySafe(byte[] inputBytes, boolean allowUserInteraction,
IOpenPgpCallback callback, AppSettings appSettings) {
// TODO: asciiArmor?!
private Bundle signImpl(ParcelFileDescriptor input, ParcelFileDescriptor output, AppSettings appSettings) {
try {
// TODO: this is not really needed
// checked if it is text with BEGIN and END tags
String message = new String(inputBytes);
Log.d(Constants.TAG, "in: " + message);
boolean signedOnly = false;
Matcher matcher = PgpHelper.PGP_MESSAGE.matcher(message);
if (matcher.matches()) {
Log.d(Constants.TAG, "PGP_MESSAGE matched");
message = matcher.group(1);
// replace non breakable spaces
message = message.replaceAll("\\xa0", " ");
// overwrite inputBytes
inputBytes = message.getBytes();
} else {
matcher = PgpHelper.PGP_SIGNED_MESSAGE.matcher(message);
if (matcher.matches()) {
signedOnly = true;
Log.d(Constants.TAG, "PGP_SIGNED_MESSAGE matched");
message = matcher.group(1);
// replace non breakable spaces
message = message.replaceAll("\\xa0", " ");
// overwrite inputBytes
inputBytes = message.getBytes();
} else {
Log.d(Constants.TAG, "Nothing matched! Binary?");
}
}
// END TODO
Log.d(Constants.TAG, "in: " + new String(inputBytes));
// TODO: This allows to decrypt messages with ALL secret keys, not only the one for the
// app, Fix this?
String passphrase = null;
if (!signedOnly) {
// BEGIN Get key
// TODO: this input stream is consumed after PgpMain.getDecryptionKeyId()... do it
// better!
InputStream inputStream2 = new ByteArrayInputStream(inputBytes);
// TODO: duplicates functions from DecryptActivity!
long secretKeyId;
try {
if (inputStream2.markSupported()) {
// should probably set this to the max size of two
// pgpF objects, if it even needs to be anything other
// than 0.
inputStream2.mark(200);
}
secretKeyId = PgpHelper.getDecryptionKeyId(this, inputStream2);
if (secretKeyId == Id.key.none) {
throw new PgpGeneralException(getString(R.string.error_no_secret_key_found));
}
} catch (NoAsymmetricEncryptionException e) {
if (inputStream2.markSupported()) {
inputStream2.reset();
}
secretKeyId = Id.key.symmetric;
if (!PgpOperation.hasSymmetricEncryption(this, inputStream2)) {
throw new PgpGeneralException(
getString(R.string.error_no_known_encryption_found));
}
// we do not support symmetric decryption from the API!
throw new Exception("Symmetric decryption is not supported!");
}
Log.d(Constants.TAG, "secretKeyId " + secretKeyId);
passphrase = getCachedPassphrase(secretKeyId, allowUserInteraction);
if (passphrase == null) {
throw new WrongPassphraseException("No or wrong passphrase!");
}
// get passphrase from cache, if key has "no" passphrase, this returns an empty String
String passphrase = PassphraseCacheService.getCachedPassphrase(getContext(), appSettings.getKeyId());
if (passphrase == null) {
return getPassphraseBundleIntent(appSettings.getKeyId());
}
// build InputData and write into OutputStream
InputStream inputStream = new ByteArrayInputStream(inputBytes);
long inputLength = inputBytes.length;
InputData inputData = new InputData(inputStream, inputLength);
// Get Input- and OutputStream from ParcelFileDescriptor
InputStream is = new ParcelFileDescriptor.AutoCloseInputStream(input);
OutputStream os = new ParcelFileDescriptor.AutoCloseOutputStream(output);
try {
long inputLength = is.available();
InputData inputData = new InputData(is, inputLength);
OutputStream outputStream = new ByteArrayOutputStream();
Bundle outputBundle;
PgpOperation operation = new PgpOperation(getContext(), null, inputData, outputStream);
if (signedOnly) {
outputBundle = operation.verifyText();
} else {
outputBundle = operation.decryptAndVerify(passphrase, false);
PgpOperation operation = new PgpOperation(getContext(), null, inputData, os);
operation.signText(appSettings.getKeyId(), passphrase, appSettings.getHashAlgorithm(),
Preferences.getPreferences(this).getForceV3Signatures());
} finally {
is.close();
os.close();
}
outputStream.close();
byte[] outputBytes = ((ByteArrayOutputStream) outputStream).toByteArray();
// get signature informations from bundle
boolean signature = outputBundle.getBoolean(KeychainIntentService.RESULT_SIGNATURE);
OpenPgpSignatureResult sigResult = null;
if (signature) {
long signatureKeyId = outputBundle
.getLong(KeychainIntentService.RESULT_SIGNATURE_KEY_ID);
String signatureUserId = outputBundle
.getString(KeychainIntentService.RESULT_SIGNATURE_USER_ID);
boolean signatureSuccess = outputBundle
.getBoolean(KeychainIntentService.RESULT_SIGNATURE_SUCCESS);
boolean signatureUnknown = outputBundle
.getBoolean(KeychainIntentService.RESULT_SIGNATURE_UNKNOWN);
int signatureStatus = OpenPgpSignatureResult.SIGNATURE_ERROR;
if (signatureSuccess) {
signatureStatus = OpenPgpSignatureResult.SIGNATURE_SUCCESS_TRUSTED;
} else if (signatureUnknown) {
signatureStatus = OpenPgpSignatureResult.SIGNATURE_UNKNOWN_PUB_KEY;
}
sigResult = new OpenPgpSignatureResult(signatureStatus, signatureUserId,
signedOnly, signatureKeyId);
}
OpenPgpData output = new OpenPgpData(new String(outputBytes));
// return over handler on client side
callback.onSuccess(output, sigResult);
} catch (UserInteractionRequiredException e) {
// callbackOpenPgpError(callback, OpenPgpError.USER_INTERACTION_REQUIRED, e.getMessage());
} catch (WrongPassphraseException e) {
callbackOpenPgpError(callback, OpenPgpError.NO_OR_WRONG_PASSPHRASE, e.getMessage());
Bundle result = new Bundle();
result.putInt(OpenPgpConstants.RESULT_CODE, OpenPgpConstants.RESULT_CODE_SUCCESS);
return result;
} catch (Exception e) {
callbackOpenPgpError(callback, OpenPgpError.GENERIC_ERROR, e.getMessage());
Bundle result = new Bundle();
result.putInt(OpenPgpConstants.RESULT_CODE, OpenPgpConstants.RESULT_CODE_ERROR);
result.putParcelable(OpenPgpConstants.RESULT_ERRORS,
new OpenPgpError(OpenPgpError.GENERIC_ERROR, e.getMessage()));
return result;
}
}
/**
* Returns error to IOpenPgpCallback
*
* @param callback
* @param errorId
* @param message
*/
private void callbackOpenPgpError(IOpenPgpCallback callback, int errorId, String message) {
private Bundle decryptAndVerifyImpl(Bundle params, ParcelFileDescriptor input,
ParcelFileDescriptor output, AppSettings appSettings) {
try {
callback.onError(new OpenPgpError(0, message));
} catch (Exception t) {
Log.e(Constants.TAG,
"Exception while returning OpenPgpError to client via callback.onError()", t);
}
}
// Get Input- and OutputStream from ParcelFileDescriptor
InputStream is = new ParcelFileDescriptor.AutoCloseInputStream(input);
OutputStream os = new ParcelFileDescriptor.AutoCloseOutputStream(output);
OpenPgpSignatureResult sigResult = null;
try {
private void callbackOpenPgpError(IOpenPgpKeyIdsCallback callback, int errorId, String message) {
try {
callback.onError(new OpenPgpError(0, message));
} catch (Exception t) {
Log.e(Constants.TAG,
"Exception while returning OpenPgpError to client via callback.onError()", t);
// TODOs API 2.0:
// implement verify-only!
// fix the mess: http://stackoverflow.com/questions/148130/how-do-i-peek-at-the-first-two-bytes-in-an-inputstream
// should we allow to decrypt everything under every key id or only the one set?
// TODO: instead of trying to get the passphrase before
// pause stream when passphrase is missing and then resume
// TODO: this is not really needed
// checked if it is text with BEGIN and END tags
// String message = new String(inputBytes);
// Log.d(Constants.TAG, "in: " + message);
boolean signedOnly = false;
// Matcher matcher = PgpHelper.PGP_MESSAGE.matcher(message);
// if (matcher.matches()) {
// Log.d(Constants.TAG, "PGP_MESSAGE matched");
// message = matcher.group(1);
// // replace non breakable spaces
// message = message.replaceAll("\\xa0", " ");
//
// // overwrite inputBytes
// inputBytes = message.getBytes();
// } else {
// matcher = PgpHelper.PGP_SIGNED_MESSAGE.matcher(message);
// if (matcher.matches()) {
// signedOnly = true;
// Log.d(Constants.TAG, "PGP_SIGNED_MESSAGE matched");
// message = matcher.group(1);
// // replace non breakable spaces
// message = message.replaceAll("\\xa0", " ");
//
// // overwrite inputBytes
// inputBytes = message.getBytes();
// } else {
// Log.d(Constants.TAG, "Nothing matched! Binary?");
// }
// }
// END TODO
// Log.d(Constants.TAG, "in: " + new String(inputBytes));
// TODO: This allows to decrypt messages with ALL secret keys, not only the one for the
// app, Fix this?
// String passphrase = null;
// if (!signedOnly) {
// // BEGIN Get key
// // TODO: this input stream is consumed after PgpMain.getDecryptionKeyId()... do it
// // better!
// InputStream inputStream2 = new ByteArrayInputStream(inputBytes);
//
// // TODO: duplicates functions from DecryptActivity!
// long secretKeyId;
// try {
// if (inputStream2.markSupported()) {
// // should probably set this to the max size of two
// // pgpF objects, if it even needs to be anything other
// // than 0.
// inputStream2.mark(200);
// }
// secretKeyId = PgpHelper.getDecryptionKeyId(this, inputStream2);
// if (secretKeyId == Id.key.none) {
// throw new PgpGeneralException(getString(R.string.error_no_secret_key_found));
// }
// } catch (NoAsymmetricEncryptionException e) {
// if (inputStream2.markSupported()) {
// inputStream2.reset();
// }
// secretKeyId = Id.key.symmetric;
// if (!PgpOperation.hasSymmetricEncryption(this, inputStream2)) {
// throw new PgpGeneralException(
// getString(R.string.error_no_known_encryption_found));
// }
// // we do not support symmetric decryption from the API!
// throw new Exception("Symmetric decryption is not supported!");
// }
//
// Log.d(Constants.TAG, "secretKeyId " + secretKeyId);
// NOTE: currently this only gets the passphrase for the saved key
String passphrase = PassphraseCacheService.getCachedPassphrase(getContext(), appSettings.getKeyId());
if (passphrase == null) {
return getPassphraseBundleIntent(appSettings.getKeyId());
}
// }
// build InputData and write into OutputStream
long inputLength = is.available();
InputData inputData = new InputData(is, inputLength);
Bundle outputBundle;
PgpOperation operation = new PgpOperation(getContext(), null, inputData, os);
if (signedOnly) {
outputBundle = operation.verifyText();
} else {
// BIG TODO: instead of trying to get the passphrase before
// pause stream when passphrase is missing and then resume
outputBundle = operation.decryptAndVerify(passphrase, false);
}
// outputStream.close();
// byte[] outputBytes = ((ByteArrayOutputStream) outputStream).toByteArray();
// get signature informations from bundle
boolean signature = outputBundle.getBoolean(KeychainIntentService.RESULT_SIGNATURE);
if (signature) {
long signatureKeyId = outputBundle
.getLong(KeychainIntentService.RESULT_SIGNATURE_KEY_ID);
String signatureUserId = outputBundle
.getString(KeychainIntentService.RESULT_SIGNATURE_USER_ID);
boolean signatureSuccess = outputBundle
.getBoolean(KeychainIntentService.RESULT_SIGNATURE_SUCCESS);
boolean signatureUnknown = outputBundle
.getBoolean(KeychainIntentService.RESULT_SIGNATURE_UNKNOWN);
int signatureStatus = OpenPgpSignatureResult.SIGNATURE_ERROR;
if (signatureSuccess) {
signatureStatus = OpenPgpSignatureResult.SIGNATURE_SUCCESS_CERTIFIED;
} else if (signatureUnknown) {
signatureStatus = OpenPgpSignatureResult.SIGNATURE_UNKNOWN_PUB_KEY;
}
sigResult = new OpenPgpSignatureResult(signatureStatus, signatureUserId,
signedOnly, signatureKeyId);
}
} finally {
is.close();
os.close();
}
Bundle result = new Bundle();
result.putInt(OpenPgpConstants.RESULT_CODE, OpenPgpConstants.RESULT_CODE_SUCCESS);
result.putParcelable(OpenPgpConstants.RESULT_SIGNATURE, sigResult);
return result;
} catch (Exception e) {
Bundle result = new Bundle();
result.putInt(OpenPgpConstants.RESULT_CODE, OpenPgpConstants.RESULT_CODE_ERROR);
result.putParcelable(OpenPgpConstants.RESULT_ERRORS,
new OpenPgpError(OpenPgpError.GENERIC_ERROR, e.getMessage()));
return result;
}
}
@ -536,6 +396,7 @@ public class OpenPgpService extends RemoteService {
* @param params
* @return
*/
private Bundle validateParamsAndVersion(Bundle params) {
if (params == null) {
Bundle result = new Bundle();
@ -557,6 +418,7 @@ public class OpenPgpService extends RemoteService {
return null;
}
// TODO: enqueue in thread pool!!!
private final IOpenPgpService.Stub mBinder = new IOpenPgpService.Stub() {
@Override
@ -568,28 +430,31 @@ public class OpenPgpService extends RemoteService {
return errorResult;
}
// Runnable r = new Runnable() {
// @Override
// public void run() {
return signImpl(input, output, appSettings);
// }
// };
// checkAndEnqueue(r);
// return null;
}
@Override
public Bundle encrypt(Bundle params, ParcelFileDescriptor input, ParcelFileDescriptor output) {
final AppSettings appSettings = getAppSettings();
return null;
Bundle errorResult = validateParamsAndVersion(params);
if (errorResult != null) {
return errorResult;
}
return encryptAndSignImpl(params, input, output, appSettings, false);
}
@Override
public Bundle signAndEncrypt(Bundle params, ParcelFileDescriptor input, ParcelFileDescriptor output) {
final AppSettings appSettings = getAppSettings();
return null;
Bundle errorResult = validateParamsAndVersion(params);
if (errorResult != null) {
return errorResult;
}
return encryptAndSignImpl(params, input, output, appSettings, true);
}
@Override
@ -598,67 +463,6 @@ public class OpenPgpService extends RemoteService {
return null;
}
// @Override
// public void encrypt(final OpenPgpData input, final OpenPgpData output, final long[] keyIds,
// final IOpenPgpCallback callback) throws RemoteException {
// final AppSettings settings = getAppSettings();
//
// Runnable r = new Runnable() {
// @Override
// public void run() {
// encryptAndSignSafe(input, output, keyIds, true, callback, settings, false);
// }
// };
//
// checkAndEnqueue(r);
// }
//
// @Override
// public void signAndEncrypt(final OpenPgpData input, final OpenPgpData output,
// final long[] keyIds, final IOpenPgpCallback callback) throws RemoteException {
// final AppSettings settings = getAppSettings();
//
// Runnable r = new Runnable() {
// @Override
// public void run() {
// encryptAndSignSafe(input, output, keyIds, true, callback, settings, true);
// }
// };
//
// checkAndEnqueue(r);
// }
//
// @Override
// public void sign(final OpenPgpData input, final OpenPgpData output,
// final IOpenPgpCallback callback) throws RemoteException {
// final AppSettings settings = getAppSettings();
//
// Runnable r = new Runnable() {
// @Override
// public void run() {
// signImpl(getInput(input), true, callback, settings);
// }
// };
//
// checkAndEnqueue(r);
// }
//
// @Override
// public void decryptAndVerify(final OpenPgpData input, final OpenPgpData output,
// final IOpenPgpCallback callback) throws RemoteException {
//
// final AppSettings settings = getAppSettings();
//
// Runnable r = new Runnable() {
// @Override
// public void run() {
// decryptAndVerifySafe(getInput(input), true, callback, settings);
// }
// };
//
// checkAndEnqueue(r);
// }
//
// @Override
// public void getKeyIds(final String[] userIds, final boolean allowUserInteraction,
// final IOpenPgpKeyIdsCallback callback) throws RemoteException {
@ -677,27 +481,6 @@ public class OpenPgpService extends RemoteService {
};
private static byte[] getInput(OpenPgpData data) {
// TODO: support Uri and ParcelFileDescriptor
byte[] inBytes = null;
switch (data.getType()) {
case OpenPgpData.TYPE_STRING:
inBytes = data.getString().getBytes();
break;
case OpenPgpData.TYPE_BYTE_ARRAY:
inBytes = data.getBytes();
break;
default:
Log.e(Constants.TAG, "Uri and ParcelFileDescriptor not supported right now!");
break;
}
return inBytes;
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;

View File

@ -26,7 +26,6 @@ import org.sufficientlysecure.keychain.Constants;
import org.sufficientlysecure.keychain.R;
import org.sufficientlysecure.keychain.provider.KeychainContract;
import org.sufficientlysecure.keychain.provider.ProviderHelper;
import org.sufficientlysecure.keychain.service.exception.WrongPackageSignatureException;
import org.sufficientlysecure.keychain.util.Log;
import org.sufficientlysecure.keychain.util.PausableThreadPoolExecutor;

View File

@ -19,6 +19,7 @@ package org.sufficientlysecure.keychain.service.remote;
import java.util.ArrayList;
import org.openintents.openpgp.util.OpenPgpConstants;
import org.sufficientlysecure.htmltextview.HtmlTextView;
import org.sufficientlysecure.keychain.Constants;
import org.sufficientlysecure.keychain.Id;
@ -86,15 +87,15 @@ public class RemoteServiceActivity extends ActionBarActivity {
protected void onStop() {
super.onStop();
// if (!finishHandled) {
// Message msg = Message.obtain();
// msg.arg1 = RemoteService.RegisterActivityCallback.CANCEL;
// try {
// mMessenger.send(msg);
// } catch (RemoteException e) {
// Log.e(Constants.TAG, "CryptoServiceActivity", e);
// }
// }
if (!finishHandled && mMessenger != null) {
Message msg = Message.obtain();
msg.arg1 = RemoteService.RegisterActivityCallback.CANCEL;
try {
mMessenger.send(msg);
} catch (RemoteException e) {
Log.e(Constants.TAG, "CryptoServiceActivity", e);
}
}
}
protected void handleActions(Intent intent, Bundle savedInstanceState) {
@ -212,39 +213,18 @@ public class RemoteServiceActivity extends ActionBarActivity {
new View.OnClickListener() {
@Override
public void onClick(View v) {
// ok
Message msg = Message.obtain();
msg.arg1 = OpenPgpService.SelectPubKeysActivityCallback.OKAY;
Bundle data = new Bundle();
data.putLongArray(
OpenPgpService.SelectPubKeysActivityCallback.PUB_KEY_IDS,
// return key ids to requesting activity
Intent finishIntent = new Intent();
finishIntent.putExtra(OpenPgpConstants.PARAMS_KEY_IDS,
mSelectFragment.getSelectedMasterKeyIds());
msg.setData(data);
try {
mMessenger.send(msg);
} catch (RemoteException e) {
Log.e(Constants.TAG, "CryptoServiceActivity", e);
}
finishHandled = true;
setResult(RESULT_OK, finishIntent);
finish();
}
}, R.string.btn_do_not_save, new View.OnClickListener() {
@Override
public void onClick(View v) {
// cancel
Message msg = Message.obtain();
msg.arg1 = OpenPgpService.SelectPubKeysActivityCallback.CANCEL;
try {
mMessenger.send(msg);
} catch (RemoteException e) {
Log.e(Constants.TAG, "CryptoServiceActivity", e);
}
finishHandled = true;
setResult(RESULT_CANCELED);
finish();
}
}
@ -287,6 +267,7 @@ public class RemoteServiceActivity extends ActionBarActivity {
@Override
public void onClick(View v) {
setResult(RESULT_OK);
finish();
}
});
@ -298,6 +279,7 @@ public class RemoteServiceActivity extends ActionBarActivity {
textView.setHtmlFromString(text);
} else {
Log.e(Constants.TAG, "Wrong action!");
setResult(RESULT_CANCELED);
finish();
}
}
@ -313,31 +295,12 @@ public class RemoteServiceActivity extends ActionBarActivity {
@Override
public void handleMessage(Message message) {
if (message.what == PassphraseDialogFragment.MESSAGE_OKAY) {
// Message msg = Message.obtain();
// msg.arg1 = OpenPgpService.PassphraseActivityCallback.OKAY;
// try {
// mMessenger.send(msg);
// } catch (RemoteException e) {
// Log.e(Constants.TAG, "CryptoServiceActivity", e);
// }
RemoteServiceActivity.this.setResult(RESULT_OK);
RemoteServiceActivity.this.finish();
} else {
// Message msg = Message.obtain();
// msg.arg1 = OpenPgpService.PassphraseActivityCallback.CANCEL;
// try {
// mMessenger.send(msg);
// } catch (RemoteException e) {
// Log.e(Constants.TAG, "CryptoServiceActivity", e);
// }
RemoteServiceActivity.this.setResult(RESULT_CANCELED);
RemoteServiceActivity.this.finish();
}
// finishHandled = true;
// finish();
RemoteServiceActivity.this.finish();
}
};
@ -351,8 +314,8 @@ public class RemoteServiceActivity extends ActionBarActivity {
passphraseDialog.show(getSupportFragmentManager(), "passphraseDialog");
} catch (PgpGeneralException e) {
Log.d(Constants.TAG, "No passphrase for this secret key, encrypt directly!");
// send message to handler to start encryption directly
// returnHandler.sendEmptyMessage(PassphraseDialogFragment.MESSAGE_OKAY);
RemoteServiceActivity.this.setResult(RESULT_OK);
RemoteServiceActivity.this.finish();
}
}
}

View File

@ -1,4 +1,4 @@
package org.sufficientlysecure.keychain.service.exception;
package org.sufficientlysecure.keychain.service.remote;
public class WrongPackageSignatureException extends Exception {

View File

@ -1,45 +0,0 @@
/*
* Copyright (C) 2013 Dominik Schürmann <dominik@dominikschuermann.de>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openintents.openpgp;
import org.openintents.openpgp.OpenPgpData;
import org.openintents.openpgp.OpenPgpSignatureResult;
import org.openintents.openpgp.OpenPgpError;
interface IOpenPgpCallback {
/**
* onSuccess returns on successful OpenPGP operations.
*
* @param output
* contains resulting output (decrypted content (when input was encrypted)
* or content without signature (when input was signed-only))
* @param signatureResult
* signatureResult is only non-null if decryptAndVerify() was called and the content
* was encrypted or signed-and-encrypted.
*/
oneway void onSuccess(in OpenPgpData output, in OpenPgpSignatureResult signatureResult);
/**
* onError returns on errors or when allowUserInteraction was set to false, but user interaction
* was required execute an OpenPGP operation.
*
* @param error
* See OpenPgpError class for more information.
*/
oneway void onError(in OpenPgpError error);
}

View File

@ -1,39 +0,0 @@
/*
* Copyright (C) 2014 Dominik Schürmann <dominik@dominikschuermann.de>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openintents.openpgp;
import org.openintents.openpgp.OpenPgpError;
interface IOpenPgpKeyIdsCallback {
/**
* onSuccess returns on successful getKeyIds operations.
*
* @param keyIds
* returned key ids
*/
oneway void onSuccess(in long[] keyIds);
/**
* onError returns on errors or when allowUserInteraction was set to false, but user interaction
* was required execute an OpenPGP operation.
*
* @param error
* See OpenPgpError class for more information.
*/
oneway void onError(in OpenPgpError error);
}

View File

@ -16,10 +16,6 @@
package org.openintents.openpgp;
import org.openintents.openpgp.OpenPgpData;
import org.openintents.openpgp.IOpenPgpCallback;
import org.openintents.openpgp.IOpenPgpKeyIdsCallback;
interface IOpenPgpService {
/**
@ -29,7 +25,7 @@ interface IOpenPgpService {
* params:
* int api_version (current: 1)
* boolean ascii_armor true/false (for output)
*
* String passphrase (for key, optional)
*
* Bundle return:
* int result_code 0,1, or 2 (see OpenPgpConstants)
@ -41,9 +37,6 @@ interface IOpenPgpService {
/**
* sign only
*
* params:
* String passphrase (optional)
*/
Bundle sign(in Bundle params, in ParcelFileDescriptor input, in ParcelFileDescriptor output);

View File

@ -1,20 +0,0 @@
/*
* Copyright (C) 2013 Dominik Schürmann <dominik@dominikschuermann.de>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openintents.openpgp;
// Declare OpenPgpData so AIDL can find it and knows that it implements the parcelable protocol.
parcelable OpenPgpData;

View File

@ -1,127 +0,0 @@
/*
* Copyright (C) 2013 Dominik Schürmann <dominik@dominikschuermann.de>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openintents.openpgp;
import android.net.Uri;
import android.os.Parcel;
import android.os.ParcelFileDescriptor;
import android.os.Parcelable;
public class OpenPgpData implements Parcelable {
public static final int TYPE_STRING = 0;
public static final int TYPE_BYTE_ARRAY = 1;
public static final int TYPE_FILE_DESCRIPTOR = 2;
public static final int TYPE_URI = 3;
int type;
String string;
byte[] bytes = new byte[0];
ParcelFileDescriptor fileDescriptor;
Uri uri;
public int getType() {
return type;
}
public String getString() {
return string;
}
public byte[] getBytes() {
return bytes;
}
public ParcelFileDescriptor getFileDescriptor() {
return fileDescriptor;
}
public Uri getUri() {
return uri;
}
public OpenPgpData() {
}
/**
* Not a real constructor. This can be used to define requested output type.
*
* @param type
*/
public OpenPgpData(int type) {
this.type = type;
}
public OpenPgpData(String string) {
this.string = string;
this.type = TYPE_STRING;
}
public OpenPgpData(byte[] bytes) {
this.bytes = bytes;
this.type = TYPE_BYTE_ARRAY;
}
public OpenPgpData(ParcelFileDescriptor fileDescriptor) {
this.fileDescriptor = fileDescriptor;
this.type = TYPE_FILE_DESCRIPTOR;
}
public OpenPgpData(Uri uri) {
this.uri = uri;
this.type = TYPE_URI;
}
public OpenPgpData(OpenPgpData b) {
this.string = b.string;
this.bytes = b.bytes;
this.fileDescriptor = b.fileDescriptor;
this.uri = b.uri;
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(type);
dest.writeString(string);
dest.writeInt(bytes.length);
dest.writeByteArray(bytes);
dest.writeParcelable(fileDescriptor, 0);
dest.writeParcelable(uri, 0);
}
public static final Creator<OpenPgpData> CREATOR = new Creator<OpenPgpData>() {
public OpenPgpData createFromParcel(final Parcel source) {
OpenPgpData vr = new OpenPgpData();
vr.type = source.readInt();
vr.string = source.readString();
vr.bytes = new byte[source.readInt()];
source.readByteArray(vr.bytes);
vr.fileDescriptor = source.readParcelable(ParcelFileDescriptor.class.getClassLoader());
vr.fileDescriptor = source.readParcelable(Uri.class.getClassLoader());
return vr;
}
public OpenPgpData[] newArray(final int size) {
return new OpenPgpData[size];
}
};
}

View File

@ -22,14 +22,14 @@ import android.os.Parcelable;
public class OpenPgpSignatureResult implements Parcelable {
// generic error on signature verification
public static final int SIGNATURE_ERROR = 0;
// successfully verified signature, with trusted public key
public static final int SIGNATURE_SUCCESS_TRUSTED = 1;
// successfully verified signature, with certified public key
public static final int SIGNATURE_SUCCESS_CERTIFIED = 1;
// no public key was found for this signature verification
// you can retrieve the key with
// getKeys(new String[] {String.valueOf(signatureResult.getKeyId)}, true, callback)
public static final int SIGNATURE_UNKNOWN_PUB_KEY = 2;
// successfully verified signature, but with untrusted public key
public static final int SIGNATURE_SUCCESS_UNTRUSTED = 3;
// successfully verified signature, but with certified public key
public static final int SIGNATURE_SUCCESS_UNCERTIFIED = 3;
int status;
boolean signatureOnly;

View File

@ -30,6 +30,7 @@ public class OpenPgpConstants {
// OpenPGP Radix-64, 33 percent overhead compared to binary, see http://tools.ietf.org/html/rfc4880#page-53)
public static final String PARAMS_REQUEST_ASCII_ARMOR = "ascii_armor";
// (for encrypt method)
public static final String PARAMS_USER_IDS = "user_ids";
public static final String PARAMS_KEY_IDS = "key_ids";
/* Bundle return */