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, 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    public static final String EXTRA_NFC_DECRYPTED_SESSION_KEY = "nfc_decrypted_session_key";
178
179    // GET_KEY
180    public static final String EXTRA_KEY_ID = "key_id";
181    public static final String RESULT_KEY_IDS = "key_ids";
182
183    /* Service Intent returns */
184    public static final String RESULT_CODE = "result_code";
185
186    // get actual error object from RESULT_ERROR
187    public static final int RESULT_CODE_ERROR = 0;
188    // success!
189    public static final int RESULT_CODE_SUCCESS = 1;
190    // get PendingIntent from RESULT_INTENT, start PendingIntent with startIntentSenderForResult,
191    // and execute service method again in onActivityResult
192    public static final int RESULT_CODE_USER_INTERACTION_REQUIRED = 2;
193
194    public static final String RESULT_ERROR = "error";
195    public static final String RESULT_INTENT = "intent";
196
197    // DECRYPT_VERIFY
198    public static final String RESULT_SIGNATURE = "signature";
199    public static final String RESULT_METADATA = "metadata";
200
201    IOpenPgpService mService;
202    Context mContext;
203
204    public OpenPgpApi(Context context, IOpenPgpService service) {
205        this.mContext = context;
206        this.mService = service;
207    }
208
209    public interface IOpenPgpCallback {
210        void onReturn(final Intent result);
211    }
212
213    private class OpenPgpAsyncTask extends AsyncTask<Void, Integer, Intent> {
214        Intent data;
215        InputStream is;
216        OutputStream os;
217        IOpenPgpCallback callback;
218
219        private OpenPgpAsyncTask(Intent data, InputStream is, OutputStream os, IOpenPgpCallback callback) {
220            this.data = data;
221            this.is = is;
222            this.os = os;
223            this.callback = callback;
224        }
225
226        @Override
227        protected Intent doInBackground(Void... unused) {
228            return executeApi(data, is, os);
229        }
230
231        protected void onPostExecute(Intent result) {
232            callback.onReturn(result);
233        }
234
235    }
236
237    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
238    public void executeApiAsync(Intent data, InputStream is, OutputStream os, IOpenPgpCallback callback) {
239        OpenPgpAsyncTask task = new OpenPgpAsyncTask(data, is, os, callback);
240
241        // don't serialize async tasks!
242        // http://commonsware.com/blog/2012/04/20/asynctask-threading-regression-confirmed.html
243        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
244            task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[]) null);
245        } else {
246            task.execute((Void[]) null);
247        }
248    }
249
250    public Intent executeApi(Intent data, InputStream is, OutputStream os) {
251        try {
252            data.putExtra(EXTRA_API_VERSION, OpenPgpApi.API_VERSION);
253
254            Intent result;
255
256            // pipe the input and output
257            ParcelFileDescriptor input = null;
258            if (is != null) {
259                input = ParcelFileDescriptorUtil.pipeFrom(is,
260                        new ParcelFileDescriptorUtil.IThreadListener() {
261
262                            @Override
263                            public void onThreadFinished(Thread thread) {
264                                //Log.d(OpenPgpApi.TAG, "Copy to service finished");
265                            }
266                        }
267                );
268            }
269            ParcelFileDescriptor output = null;
270            if (os != null) {
271                output = ParcelFileDescriptorUtil.pipeTo(os,
272                        new ParcelFileDescriptorUtil.IThreadListener() {
273
274                            @Override
275                            public void onThreadFinished(Thread thread) {
276                                //Log.d(OpenPgpApi.TAG, "Service finished writing!");
277                            }
278                        }
279                );
280            }
281
282            // blocks until result is ready
283            result = mService.execute(data, input, output);
284            // close() is required to halt the TransferThread
285            if (output != null) {
286                output.close();
287            }
288            // TODO: close input?
289
290            // set class loader to current context to allow unparcelling
291            // of OpenPgpError and OpenPgpSignatureResult
292            // http://stackoverflow.com/a/3806769
293            result.setExtrasClassLoader(mContext.getClassLoader());
294
295            return result;
296        } catch (Exception e) {
297            Log.e(OpenPgpApi.TAG, "Exception in executeApi call", e);
298            Intent result = new Intent();
299            result.putExtra(RESULT_CODE, RESULT_CODE_ERROR);
300            result.putExtra(RESULT_ERROR,
301                    new OpenPgpError(OpenPgpError.CLIENT_SIDE_ERROR, e.getMessage()));
302            return result;
303        }
304    }
305
306}