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