1
0
mirror of https://github.com/moparisthebest/k-9 synced 2024-12-23 16:18:50 -05:00

New OpenPGP Provider API

This commit is contained in:
Dominik Schürmann 2014-02-21 17:38:20 +01:00
parent dd5ac0f1c4
commit 4a69ef1509
45 changed files with 2212 additions and 53 deletions

View File

@ -15,6 +15,7 @@ dependencies {
compile project(':plugins:Android-PullToRefresh:library')
compile project(':plugins:ckChangeLog:library')
compile project(':plugins:HoloColorPicker')
compile project(':plugins:keychain-api-library')
compile fileTree(dir: 'libs', include: '*.jar')
}
@ -37,6 +38,11 @@ android {
}
}
// Do not abort build if lint finds errors
lintOptions {
abortOnError false
}
packagingOptions {
exclude 'META-INF/DEPENDENCIES'
exclude 'META-INF/LICENSE'

View File

@ -15,6 +15,11 @@ android {
res.srcDirs = ['res']
}
}
// Do not abort build if lint finds errors
lintOptions {
abortOnError false
}
}
archivesBaseName = 'ActionBarSherlock'

View File

@ -11,6 +11,11 @@ android {
res.srcDirs = ['res']
}
}
// Do not abort build if lint finds errors
lintOptions {
abortOnError false
}
}
archivesBaseName = 'PullToRefresh'

View File

@ -11,4 +11,9 @@ android {
res.srcDirs = ['res']
}
}
// Do not abort build if lint finds errors
lintOptions {
abortOnError false
}
}

View File

@ -11,6 +11,11 @@ android {
res.srcDirs = ['res']
}
}
// Do not abort build if lint finds errors
lintOptions {
abortOnError false
}
}
archivesBaseName = 'ckChangeLog'

29
plugins/keychain-api-library/.gitignore vendored Normal file
View File

@ -0,0 +1,29 @@
#Android specific
bin
gen
obj
lint.xml
local.properties
release.properties
ant.properties
*.class
*.apk
#Gradle
.gradle
build
gradle.properties
#Maven
target
pom.xml.*
#Eclipse
.project
.classpath
.settings
.metadata
#IntelliJ IDEA
.idea
*.iml

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.sufficientlysecure.keychain.api"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="9"
android:targetSdkVersion="17" />
<application/>
</manifest>

View File

@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
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.

View File

@ -0,0 +1,35 @@
// please leave this here, so this library builds on its own
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:0.8.3'
}
}
apply plugin: 'android-library'
android {
compileSdkVersion 17
buildToolsVersion '19.0.1'
// NOTE: We are using the old folder structure to also support Eclipse
sourceSets {
main {
manifest.srcFile 'AndroidManifest.xml'
java.srcDirs = ['src']
resources.srcDirs = ['src']
aidl.srcDirs = ['src']
renderscript.srcDirs = ['src']
res.srcDirs = ['res']
assets.srcDirs = ['assets']
}
}
// Do not abort build if lint finds errors
lintOptions {
abortOnError false
}
}

View File

@ -0,0 +1,15 @@
# This file is automatically generated by Android Tools.
# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
#
# This file must be checked in Version Control Systems.
#
# To customize properties used by the Ant build system edit
# "ant.properties", and override values to adapt the script to your
# project structure.
#
# To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home):
#proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
# Project target.
target=android-19
android.library=true

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

View File

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="openpgp_list_preference_none">None</string>
<string name="openpgp_install_openkeychain_via">Install OpenKeychain via %s</string>
</resources>

View File

@ -0,0 +1,24 @@
/*
* 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;
interface IOpenPgpService {
// see OpenPgpApi for documentation
Intent execute(in Intent data, in ParcelFileDescriptor input, in ParcelFileDescriptor output);
}

View File

@ -0,0 +1,84 @@
/*
* 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 android.os.Parcel;
import android.os.Parcelable;
public class OpenPgpError implements Parcelable {
public static final int CLIENT_SIDE_ERROR = -1;
public static final int GENERIC_ERROR = 0;
public static final int INCOMPATIBLE_API_VERSIONS = 1;
public static final int NO_OR_WRONG_PASSPHRASE = 2;
public static final int NO_USER_IDS = 3;
int errorId;
String message;
public OpenPgpError() {
}
public OpenPgpError(int errorId, String message) {
this.errorId = errorId;
this.message = message;
}
public OpenPgpError(OpenPgpError b) {
this.errorId = b.errorId;
this.message = b.message;
}
public int getErrorId() {
return errorId;
}
public void setErrorId(int errorId) {
this.errorId = errorId;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(errorId);
dest.writeString(message);
}
public static final Creator<OpenPgpError> CREATOR = new Creator<OpenPgpError>() {
public OpenPgpError createFromParcel(final Parcel source) {
OpenPgpError error = new OpenPgpError();
error.errorId = source.readInt();
error.message = source.readString();
return error;
}
public OpenPgpError[] newArray(final int size) {
return new OpenPgpError[size];
}
};
}

View File

@ -0,0 +1,108 @@
/*
* 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 android.os.Parcel;
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 certified public key
public static final int SIGNATURE_SUCCESS_CERTIFIED = 1;
// no public key was found for this signature verification
public static final int SIGNATURE_UNKNOWN_PUB_KEY = 2;
// successfully verified signature, but with uncertified public key
public static final int SIGNATURE_SUCCESS_UNCERTIFIED = 3;
int status;
boolean signatureOnly;
String userId;
long keyId;
public int getStatus() {
return status;
}
public boolean isSignatureOnly() {
return signatureOnly;
}
public String getUserId() {
return userId;
}
public long getKeyId() {
return keyId;
}
public OpenPgpSignatureResult() {
}
public OpenPgpSignatureResult(int signatureStatus, String signatureUserId,
boolean signatureOnly, long keyId) {
this.status = signatureStatus;
this.signatureOnly = signatureOnly;
this.userId = signatureUserId;
this.keyId = keyId;
}
public OpenPgpSignatureResult(OpenPgpSignatureResult b) {
this.status = b.status;
this.userId = b.userId;
this.signatureOnly = b.signatureOnly;
this.keyId = b.keyId;
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(status);
dest.writeByte((byte) (signatureOnly ? 1 : 0));
dest.writeString(userId);
dest.writeLong(keyId);
}
public static final Creator<OpenPgpSignatureResult> CREATOR = new Creator<OpenPgpSignatureResult>() {
public OpenPgpSignatureResult createFromParcel(final Parcel source) {
OpenPgpSignatureResult vr = new OpenPgpSignatureResult();
vr.status = source.readInt();
vr.signatureOnly = source.readByte() == 1;
vr.userId = source.readString();
vr.keyId = source.readLong();
return vr;
}
public OpenPgpSignatureResult[] newArray(final int size) {
return new OpenPgpSignatureResult[size];
}
};
@Override
public String toString() {
String out = new String();
out += "\nstatus: " + status;
out += "\nuserId: " + userId;
out += "\nsignatureOnly: " + signatureOnly;
out += "\nkeyId: " + keyId;
return out;
}
}

View File

@ -0,0 +1,231 @@
/*
* 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.util;
import android.content.Context;
import android.content.Intent;
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;
public class OpenPgpApi {
//TODO: fix this documentation
/**
* General extras
* --------------
*
* Intent extras:
* int api_version (required)
* boolean ascii_armor (request ascii armor for ouput)
*
* returned Bundle:
* int result_code (0, 1, or 2 (see OpenPgpApi))
* OpenPgpError error (if result_code == 0)
* Intent intent (if result_code == 2)
*/
/**
* Sign only
*
* optional params:
* String passphrase (for key passphrase)
*/
/**
* Encrypt
*
* Intent extras:
* long[] key_ids
* or
* String[] user_ids (= emails of recipients) (if more than one key has this user_id, a PendingIntent is returned)
*
* optional extras:
* String passphrase (for key passphrase)
*/
/**
* Sign and encrypt
*
* Intent extras:
* same as in encrypt()
*/
/**
* Decrypts and verifies given input bytes. This methods handles encrypted-only, signed-and-encrypted,
* and also signed-only input.
*
* returned Bundle:
* OpenPgpSignatureResult signature_result
*/
/**
* Retrieves key ids based on given user ids (=emails)
*
* Intent extras:
* String[] user_ids
*
* returned Bundle:
* long[] key_ids
*/
public static final String TAG = "OpenPgp API";
public static final int API_VERSION = 2;
public static final String SERVICE_INTENT = "org.openintents.openpgp.IOpenPgpService";
public static final String ACTION_SIGN = "org.openintents.openpgp.action.SIGN";
public static final String ACTION_ENCRYPT = "org.openintents.openpgp.action.ENCRYPT";
public static final String ACTION_SIGN_AND_ENCTYPT = "org.openintents.openpgp.action.SIGN_AND_ENCRYPT";
public static final String ACTION_DECRYPT_VERIFY = "org.openintents.openpgp.action.DECRYPT_VERIFY";
public static final String ACTION_DOWNLOAD_KEYS = "org.openintents.openpgp.action.DOWNLOAD_KEYS";
public static final String ACTION_GET_KEY_IDS = "org.openintents.openpgp.action.GET_KEY_IDS";
/* Bundle params */
public static final String EXTRA_API_VERSION = "api_version";
// SIGN, ENCRYPT, SIGN_ENCRYPT, DECRYPT_VERIFY
// request ASCII Armor for output
// OpenPGP Radix-64, 33 percent overhead compared to binary, see http://tools.ietf.org/html/rfc4880#page-53)
public static final String EXTRA_REQUEST_ASCII_ARMOR = "ascii_armor";
// ENCRYPT, SIGN_ENCRYPT
public static final String EXTRA_USER_IDS = "user_ids";
public static final String EXTRA_KEY_IDS = "key_ids";
// optional parameter:
public static final String EXTRA_PASSPHRASE = "passphrase";
/* Service Bundle returns */
public static final String RESULT_CODE = "result_code";
public static final String RESULT_SIGNATURE = "signature";
public static final String RESULT_ERRORS = "error";
public static final String RESULT_INTENT = "intent";
// get actual error object from RESULT_ERRORS
public static final int RESULT_CODE_ERROR = 0;
// success!
public static final int RESULT_CODE_SUCCESS = 1;
// executeServiceMethod intent and do it again with intent
public static final int RESULT_CODE_USER_INTERACTION_REQUIRED = 2;
IOpenPgpService mService;
Context mContext;
public OpenPgpApi(Context context, IOpenPgpService service) {
this.mContext = context;
this.mService = service;
}
public interface IOpenPgpCallback {
void onReturn(final Intent result);
}
private class OpenPgpAsyncTask extends AsyncTask<Void, Integer, Intent> {
Intent data;
InputStream is;
OutputStream os;
IOpenPgpCallback callback;
private OpenPgpAsyncTask(Intent data, InputStream is, OutputStream os, IOpenPgpCallback callback) {
this.data = data;
this.is = is;
this.os = os;
this.callback = callback;
}
@Override
protected Intent doInBackground(Void... unused) {
return executeApi(data, is, os);
}
protected void onPostExecute(Intent result) {
callback.onReturn(result);
}
}
public void executeApiAsync(Intent data, InputStream is, OutputStream os, IOpenPgpCallback callback) {
OpenPgpAsyncTask task = new OpenPgpAsyncTask(data, is, os, callback);
// don't serialize async tasks!
// http://commonsware.com/blog/2012/04/20/asynctask-threading-regression-confirmed.html
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[]) null);
} else {
task.execute((Void[]) null);
}
}
public Intent executeApi(Intent data, InputStream is, OutputStream os) {
try {
data.putExtra(EXTRA_API_VERSION, OpenPgpApi.API_VERSION);
Intent result = null;
if (ACTION_GET_KEY_IDS.equals(data.getAction())) {
result = mService.execute(data, null, null);
return result;
} else {
// send the input and output pfds
ParcelFileDescriptor 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,
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;
}
} catch (Exception e) {
Log.e(OpenPgpApi.TAG, "Exception", e);
Intent result = new Intent();
result.putExtra(RESULT_CODE, RESULT_CODE_ERROR);
result.putExtra(RESULT_ERRORS,
new OpenPgpError(OpenPgpError.CLIENT_SIDE_ERROR, e.getMessage()));
return result;
}
}
}

View File

@ -0,0 +1,257 @@
/*
* 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.util;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.preference.DialogPreference;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.TextView;
import org.sufficientlysecure.keychain.api.R;
import java.util.ArrayList;
import java.util.List;
/**
* Does not extend ListPreference, but is very similar to it!
* http://grepcode.com/file_/repository.grepcode.com/java/ext/com.google.android/android/4.4_r1/android/preference/ListPreference.java/?v=source
*/
public class OpenPgpListPreference extends DialogPreference {
private static final String OPENKEYCHAIN_PACKAGE = "org.sufficientlysecure.keychain";
private static final String MARKET_INTENT_URI_BASE = "market://details?id=%s";
private static final Intent MARKET_INTENT = new Intent(Intent.ACTION_VIEW, Uri.parse(
String.format(MARKET_INTENT_URI_BASE, OPENKEYCHAIN_PACKAGE)));
private ArrayList<OpenPgpProviderEntry> mLegacyList = new ArrayList<OpenPgpProviderEntry>();
private ArrayList<OpenPgpProviderEntry> mList = new ArrayList<OpenPgpProviderEntry>();
private String mSelectedPackage;
public OpenPgpListPreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
public OpenPgpListPreference(Context context) {
this(context, null);
}
/**
* Public method to add new entries for legacy applications
*
* @param packageName
* @param simpleName
* @param icon
*/
public void addLegacyProvider(int position, String packageName, String simpleName, Drawable icon) {
mLegacyList.add(position, new OpenPgpProviderEntry(packageName, simpleName, icon));
}
@Override
protected void onPrepareDialogBuilder(Builder builder) {
mList.clear();
// add "none"-entry
mList.add(0, new OpenPgpProviderEntry("",
getContext().getString(R.string.openpgp_list_preference_none),
getContext().getResources().getDrawable(R.drawable.ic_action_cancel_launchersize_light)));
// add all additional (legacy) providers
mList.addAll(mLegacyList);
// search for OpenPGP providers...
ArrayList<OpenPgpProviderEntry> providerList = new ArrayList<OpenPgpProviderEntry>();
Intent intent = new Intent(OpenPgpApi.SERVICE_INTENT);
List<ResolveInfo> resInfo = getContext().getPackageManager().queryIntentServices(intent, 0);
if (!resInfo.isEmpty()) {
for (ResolveInfo resolveInfo : resInfo) {
if (resolveInfo.serviceInfo == null)
continue;
String packageName = resolveInfo.serviceInfo.packageName;
String simpleName = String.valueOf(resolveInfo.serviceInfo.loadLabel(getContext()
.getPackageManager()));
Drawable icon = resolveInfo.serviceInfo.loadIcon(getContext().getPackageManager());
providerList.add(new OpenPgpProviderEntry(packageName, simpleName, icon));
}
}
if (providerList.isEmpty()) {
// add install links if provider list is empty
resInfo = getContext().getPackageManager().queryIntentActivities
(MARKET_INTENT, 0);
for (ResolveInfo resolveInfo : resInfo) {
Intent marketIntent = new Intent(MARKET_INTENT);
marketIntent.setPackage(resolveInfo.activityInfo.packageName);
Drawable icon = resolveInfo.activityInfo.loadIcon(getContext().getPackageManager());
String marketName = String.valueOf(resolveInfo.activityInfo.applicationInfo
.loadLabel(getContext().getPackageManager()));
String simpleName = String.format(getContext().getString(R.string
.openpgp_install_openkeychain_via), marketName);
mList.add(new OpenPgpProviderEntry(OPENKEYCHAIN_PACKAGE, simpleName,
icon, marketIntent));
}
} else {
// add provider
mList.addAll(providerList);
}
// Init ArrayAdapter with OpenPGP Providers
ListAdapter adapter = new ArrayAdapter<OpenPgpProviderEntry>(getContext(),
android.R.layout.select_dialog_singlechoice, android.R.id.text1, mList) {
public View getView(int position, View convertView, ViewGroup parent) {
// User super class to create the View
View v = super.getView(position, convertView, parent);
TextView tv = (TextView) v.findViewById(android.R.id.text1);
// Put the image on the TextView
tv.setCompoundDrawablesWithIntrinsicBounds(mList.get(position).icon, null,
null, null);
// Add margin between image and text (support various screen densities)
int dp10 = (int) (10 * getContext().getResources().getDisplayMetrics().density + 0.5f);
tv.setCompoundDrawablePadding(dp10);
return v;
}
};
builder.setSingleChoiceItems(adapter, getIndexOfProviderList(getValue()),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
OpenPgpProviderEntry entry = mList.get(which);
if (entry.intent != null) {
/*
* Intents are called as activity
*
* Current approach is to assume the user installed the app.
* If he does not, the selected package is not valid.
*
* However applications should always consider this could happen,
* as the user might remove the currently used OpenPGP app.
*/
getContext().startActivity(entry.intent);
}
mSelectedPackage = entry.packageName;
/*
* Clicking on an item simulates the positive button click, and dismisses
* the dialog.
*/
OpenPgpListPreference.this.onClick(dialog, DialogInterface.BUTTON_POSITIVE);
dialog.dismiss();
}
});
/*
* The typical interaction for list-based dialogs is to have click-on-an-item dismiss the
* dialog instead of the user having to press 'Ok'.
*/
builder.setPositiveButton(null, null);
}
@Override
protected void onDialogClosed(boolean positiveResult) {
super.onDialogClosed(positiveResult);
if (positiveResult && (mSelectedPackage != null)) {
if (callChangeListener(mSelectedPackage)) {
setValue(mSelectedPackage);
}
}
}
private int getIndexOfProviderList(String packageName) {
for (OpenPgpProviderEntry app : mList) {
if (app.packageName.equals(packageName)) {
return mList.indexOf(app);
}
}
return -1;
}
public void setValue(String packageName) {
mSelectedPackage = packageName;
persistString(packageName);
}
public String getValue() {
return mSelectedPackage;
}
public String getEntry() {
return getEntryByValue(mSelectedPackage);
}
@Override
protected Object onGetDefaultValue(TypedArray a, int index) {
return a.getString(index);
}
@Override
protected void onSetInitialValue(boolean restoreValue, Object defaultValue) {
setValue(restoreValue ? getPersistedString(mSelectedPackage) : (String) defaultValue);
}
public String getEntryByValue(String packageName) {
for (OpenPgpProviderEntry app : mList) {
if (app.packageName.equals(packageName)) {
return app.simpleName;
}
}
return null;
}
private static class OpenPgpProviderEntry {
private String packageName;
private String simpleName;
private Drawable icon;
private Intent intent;
public OpenPgpProviderEntry(String packageName, String simpleName, Drawable icon) {
this.packageName = packageName;
this.simpleName = simpleName;
this.icon = icon;
}
public OpenPgpProviderEntry(String packageName, String simpleName, Drawable icon, Intent intent) {
this(packageName, simpleName, icon);
this.intent = intent;
}
@Override
public String toString() {
return simpleName;
}
}
}

View File

@ -0,0 +1,88 @@
/*
* 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.util;
import org.openintents.openpgp.IOpenPgpService;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
public class OpenPgpServiceConnection {
private Context mApplicationContext;
private boolean mBound;
private IOpenPgpService mService;
private String mProviderPackageName;
public OpenPgpServiceConnection(Context context, String providerPackageName) {
this.mApplicationContext = context.getApplicationContext();
this.mProviderPackageName = providerPackageName;
}
public IOpenPgpService getService() {
return mService;
}
public boolean isBound() {
return mBound;
}
private ServiceConnection mServiceConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName name, IBinder service) {
mService = IOpenPgpService.Stub.asInterface(service);
mBound = true;
}
public void onServiceDisconnected(ComponentName name) {
mService = null;
mBound = false;
}
};
/**
* If not already bound, bind to service!
*
* @return
*/
public boolean bindToService() {
// if not already bound...
if (mService == null && !mBound) {
try {
Intent serviceIntent = new Intent();
serviceIntent.setAction(IOpenPgpService.class.getName());
// NOTE: setPackage is very important to restrict the intent to this provider only!
serviceIntent.setPackage(mProviderPackageName);
mApplicationContext.bindService(serviceIntent, mServiceConnection,
Context.BIND_AUTO_CREATE);
return true;
} catch (Exception e) {
return false;
}
} else {
return true;
}
}
public void unbindFromService() {
mApplicationContext.unbindService(mServiceConnection);
}
}

View File

@ -0,0 +1,64 @@
/*
* 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.util;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ResolveInfo;
public class OpenPgpUtils {
public static final Pattern PGP_MESSAGE = Pattern.compile(
".*?(-----BEGIN PGP MESSAGE-----.*?-----END PGP MESSAGE-----).*",
Pattern.DOTALL);
public static final Pattern PGP_SIGNED_MESSAGE = Pattern.compile(
".*?(-----BEGIN PGP SIGNED MESSAGE-----.*?-----BEGIN PGP SIGNATURE-----.*?-----END PGP SIGNATURE-----).*",
Pattern.DOTALL);
public static final int PARSE_RESULT_NO_PGP = -1;
public static final int PARSE_RESULT_MESSAGE = 0;
public static final int PARSE_RESULT_SIGNED_MESSAGE = 1;
public static int parseMessage(String message) {
Matcher matcherSigned = PGP_SIGNED_MESSAGE.matcher(message);
Matcher matcherMessage = PGP_MESSAGE.matcher(message);
if (matcherMessage.matches()) {
return PARSE_RESULT_MESSAGE;
} else if (matcherSigned.matches()) {
return PARSE_RESULT_SIGNED_MESSAGE;
} else {
return PARSE_RESULT_NO_PGP;
}
}
public static boolean isAvailable(Context context) {
Intent intent = new Intent(OpenPgpApi.SERVICE_INTENT);
List<ResolveInfo> resInfo = context.getPackageManager().queryIntentServices(intent, 0);
if (!resInfo.isEmpty()) {
return true;
} else {
return false;
}
}
}

View File

@ -0,0 +1,103 @@
/*
* Copyright (C) 2014 Dominik Schürmann <dominik@dominikschuermann.de>
* 2013 Flow (http://stackoverflow.com/questions/18212152/transfer-inputstream-to-another-service-across-process-boundaries-with-parcelf)
*
* 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.util;
import android.os.ParcelFileDescriptor;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class ParcelFileDescriptorUtil {
public interface IThreadListener {
void onThreadFinished(final Thread thread);
}
public static ParcelFileDescriptor pipeFrom(InputStream inputStream, IThreadListener listener)
throws IOException {
ParcelFileDescriptor[] pipe = ParcelFileDescriptor.createPipe();
ParcelFileDescriptor readSide = pipe[0];
ParcelFileDescriptor writeSide = pipe[1];
// start the transfer thread
new TransferThread(inputStream, new ParcelFileDescriptor.AutoCloseOutputStream(writeSide),
listener)
.start();
return readSide;
}
public static ParcelFileDescriptor pipeTo(OutputStream outputStream, IThreadListener listener)
throws IOException {
ParcelFileDescriptor[] pipe = ParcelFileDescriptor.createPipe();
ParcelFileDescriptor readSide = pipe[0];
ParcelFileDescriptor writeSide = pipe[1];
// start the transfer thread
new TransferThread(new ParcelFileDescriptor.AutoCloseInputStream(readSide), outputStream,
listener)
.start();
return writeSide;
}
static class TransferThread extends Thread {
final InputStream mIn;
final OutputStream mOut;
final IThreadListener mListener;
TransferThread(InputStream in, OutputStream out, IThreadListener listener) {
super("ParcelFileDescriptor Transfer Thread");
mIn = in;
mOut = out;
mListener = listener;
setDaemon(true);
}
@Override
public void run() {
byte[] buf = new byte[1024];
int len;
try {
while ((len = mIn.read(buf)) > 0) {
mOut.write(buf, 0, len);
}
mOut.flush(); // just to be safe
} catch (IOException e) {
//Log.e(OpenPgpApi.TAG, "TransferThread" + getId() + ": writing failed", e);
} finally {
try {
mIn.close();
} catch (IOException e) {
//Log.e(OpenPgpApi.TAG, "TransferThread" + getId(), e);
}
try {
mOut.close();
} catch (IOException e) {
//Log.e(OpenPgpApi.TAG, "TransferThread" + getId(), e);
}
}
if (mListener != null) {
//Log.d(OpenPgpApi.TAG, "TransferThread " + getId() + " finished!");
mListener.onThreadFinished(this);
}
}
}
}

View File

@ -0,0 +1,37 @@
/*
* 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.sufficientlysecure.keychain.api;
public class OpenKeychainIntents {
public static final String ENCRYPT = "org.sufficientlysecure.keychain.action.ENCRYPT";
public static final String ENCRYPT_EXTRA_TEXT = "text"; // String
public static final String ENCRYPT_ASCII_ARMOR = "ascii_armor"; // boolean
public static final String DECRYPT = "org.sufficientlysecure.keychain.action.DECRYPT";
public static final String DECRYPT_EXTRA_TEXT = "text"; // String
public static final String IMPORT_KEY = "org.sufficientlysecure.keychain.action.IMPORT_KEY";
public static final String IMPORT_KEY_EXTRA_KEY_BYTES = "key_bytes"; // byte[]
public static final String IMPORT_KEY_FROM_KEYSERVER = "org.sufficientlysecure.keychain.action.IMPORT_KEY_FROM_KEYSERVER";
public static final String IMPORT_KEY_FROM_KEYSERVER_QUERY = "query"; // String
public static final String IMPORT_KEY_FROM_KEYSERVER_FINGERPRINT = "fingerprint"; // String
public static final String IMPORT_KEY_FROM_QR_CODE = "org.sufficientlysecure.keychain.action.IMPORT_KEY_FROM_QR_CODE";
}

View File

@ -17,3 +17,4 @@ android.library.reference.1=plugins/ActionBarSherlock/library
android.library.reference.2=plugins/Android-PullToRefresh/library
android.library.reference.3=plugins/ckChangeLog/library
android.library.reference.4=plugins/HoloColorPicker
android.library.reference.5=plugins/keychain-api-library

View File

@ -251,5 +251,7 @@
</LinearLayout>
<include layout="@layout/message_view_crypto_layout" />
<include layout="@layout/message_view_openpgp_layout"/>
</com.fsck.k9.view.MessageHeader>

View File

@ -0,0 +1,91 @@
<?xml version="1.0" encoding="utf-8"?>
<com.fsck.k9.view.MessageOpenPgpView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/layout_decrypt_openpgp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:visibility="gone" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1.00"
android:orientation="vertical"
android:padding="2dp" >
<TextView
android:id="@+id/openpgp_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:ellipsize="end"
android:gravity="center"
android:maxLines="1"
android:padding="2dp"
android:singleLine="true"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="?android:textColorPrimaryInverse"
android:textIsSelectable="false" />
<RelativeLayout
android:id="@+id/openpgp_signature_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="horizontal"
android:padding="2dp"
android:visibility="gone" >
<RelativeLayout
android:id="@+id/openpgp_signature_layout_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<ImageView
android:id="@+id/openpgp_signature"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/signed_large" />
<ImageView
android:id="@+id/openpgp_signature_status"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/overlay_error" />
</RelativeLayout>
<TextView
android:id="@+id/openpgp_user_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toRightOf="@+id/openpgp_signature_layout_image"
android:ellipsize="end"
android:paddingLeft="5dip"
android:text="User Id"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="?android:textColorPrimaryInverse" />
</RelativeLayout>
</LinearLayout>
<Button
android:id="@+id/openpgp_get_key"
style="?android:attr/buttonStyleSmall"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="@+id/openpgp_signature_layout_image"
android:layout_gravity="center_vertical"
android:text="@string/openpgp_get_key"
android:visibility="gone" />
<ProgressBar
android:id="@+id/openpgp_progress"
style="?android:attr/progressBarStyleSmallInverse"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:padding="4dp"
android:visibility="gone" />
</com.fsck.k9.view.MessageOpenPgpView>

View File

@ -628,16 +628,6 @@
<item>10</item>
</string-array>
<string-array name="account_settings_crypto_app_entries">
<item>@string/account_settings_crypto_app_none</item>
<item>APG</item>
</string-array>
<string-array name="account_settings_crypto_app_values" translatable="false">
<item></item>
<item>apg</item>
</string-array>
<string-array name="settings_preview_lines_values" translatable="false">
<item>0</item>
<item>1</item>

View File

@ -1,4 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="message_list_item_footer_background">#eeeeee</color>
<color name="openpgp_red">#CC0000</color>
<color name="openpgp_orange">#FF8800</color>
<color name="openpgp_green">#669900</color>
<color name="openpgp_blue">#336699</color>
</resources>

View File

@ -1153,4 +1153,17 @@ Please submit bug reports, contribute new features and ask questions at
<string name="fetching_attachment_dialog_title_send">Sending message</string>
<string name="fetching_attachment_dialog_title_save">Saving draft</string>
<string name="fetching_attachment_dialog_message">Fetching attachment…</string>
<!-- === OpenPGP specific ================================================================== -->
<string name="openpgp_decrypting_verifying">Decrypting/Verifying…</string>
<string name="openpgp_successful_decryption">Successful decryption</string>
<string name="openpgp_signature_valid">Valid signature</string>
<string name="openpgp_signature_unknown">Unknown signer</string>
<string name="openpgp_signature_invalid">Invalid signature</string>
<string name="openpgp_signature_unknown_text">Missing public key for this signature</string>
<string name="openpgp_successful_decryption_valid_signature">Successful decryption and valid signature</string>
<string name="openpgp_successful_decryption_unknown_signature">Successful decryption but missing public key</string>
<string name="openpgp_get_key">Lookup missing key</string>
<string name="openpgp_error">OpenPGP Error:</string>
</resources>

View File

@ -464,13 +464,10 @@
android:title="@string/account_settings_crypto"
android:key="crypto">
<ListPreference
<org.openintents.openpgp.util.OpenPgpListPreference
android:persistent="false"
android:key="crypto_app"
android:title="@string/account_settings_crypto_app"
android:entries="@array/account_settings_crypto_app_entries"
android:entryValues="@array/account_settings_crypto_app_values"
android:dialogTitle="@string/account_settings_crypto_app" />
android:title="@string/account_settings_crypto_app" />
<CheckBoxPreference
android:persistent="false"

View File

@ -2,3 +2,4 @@ include ':plugins:ActionBarSherlock:library'
include ':plugins:Android-PullToRefresh:library'
include ':plugins:ckChangeLog:library'
include ':plugins:HoloColorPicker'
include ':plugins:keychain-api-library'

View File

@ -1719,6 +1719,14 @@ public class Account implements BaseAccount {
}
return mCryptoProvider;
}
public synchronized String getOpenPgpProvider() {
// return null if set to "APG" or "None"
if (getCryptoApp().equals("apg") || getCryptoApp().equals("")) {
return null;
}
return getCryptoApp();
}
public synchronized NotificationSetting getNotificationSetting() {
return mNotificationSetting;

View File

@ -3,12 +3,14 @@ package com.fsck.k9.activity;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.ClipData;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.AsyncTask;
@ -25,6 +27,7 @@ import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.Window;
@ -47,6 +50,7 @@ import android.widget.LinearLayout;
import android.widget.MultiAutoCompleteTextView;
import android.widget.TextView;
import android.widget.Toast;
import com.fsck.k9.Account;
import com.fsck.k9.Account.MessageFormat;
import com.fsck.k9.Account.QuoteStyle;
@ -88,13 +92,21 @@ import com.fsck.k9.mail.store.LocalStore.LocalAttachmentBody;
import com.fsck.k9.mail.store.LocalStore.TempFileBody;
import com.fsck.k9.mail.store.LocalStore.TempFileMessageBody;
import com.fsck.k9.view.MessageWebView;
import org.apache.james.mime4j.codec.EncoderUtil;
import org.apache.james.mime4j.util.MimeUtil;
import org.htmlcleaner.CleanerProperties;
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.SimpleHtmlSerializer;
import org.htmlcleaner.TagNode;
import org.openintents.openpgp.OpenPgpError;
import org.openintents.openpgp.util.OpenPgpApi;
import org.openintents.openpgp.util.OpenPgpServiceConnection;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Arrays;
@ -179,6 +191,8 @@ public class MessageCompose extends K9Activity implements OnClickListener,
private static final int CONTACT_PICKER_BCC2 = 9;
private static final Account[] EMPTY_ACCOUNT_ARRAY = new Account[0];
private static final int REQUEST_CODE_SIGN_ENCRYPT = 12;
/**
* Regular expression to remove the first localized "Re:" prefix in subjects.
@ -301,7 +315,10 @@ public class MessageCompose extends K9Activity implements OnClickListener,
private PgpData mPgpData = null;
private boolean mAutoEncrypt = false;
private boolean mContinueWithoutPublicKey = false;
private String mOpenPgpProvider;
private OpenPgpServiceConnection mOpenPgpServiceConnection;
private String mReferences;
private String mInReplyTo;
private Menu mMenu;
@ -826,6 +843,12 @@ public class MessageCompose extends K9Activity implements OnClickListener,
mEncryptLayout = findViewById(R.id.layout_encrypt);
mCryptoSignatureCheckbox = (CheckBox)findViewById(R.id.cb_crypto_signature);
mCryptoSignatureCheckbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
updateMessageFormat();
}
});
mCryptoSignatureUserId = (TextView)findViewById(R.id.userId);
mCryptoSignatureUserIdRest = (TextView)findViewById(R.id.userIdRest);
mEncryptCheckbox = (CheckBox)findViewById(R.id.cb_encrypt);
@ -843,8 +866,35 @@ public class MessageCompose extends K9Activity implements OnClickListener,
}
initializeCrypto();
final CryptoProvider crypto = mAccount.getCryptoProvider();
if (crypto.isAvailable(this)) {
mOpenPgpProvider = mAccount.getOpenPgpProvider();
if (mOpenPgpProvider != null) {
// New OpenPGP Provider API
// bind to service
mOpenPgpServiceConnection = new OpenPgpServiceConnection(this, mOpenPgpProvider);
mOpenPgpServiceConnection.bindToService();
mEncryptLayout.setVisibility(View.VISIBLE);
mCryptoSignatureCheckbox.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
CheckBox checkBox = (CheckBox) v;
if (checkBox.isChecked()) {
mPreventDraftSaving = true;
}
}
});
if (mAccount.getCryptoAutoSignature()) {
// TODO: currently disabled for new openpgp providers (see AccountSettings)
}
updateMessageFormat();
// TODO: currently disabled for new openpgp providers (see AccountSettings)
mAutoEncrypt = false;
//mAutoEncrypt = mAccount.isCryptoAutoEncrypt();
} else if (crypto.isAvailable(this)) {
mEncryptLayout.setVisibility(View.VISIBLE);
mCryptoSignatureCheckbox.setOnClickListener(new OnClickListener() {
@Override
@ -894,6 +944,15 @@ public class MessageCompose extends K9Activity implements OnClickListener,
setTitle();
}
@Override
public void onDestroy() {
super.onDestroy();
if (mOpenPgpServiceConnection != null) {
mOpenPgpServiceConnection.unbindFromService();
}
}
/**
* Handle external intents that trigger the message compose activity.
@ -1849,36 +1908,66 @@ public class MessageCompose extends K9Activity implements OnClickListener,
private void performSend() {
final CryptoProvider crypto = mAccount.getCryptoProvider();
if (mEncryptCheckbox.isChecked() && !mPgpData.hasEncryptionKeys()) {
// key selection before encryption
StringBuilder emails = new StringBuilder();
for (Address address : getRecipientAddresses()) {
if (mOpenPgpProvider != null) {
// OpenPGP Provider API
// If not already encrypted but user wants to encrypt...
if (mPgpData.getEncryptedData() == null &&
(mEncryptCheckbox.isChecked() || mCryptoSignatureCheckbox.isChecked())) {
String[] emailsArray = null;
if (mEncryptCheckbox.isChecked()) {
// get emails as array
ArrayList<String> emails = new ArrayList<String>();
for (Address address : getRecipientAddresses()) {
emails.add(address.getAddress());
}
emailsArray = emails.toArray(new String[emails.size()]);
}
if (mEncryptCheckbox.isChecked() && mCryptoSignatureCheckbox.isChecked()) {
Intent intent = new Intent(OpenPgpApi.ACTION_SIGN_AND_ENCTYPT);
intent.putExtra(OpenPgpApi.EXTRA_USER_IDS, emailsArray);
executeOpenPgpMethod(intent);
} else if (mCryptoSignatureCheckbox.isChecked()) {
String text = buildText(false).getText();
Intent intent = new Intent(OpenPgpApi.ACTION_SIGN);
executeOpenPgpMethod(intent);
} else if (mEncryptCheckbox.isChecked()) {
Intent intent = new Intent(OpenPgpApi.ACTION_ENCRYPT);
intent.putExtra(OpenPgpApi.EXTRA_USER_IDS, emailsArray);
executeOpenPgpMethod(intent);
}
// onSend() is called again in SignEncryptCallback and with
// encryptedData set in pgpData!
return;
}
} else if (crypto.isAvailable(this)) {
// Legacy APG API
if (mEncryptCheckbox.isChecked() && !mPgpData.hasEncryptionKeys()) {
// key selection before encryption
StringBuilder emails = new StringBuilder();
for (Address address : getRecipientAddresses()) {
if (emails.length() != 0) {
emails.append(',');
}
emails.append(address.getAddress());
if (!mContinueWithoutPublicKey &&
!crypto.hasPublicKeyForEmail(this, address.getAddress())) {
showDialog(DIALOG_CONTINUE_WITHOUT_PUBLIC_KEY);
return;
}
}
if (emails.length() != 0) {
emails.append(',');
}
emails.append(address.getAddress());
if (!mContinueWithoutPublicKey &&
!crypto.hasPublicKeyForEmail(this, address.getAddress())) {
showDialog(DIALOG_CONTINUE_WITHOUT_PUBLIC_KEY);
return;
}
}
if (emails.length() != 0) {
emails.append(',');
}
emails.append(mIdentity.getEmail());
emails.append(mIdentity.getEmail());
mPreventDraftSaving = true;
if (!crypto.selectEncryptionKeys(MessageCompose.this, emails.toString(), mPgpData)) {
mPreventDraftSaving = false;
}
return;
}
if (mPgpData.hasEncryptionKeys() || mPgpData.hasSignatureKey()) {
if (mPgpData.getEncryptedData() == null) {
String text = buildText(false).getText();
mPreventDraftSaving = true;
if (!crypto.encrypt(this, text, mPgpData)) {
if (!crypto.selectEncryptionKeys(MessageCompose.this, emails.toString(), mPgpData)) {
mPreventDraftSaving = false;
}
return;
@ -1899,6 +1988,95 @@ public class MessageCompose extends K9Activity implements OnClickListener,
mDraftNeedsSaving = false;
finish();
}
private InputStream getOpenPgpInputStream() {
String text = buildText(false).getText();
InputStream is = null;
try {
is = new ByteArrayInputStream(text.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
Log.e(K9.LOG_TAG, "UnsupportedEncodingException.", e);
}
return is;
}
private void executeOpenPgpMethod(Intent intent) {
intent.putExtra(OpenPgpApi.EXTRA_REQUEST_ASCII_ARMOR, true);
final InputStream is = getOpenPgpInputStream();
final ByteArrayOutputStream os = new ByteArrayOutputStream();
SignEncryptCallback callback = new SignEncryptCallback(os, REQUEST_CODE_SIGN_ENCRYPT);
OpenPgpApi api = new OpenPgpApi(this, mOpenPgpServiceConnection.getService());
api.executeApiAsync(intent, is, os, callback);
}
/**
* Called on successful encrypt/verify
*/
private class SignEncryptCallback implements OpenPgpApi.IOpenPgpCallback {
ByteArrayOutputStream os;
int requestCode;
private SignEncryptCallback(ByteArrayOutputStream os, int requestCode) {
this.os = os;
this.requestCode = requestCode;
}
@Override
public void onReturn(Intent result) {
switch (result.getIntExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_ERROR)) {
case OpenPgpApi.RESULT_CODE_SUCCESS: {
try {
final String output = os.toString("UTF-8");
if (K9.DEBUG)
Log.d(OpenPgpApi.TAG, "result: " + os.toByteArray().length
+ " str=" + output);
mPgpData.setEncryptedData(output);
onSend();
} catch (UnsupportedEncodingException e) {
Log.e(K9.LOG_TAG, "UnsupportedEncodingException", e);
}
break;
}
case OpenPgpApi.RESULT_CODE_USER_INTERACTION_REQUIRED: {
PendingIntent pi = result.getParcelableExtra(OpenPgpApi.RESULT_INTENT);
try {
startIntentSenderForResult(pi.getIntentSender(),
requestCode, null, 0, 0, 0);
} catch (SendIntentException e) {
Log.e(K9.LOG_TAG, "SendIntentException", e);
}
break;
}
case OpenPgpApi.RESULT_CODE_ERROR: {
OpenPgpError error = result.getParcelableExtra(OpenPgpApi.RESULT_ERRORS);
handleOpenPgpErrors(error);
break;
}
}
}
}
private void handleOpenPgpErrors(final OpenPgpError error) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Log.e(K9.LOG_TAG, "OpenPGP Error ID:" + error.getErrorId());
Log.e(K9.LOG_TAG, "OpenPGP Error Message:" + error.getMessage());
Toast.makeText(MessageCompose.this,
getString(R.string.openpgp_error) + " " + error.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
private void onDiscard() {
if (mDraftId != INVALID_DRAFT_ID) {
@ -1984,7 +2162,7 @@ public class MessageCompose extends K9Activity implements OnClickListener,
* The MIME type we want our attachment to have.
*/
private void onAddAttachment2(final String mime_type) {
if (mAccount.getCryptoProvider().isAvailable(this)) {
if (mAccount.getCryptoProvider().isAvailable(this) || mAccount.getOpenPgpProvider() != null) {
Toast.makeText(this, R.string.attachment_encryption_unsupported, Toast.LENGTH_LONG).show();
}
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
@ -2169,6 +2347,19 @@ public class MessageCompose extends K9Activity implements OnClickListener,
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// if a CryptoSystem activity is returning, then mPreventDraftSaving was set to true
mPreventDraftSaving = false;
// OpenPGP: try again after user interaction
if (resultCode == RESULT_OK && requestCode == REQUEST_CODE_SIGN_ENCRYPT) {
/*
* The data originally given to the pgp method are are again
* returned here to be used when calling again after user
* interaction. They also contain results from the user interaction
* which happened, for example selected key ids.
*/
executeOpenPgpMethod(data);
return;
}
if (mAccount.getCryptoProvider().onActivityResult(this, requestCode, resultCode, data, mPgpData)) {
return;

View File

@ -51,7 +51,9 @@ import com.fsck.k9.search.SearchSpecification.Attribute;
import com.fsck.k9.search.SearchSpecification.Searchfield;
import com.fsck.k9.search.SearchSpecification.SearchCondition;
import com.fsck.k9.view.MessageHeader;
import com.fsck.k9.view.MessageOpenPgpView;
import com.fsck.k9.view.MessageTitleView;
import com.fsck.k9.view.SingleMessageView;
import com.fsck.k9.view.ViewSwitcher;
import com.fsck.k9.view.ViewSwitcher.OnSwitchCompleteListener;
@ -1568,4 +1570,19 @@ public class MessageList extends K9FragmentActivity implements MessageListFragme
removeMessageViewFragment();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// TODO: ugly pass-through! Can not be handled in fragment, because startIntentSenderForResult()
// does not support fragments!
// handle OpenPGP results from PendingIntents in OpenPGP view
MessageOpenPgpView mOpenPgpView = (MessageOpenPgpView) findViewById(R.id.layout_decrypt_openpgp);
if (mOpenPgpView != null && mOpenPgpView.handleOnActivityResult(requestCode, resultCode, data)) {
return;
}
}
}

View File

@ -2,11 +2,15 @@
package com.fsck.k9.activity.setup;
import android.app.Dialog;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.openintents.openpgp.util.OpenPgpListPreference;
import org.openintents.openpgp.util.OpenPgpUtils;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
@ -171,7 +175,7 @@ public class AccountSettings extends K9PreferenceActivity {
private ListPreference mIdleRefreshPeriod;
private ListPreference mMaxPushFolders;
private boolean mHasCrypto = false;
private ListPreference mCryptoApp;
private OpenPgpListPreference mCryptoApp;
private CheckBoxPreference mCryptoAutoSignature;
private CheckBoxPreference mCryptoAutoEncrypt;
@ -689,16 +693,21 @@ public class AccountSettings extends K9PreferenceActivity {
}
});
mHasCrypto = new Apg().isAvailable(this);
mHasCrypto = (new Apg().isAvailable(this) || OpenPgpUtils.isAvailable(this));
if (mHasCrypto) {
mCryptoApp = (ListPreference) findPreference(PREFERENCE_CRYPTO_APP);
mCryptoApp = (OpenPgpListPreference) findPreference(PREFERENCE_CRYPTO_APP);
// add "apg"
if (new Apg().isAvailable(this)) {
mCryptoApp.addLegacyProvider(0, "apg", "APG", null);
}
mCryptoApp.setValue(String.valueOf(mAccount.getCryptoApp()));
mCryptoApp.setSummary(mCryptoApp.getEntry());
mCryptoApp.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
String value = newValue.toString();
int index = mCryptoApp.findIndexOfValue(value);
mCryptoApp.setSummary(mCryptoApp.getEntries()[index]);
mCryptoApp.setSummary(mCryptoApp.getEntryByValue(value));
mCryptoApp.setValue(value);
handleCryptoAppDependencies();
if (Apg.NAME.equals(value)) {
@ -743,12 +752,12 @@ public class AccountSettings extends K9PreferenceActivity {
}
private void handleCryptoAppDependencies() {
if ("".equals(mCryptoApp.getValue())) {
mCryptoAutoSignature.setEnabled(false);
mCryptoAutoEncrypt.setEnabled(false);
} else {
if ("apg".equals(mCryptoApp.getValue())) {
mCryptoAutoSignature.setEnabled(true);
mCryptoAutoEncrypt.setEnabled(true);
} else {
mCryptoAutoSignature.setEnabled(false);
mCryptoAutoEncrypt.setEnabled(false);
}
}

View File

@ -0,0 +1,77 @@
package com.fsck.k9.crypto;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.fsck.k9.mail.Message;
import com.fsck.k9.mail.MessagingException;
import com.fsck.k9.mail.Part;
import com.fsck.k9.mail.internet.MimeUtility;
public class CryptoHelper {
public static Pattern PGP_MESSAGE =
Pattern.compile(".*?(-----BEGIN PGP MESSAGE-----.*?-----END PGP MESSAGE-----).*",
Pattern.DOTALL);
public static Pattern PGP_SIGNED_MESSAGE =
Pattern.compile(
".*?(-----BEGIN PGP SIGNED MESSAGE-----.*?-----BEGIN PGP SIGNATURE-----.*?-----END PGP SIGNATURE-----).*",
Pattern.DOTALL);
public CryptoHelper() {
super();
}
/**
* TODO: use new parseMessage() from PgpUtils to actually parse!
* @param message
* @return
*/
public boolean isEncrypted(Message message) {
String data = null;
try {
Part part = MimeUtility.findFirstPartByMimeType(message, "text/plain");
if (part == null) {
part = MimeUtility.findFirstPartByMimeType(message, "text/html");
}
if (part != null) {
data = MimeUtility.getTextFromPart(part);
}
} catch (MessagingException e) {
// guess not...
// TODO: maybe log this?
}
if (data == null) {
return false;
}
Matcher matcher = PGP_MESSAGE.matcher(data);
return matcher.matches();
}
public boolean isSigned(Message message) {
String data = null;
try {
Part part = MimeUtility.findFirstPartByMimeType(message, "text/plain");
if (part == null) {
part = MimeUtility.findFirstPartByMimeType(message, "text/html");
}
if (part != null) {
data = MimeUtility.getTextFromPart(part);
}
} catch (MessagingException e) {
// guess not...
// TODO: maybe log this?
}
if (data == null) {
return false;
}
Matcher matcher = PGP_SIGNED_MESSAGE.matcher(data);
return matcher.matches();
}
}

View File

@ -2,6 +2,8 @@ package com.fsck.k9.crypto;
import java.io.Serializable;
import org.openintents.openpgp.OpenPgpSignatureResult;
public class PgpData implements Serializable {
private static final long serialVersionUID = 6314045536470848410L;
protected long mEncryptionKeyIds[] = null;
@ -11,6 +13,17 @@ public class PgpData implements Serializable {
protected boolean mSignatureUnknown = false;
protected String mDecryptedData = null;
protected String mEncryptedData = null;
// new API
protected OpenPgpSignatureResult mSignatureResult;
public OpenPgpSignatureResult getSignatureResult() {
return mSignatureResult;
}
public void setSignatureResult(OpenPgpSignatureResult signatureResult) {
this.mSignatureResult = signatureResult;
}
public void setSignatureKeyId(long keyId) {
mSignatureKeyId = keyId;

View File

@ -3,6 +3,8 @@ package com.fsck.k9.fragment;
import java.io.File;
import java.util.Collections;
import org.openintents.openpgp.OpenPgpSignatureResult;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
@ -713,6 +715,21 @@ public class MessageViewFragment extends SherlockFragment implements OnClickList
});
}
}
/**
* Used by MessageOpenPgpView
*/
public void setMessageWithOpenPgp(String decryptedData, OpenPgpSignatureResult signatureResult) {
try {
// TODO: get rid of PgpData?
PgpData data = new PgpData();
data.setDecryptedData(decryptedData);
data.setSignatureResult(signatureResult);
mMessageView.setMessage(mAccount, (LocalMessage) mMessage, data, mController, mListener);
} catch (MessagingException e) {
Log.e(K9.LOG_TAG, "displayMessageBody failed", e);
}
}
// This REALLY should be in MessageCryptoView
@Override

View File

@ -0,0 +1,398 @@
package com.fsck.k9.view;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import org.openintents.openpgp.OpenPgpError;
import org.openintents.openpgp.OpenPgpSignatureResult;
import org.openintents.openpgp.util.OpenPgpApi;
import org.openintents.openpgp.util.OpenPgpServiceConnection;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.support.v4.app.Fragment;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.fsck.k9.K9;
import com.fsck.k9.R;
import com.fsck.k9.crypto.CryptoHelper;
import com.fsck.k9.fragment.MessageViewFragment;
import com.fsck.k9.mail.Message;
import com.fsck.k9.mail.MessagingException;
import com.fsck.k9.mail.Part;
import com.fsck.k9.mail.internet.MimeUtility;
public class MessageOpenPgpView extends LinearLayout {
private Context mContext;
private MessageViewFragment mFragment;
private RelativeLayout mSignatureLayout = null;
private ImageView mSignatureStatusImage = null;
private TextView mSignatureUserId = null;
private TextView mText = null;
private ProgressBar mProgress;
private Button mGetKeyButton;
private OpenPgpServiceConnection mOpenPgpServiceConnection;
private OpenPgpApi mOpenPgpApi;
private String mOpenPgpProvider;
private String mDecryptedData;
private Message mMessage;
private PendingIntent mMissingKeyPI;
private static final int REQUEST_CODE_DECRYPT_VERIFY = 12;
String mData;
public MessageOpenPgpView(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
}
public void setupChildViews() {
mSignatureLayout = (RelativeLayout) findViewById(R.id.openpgp_signature_layout);
mSignatureStatusImage = (ImageView) findViewById(R.id.openpgp_signature_status);
mSignatureUserId = (TextView) findViewById(R.id.openpgp_user_id);
mText = (TextView) findViewById(R.id.openpgp_text);
mProgress = (ProgressBar) findViewById(R.id.openpgp_progress);
mGetKeyButton = (Button) findViewById(R.id.openpgp_get_key);
mGetKeyButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
getMissingKey();
}
});
}
public void setFragment(Fragment fragment) {
mFragment = (MessageViewFragment) fragment;
}
/**
* Fill the decrypt layout with signature data, if known, make controls
* visible, if they should be visible.
*/
public void updateLayout(String openPgpProvider, String decryptedData,
final OpenPgpSignatureResult signatureResult,
final Message message) {
// set class variables
mOpenPgpProvider = openPgpProvider;
mDecryptedData = decryptedData;
mMessage = message;
// only use this view if a OpenPGP Provider is set
if (mOpenPgpProvider == null) {
return;
}
// bind to service
mOpenPgpServiceConnection = new OpenPgpServiceConnection(mFragment.getActivity(),
mOpenPgpProvider);
mOpenPgpServiceConnection.bindToService();
if ((message == null) && (decryptedData == null)) {
this.setVisibility(View.GONE);
// don't process further
return;
}
if (decryptedData != null && signatureResult == null) {
// only decrypt
MessageOpenPgpView.this.setBackgroundColor(mFragment.getResources().getColor(
R.color.openpgp_blue));
mText.setText(R.string.openpgp_successful_decryption);
// don't process further
return;
} else if (signatureResult != null && decryptedData != null) {
// decryptAndVerify / only verify
switch (signatureResult.getStatus()) {
case OpenPgpSignatureResult.SIGNATURE_ERROR:
// TODO: signature error but decryption works?
mText.setText(R.string.openpgp_signature_invalid);
MessageOpenPgpView.this.setBackgroundColor(mFragment.getResources().getColor(
R.color.openpgp_red));
// mSignatureStatusImage.setImageResource(R.drawable.overlay_error);
mSignatureLayout.setVisibility(View.GONE);
break;
case OpenPgpSignatureResult.SIGNATURE_SUCCESS_CERTIFIED:
if (signatureResult.isSignatureOnly()) {
mText.setText(R.string.openpgp_signature_valid);
}
else {
mText.setText(R.string.openpgp_successful_decryption_valid_signature);
}
MessageOpenPgpView.this.setBackgroundColor(mFragment.getResources().getColor(
R.color.openpgp_green));
mSignatureUserId.setText(signatureResult.getUserId());
mSignatureStatusImage.setImageResource(R.drawable.overlay_ok);
mSignatureLayout.setVisibility(View.VISIBLE);
break;
case OpenPgpSignatureResult.SIGNATURE_UNKNOWN_PUB_KEY:
if (signatureResult.isSignatureOnly()) {
mText.setText(R.string.openpgp_signature_unknown_text);
}
else {
mText.setText(R.string.openpgp_successful_decryption_unknown_signature);
}
mGetKeyButton.setVisibility(View.VISIBLE);
MessageOpenPgpView.this.setBackgroundColor(mFragment.getResources().getColor(
R.color.openpgp_orange));
mSignatureUserId.setText(R.string.openpgp_signature_unknown);
mSignatureStatusImage.setImageResource(R.drawable.overlay_error);
mSignatureLayout.setVisibility(View.VISIBLE);
break;
default:
break;
}
// don't process further
return;
}
// Start new decryption/verification
CryptoHelper helper = new CryptoHelper();
if (helper.isEncrypted(message) || helper.isSigned(message)) {
// start automatic decrypt
decryptAndVerify(message);
} else {
try {
// check for PGP/MIME encryption
Part pgp = MimeUtility
.findFirstPartByMimeType(message, "application/pgp-encrypted");
if (pgp != null) {
Toast.makeText(mContext, R.string.pgp_mime_unsupported, Toast.LENGTH_LONG)
.show();
}
} catch (MessagingException e) {
// nothing to do...
}
}
}
private void decryptAndVerify(final Message message) {
this.setVisibility(View.VISIBLE);
mProgress.setVisibility(View.VISIBLE);
MessageOpenPgpView.this.setBackgroundColor(mFragment.getResources().getColor(
R.color.openpgp_orange));
mText.setText(R.string.openpgp_decrypting_verifying);
// waiting in a new thread
Runnable r = new Runnable() {
@Override
public void run() {
try {
// get data String
Part part = MimeUtility.findFirstPartByMimeType(message, "text/plain");
if (part == null) {
part = MimeUtility.findFirstPartByMimeType(message, "text/html");
}
if (part != null) {
mData = MimeUtility.getTextFromPart(part);
}
// wait for service to be bound
while (!mOpenPgpServiceConnection.isBound()) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
}
mOpenPgpApi = new OpenPgpApi(getContext(),
mOpenPgpServiceConnection.getService());
decryptVerify(new Intent());
} catch (MessagingException me) {
Log.e(K9.LOG_TAG, "Unable to decrypt email.", me);
}
}
};
new Thread(r).start();
}
private void decryptVerify(Intent intent) {
intent.setAction(OpenPgpApi.ACTION_DECRYPT_VERIFY);
intent.putExtra(OpenPgpApi.EXTRA_REQUEST_ASCII_ARMOR, true);
InputStream is = null;
try {
is = new ByteArrayInputStream(mData.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
Log.e(K9.LOG_TAG, "UnsupportedEncodingException.", e);
}
final ByteArrayOutputStream os = new ByteArrayOutputStream();
DecryptVerifyCallback callback = new DecryptVerifyCallback(os, REQUEST_CODE_DECRYPT_VERIFY);
mOpenPgpApi.executeApiAsync(intent, is, os, callback);
}
private void getMissingKey() {
try {
mFragment.getActivity().startIntentSenderForResult(
mMissingKeyPI.getIntentSender(),
REQUEST_CODE_DECRYPT_VERIFY, null, 0, 0, 0);
} catch (SendIntentException e) {
Log.e(K9.LOG_TAG, "SendIntentException", e);
}
}
/**
* Called on successful decrypt/verification
*/
private class DecryptVerifyCallback implements OpenPgpApi.IOpenPgpCallback {
ByteArrayOutputStream os;
int requestCode;
private DecryptVerifyCallback(ByteArrayOutputStream os, int requestCode) {
this.os = os;
this.requestCode = requestCode;
}
@Override
public void onReturn(Intent result) {
switch (result.getIntExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_ERROR)) {
case OpenPgpApi.RESULT_CODE_SUCCESS: {
try {
final String output = os.toString("UTF-8");
OpenPgpSignatureResult sigResult = null;
if (result.hasExtra(OpenPgpApi.RESULT_SIGNATURE)) {
sigResult = result.getParcelableExtra(OpenPgpApi.RESULT_SIGNATURE);
}
if (K9.DEBUG)
Log.d(OpenPgpApi.TAG, "result: " + os.toByteArray().length
+ " str=" + output);
// missing key -> PendingIntent to get keys
mMissingKeyPI = result.getParcelableExtra(OpenPgpApi.RESULT_INTENT);
mProgress.setVisibility(View.GONE);
mFragment.setMessageWithOpenPgp(output, sigResult);
} catch (UnsupportedEncodingException e) {
Log.e(K9.LOG_TAG, "UnsupportedEncodingException", e);
}
break;
}
case OpenPgpApi.RESULT_CODE_USER_INTERACTION_REQUIRED: {
PendingIntent pi = result.getParcelableExtra(OpenPgpApi.RESULT_INTENT);
try {
mFragment.getActivity().startIntentSenderForResult(
pi.getIntentSender(),
requestCode, null, 0, 0, 0);
} catch (SendIntentException e) {
Log.e(K9.LOG_TAG, "SendIntentException", e);
}
break;
}
case OpenPgpApi.RESULT_CODE_ERROR: {
OpenPgpError error = result.getParcelableExtra(OpenPgpApi.RESULT_ERRORS);
handleError(error, true);
break;
}
}
}
}
public boolean handleOnActivityResult(int requestCode, int resultCode, Intent data) {
if (K9.DEBUG)
Log.d(K9.LOG_TAG, "onActivityResult resultCode: " + resultCode);
// try again after user interaction
if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_CODE_DECRYPT_VERIFY) {
/*
* The data originally given to the pgp method are are again
* returned here to be used when calling again after user
* interaction. They also contain results from the user interaction
* which happened, for example selected key ids.
*/
decryptVerify(data);
return true;
}
return false;
}
private void handleError(final OpenPgpError error, final boolean changeColor) {
mFragment.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
mProgress.setVisibility(View.GONE);
if (K9.DEBUG) {
Log.d(K9.LOG_TAG, "handleError getErrorId:" + error.getErrorId());
Log.d(K9.LOG_TAG, "handleError getMessage:" + error.getMessage());
}
// TODO: better error handling with ids?
mText.setText(mFragment.getString(R.string.openpgp_error) + " "
+ error.getMessage());
if (changeColor)
MessageOpenPgpView.this.setBackgroundColor(mFragment.getResources().getColor(
R.color.openpgp_red));
}
});
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
// bind to service if a OpenPGP Provider is available
if (mOpenPgpProvider != null) {
mOpenPgpServiceConnection = new OpenPgpServiceConnection(mFragment.getActivity(),
mOpenPgpProvider);
mOpenPgpServiceConnection.bindToService();
}
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
if (mOpenPgpServiceConnection != null) {
mOpenPgpServiceConnection.unbindFromService();
}
}
}

View File

@ -87,6 +87,7 @@ public class SingleMessageView extends LinearLayout implements OnClickListener,
private boolean mScreenReaderEnabled;
private MessageCryptoView mCryptoView;
private MessageOpenPgpView mOpenPgpView;
private MessageWebView mMessageContentView;
private AccessibleWebView mAccessibleMessageContentView;
private MessageHeader mHeaderContainer;
@ -128,6 +129,9 @@ public class SingleMessageView extends LinearLayout implements OnClickListener,
mCryptoView = (MessageCryptoView) findViewById(R.id.layout_decrypt);
mCryptoView.setFragment(fragment);
mCryptoView.setupChildViews();
mOpenPgpView = (MessageOpenPgpView) findViewById(R.id.layout_decrypt_openpgp);
mOpenPgpView.setFragment(fragment);
mOpenPgpView.setupChildViews();
mShowPicturesAction = findViewById(R.id.show_pictures);
mShowMessageAction = findViewById(R.id.show_message);
@ -545,7 +549,7 @@ public class SingleMessageView extends LinearLayout implements OnClickListener,
public boolean additionalHeadersVisible() {
return mHeaderContainer.additionalHeadersVisible();
}
public void setMessage(Account account, LocalMessage message, PgpData pgpData,
MessagingController controller, MessagingListener listener) throws MessagingException {
resetView();
@ -616,6 +620,8 @@ public class SingleMessageView extends LinearLayout implements OnClickListener,
if (text != null) {
loadBodyFromText(text);
updateCryptoLayout(account.getCryptoProvider(), pgpData, message);
mOpenPgpView.updateLayout(account.getOpenPgpProvider(),pgpData.getDecryptedData(),
pgpData.getSignatureResult(), message);
} else {
showStatusMessage(getContext().getString(R.string.webview_empty_message));
}