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