OpenPgpApi.java

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