1/*
2 * Copyright (C) 2014 Dominik Schürmann <dominik@dominikschuermann.de>
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package org.openintents.openpgp.util;
18
19import android.annotation.TargetApi;
20import android.content.Context;
21import android.content.Intent;
22import android.os.AsyncTask;
23import android.os.Build;
24import android.os.ParcelFileDescriptor;
25import android.util.Log;
26
27import org.openintents.openpgp.IOpenPgpService;
28import org.openintents.openpgp.OpenPgpError;
29
30import java.io.InputStream;
31import java.io.OutputStream;
32
33public class OpenPgpApi {
34
35 public static final String TAG = "OpenPgp API";
36
37 public static final String SERVICE_INTENT = "org.openintents.openpgp.IOpenPgpService";
38
39 /**
40 * Version history
41 * ---------------
42 * <p/>
43 * 3:
44 * - first public stable version
45 * <p/>
46 * 4:
47 * - No changes to existing methods -> backward compatible
48 * - Introduction of ACTION_DECRYPT_METADATA, RESULT_METADATA, EXTRA_ORIGINAL_FILENAME, and OpenPgpMetadata parcel
49 * - Introduction of internal NFC extras: EXTRA_NFC_SIGNED_HASH, EXTRA_NFC_SIG_CREATION_TIMESTAMP
50 * 5:
51 * - OpenPgpSignatureResult: new SIGNATURE_KEY_REVOKED and SIGNATURE_KEY_EXPIRED
52 */
53 public static final int API_VERSION = 5;
54
55 /**
56 * General extras
57 * --------------
58 *
59 * required extras:
60 * int EXTRA_API_VERSION (always required)
61 *
62 * returned extras:
63 * int RESULT_CODE (RESULT_CODE_ERROR, RESULT_CODE_SUCCESS or RESULT_CODE_USER_INTERACTION_REQUIRED)
64 * OpenPgpError RESULT_ERROR (if RESULT_CODE == RESULT_CODE_ERROR)
65 * PendingIntent RESULT_INTENT (if RESULT_CODE == RESULT_CODE_USER_INTERACTION_REQUIRED)
66 */
67
68 /**
69 * Sign only
70 * <p/>
71 * optional extras:
72 * boolean EXTRA_REQUEST_ASCII_ARMOR (request ascii armor for output)
73 * String EXTRA_PASSPHRASE (key passphrase)
74 */
75 public static final String ACTION_SIGN = "org.openintents.openpgp.action.SIGN";
76
77 /**
78 * Encrypt
79 * <p/>
80 * required extras:
81 * String[] EXTRA_USER_IDS (=emails of recipients, if more than one key has a user_id, a PendingIntent is returned via RESULT_INTENT)
82 * or
83 * long[] EXTRA_KEY_IDS
84 * <p/>
85 * optional extras:
86 * boolean EXTRA_REQUEST_ASCII_ARMOR (request ascii armor for output)
87 * String EXTRA_PASSPHRASE (key passphrase)
88 * String EXTRA_ORIGINAL_FILENAME (original filename to be encrypted as metadata)
89 */
90 public static final String ACTION_ENCRYPT = "org.openintents.openpgp.action.ENCRYPT";
91
92 /**
93 * Sign and encrypt
94 * <p/>
95 * required extras:
96 * String[] EXTRA_USER_IDS (=emails of recipients, if more than one key has a user_id, a PendingIntent is returned via RESULT_INTENT)
97 * or
98 * long[] EXTRA_KEY_IDS
99 * <p/>
100 * optional extras:
101 * boolean EXTRA_REQUEST_ASCII_ARMOR (request ascii armor for output)
102 * String EXTRA_PASSPHRASE (key passphrase)
103 * String EXTRA_ORIGINAL_FILENAME (original filename to be encrypted as metadata)
104 */
105 public static final String ACTION_SIGN_AND_ENCRYPT = "org.openintents.openpgp.action.SIGN_AND_ENCRYPT";
106
107 /**
108 * Decrypts and verifies given input stream. This methods handles encrypted-only, signed-and-encrypted,
109 * and also signed-only input.
110 * <p/>
111 * If OpenPgpSignatureResult.getStatus() == OpenPgpSignatureResult.SIGNATURE_KEY_MISSING
112 * in addition a PendingIntent is returned via RESULT_INTENT to download missing keys.
113 * <p/>
114 * optional extras:
115 * boolean EXTRA_REQUEST_ASCII_ARMOR (request ascii armor for output)
116 * <p/>
117 * returned extras:
118 * OpenPgpSignatureResult RESULT_SIGNATURE
119 * OpenPgpDecryptMetadata RESULT_METADATA
120 */
121 public static final String ACTION_DECRYPT_VERIFY = "org.openintents.openpgp.action.DECRYPT_VERIFY";
122
123 /**
124 * Decrypts the header of an encrypted file to retrieve metadata such as original filename.
125 * <p/>
126 * This does not decrypt the actual content of the file.
127 * <p/>
128 * returned extras:
129 * OpenPgpDecryptMetadata RESULT_METADATA
130 */
131 public static final String ACTION_DECRYPT_METADATA = "org.openintents.openpgp.action.DECRYPT_METADATA";
132
133 /**
134 * Get key ids based on given user ids (=emails)
135 * <p/>
136 * required extras:
137 * String[] EXTRA_USER_IDS
138 * <p/>
139 * returned extras:
140 * long[] RESULT_KEY_IDS
141 */
142 public static final String ACTION_GET_KEY_IDS = "org.openintents.openpgp.action.GET_KEY_IDS";
143
144 /**
145 * This action returns RESULT_CODE_SUCCESS if the OpenPGP Provider already has the key
146 * corresponding to the given key id in its database.
147 * <p/>
148 * It returns RESULT_CODE_USER_INTERACTION_REQUIRED if the Provider does not have the key.
149 * The PendingIntent from RESULT_INTENT can be used to retrieve those from a keyserver.
150 * <p/>
151 * required extras:
152 * long EXTRA_KEY_ID
153 */
154 public static final String ACTION_GET_KEY = "org.openintents.openpgp.action.GET_KEY";
155
156 /* Intent extras */
157 public static final String EXTRA_API_VERSION = "api_version";
158
159 public static final String EXTRA_ACCOUNT_NAME = "account_name";
160
161 // SIGN, ENCRYPT, SIGN_AND_ENCRYPT, DECRYPT_VERIFY
162 // request ASCII Armor for output
163 // OpenPGP Radix-64, 33 percent overhead compared to binary, see http://tools.ietf.org/html/rfc4880#page-53)
164 public static final String EXTRA_REQUEST_ASCII_ARMOR = "ascii_armor";
165
166 // ENCRYPT, SIGN_AND_ENCRYPT
167 public static final String EXTRA_USER_IDS = "user_ids";
168 public static final String EXTRA_KEY_IDS = "key_ids";
169 // optional extras:
170 public static final String EXTRA_PASSPHRASE = "passphrase";
171 public static final String EXTRA_ORIGINAL_FILENAME = "original_filename";
172
173 // internal NFC states
174 public static final String EXTRA_NFC_SIGNED_HASH = "nfc_signed_hash";
175 public static final String EXTRA_NFC_SIG_CREATION_TIMESTAMP = "nfc_sig_creation_timestamp";
176
177 // GET_KEY
178 public static final String EXTRA_KEY_ID = "key_id";
179 public static final String RESULT_KEY_IDS = "key_ids";
180
181 /* Service Intent returns */
182 public static final String RESULT_CODE = "result_code";
183
184 // get actual error object from RESULT_ERROR
185 public static final int RESULT_CODE_ERROR = 0;
186 // success!
187 public static final int RESULT_CODE_SUCCESS = 1;
188 // get PendingIntent from RESULT_INTENT, start PendingIntent with startIntentSenderForResult,
189 // and execute service method again in onActivityResult
190 public static final int RESULT_CODE_USER_INTERACTION_REQUIRED = 2;
191
192 public static final String RESULT_ERROR = "error";
193 public static final String RESULT_INTENT = "intent";
194
195 // DECRYPT_VERIFY
196 public static final String RESULT_SIGNATURE = "signature";
197 public static final String RESULT_METADATA = "metadata";
198
199 IOpenPgpService mService;
200 Context mContext;
201
202 public OpenPgpApi(Context context, IOpenPgpService service) {
203 this.mContext = context;
204 this.mService = service;
205 }
206
207 public interface IOpenPgpCallback {
208 void onReturn(final Intent result);
209 }
210
211 private class OpenPgpAsyncTask extends AsyncTask<Void, Integer, Intent> {
212 Intent data;
213 InputStream is;
214 OutputStream os;
215 IOpenPgpCallback callback;
216
217 private OpenPgpAsyncTask(Intent data, InputStream is, OutputStream os, IOpenPgpCallback callback) {
218 this.data = data;
219 this.is = is;
220 this.os = os;
221 this.callback = callback;
222 }
223
224 @Override
225 protected Intent doInBackground(Void... unused) {
226 return executeApi(data, is, os);
227 }
228
229 protected void onPostExecute(Intent result) {
230 callback.onReturn(result);
231 }
232
233 }
234
235 @TargetApi(Build.VERSION_CODES.HONEYCOMB)
236 public void executeApiAsync(Intent data, InputStream is, OutputStream os, IOpenPgpCallback callback) {
237 OpenPgpAsyncTask task = new OpenPgpAsyncTask(data, is, os, callback);
238
239 // don't serialize async tasks!
240 // http://commonsware.com/blog/2012/04/20/asynctask-threading-regression-confirmed.html
241 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
242 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[]) null);
243 } else {
244 task.execute((Void[]) null);
245 }
246 }
247
248 public Intent executeApi(Intent data, InputStream is, OutputStream os) {
249 try {
250 data.putExtra(EXTRA_API_VERSION, OpenPgpApi.API_VERSION);
251
252 Intent result;
253
254 // pipe the input and output
255 ParcelFileDescriptor input = null;
256 if (is != null) {
257 input = ParcelFileDescriptorUtil.pipeFrom(is,
258 new ParcelFileDescriptorUtil.IThreadListener() {
259
260 @Override
261 public void onThreadFinished(Thread thread) {
262 //Log.d(OpenPgpApi.TAG, "Copy to service finished");
263 }
264 }
265 );
266 }
267 ParcelFileDescriptor output = null;
268 if (os != null) {
269 output = ParcelFileDescriptorUtil.pipeTo(os,
270 new ParcelFileDescriptorUtil.IThreadListener() {
271
272 @Override
273 public void onThreadFinished(Thread thread) {
274 //Log.d(OpenPgpApi.TAG, "Service finished writing!");
275 }
276 }
277 );
278 }
279
280 // blocks until result is ready
281 result = mService.execute(data, input, output);
282 // close() is required to halt the TransferThread
283 if (output != null) {
284 output.close();
285 }
286 // TODO: close input?
287
288 // set class loader to current context to allow unparcelling
289 // of OpenPgpError and OpenPgpSignatureResult
290 // http://stackoverflow.com/a/3806769
291 result.setExtrasClassLoader(mContext.getClassLoader());
292
293 return result;
294 } catch (Exception e) {
295 Log.e(OpenPgpApi.TAG, "Exception in executeApi call", e);
296 Intent result = new Intent();
297 result.putExtra(RESULT_CODE, RESULT_CODE_ERROR);
298 result.putExtra(RESULT_ERROR,
299 new OpenPgpError(OpenPgpError.CLIENT_SIDE_ERROR, e.getMessage()));
300 return result;
301 }
302 }
303
304}