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