aboutsummaryrefslogtreecommitdiffstats
path: root/OpenPGP-Keychain-API-Demo/src/org/sufficientlysecure/keychain/demo/CryptoProviderDemoActivity.java
blob: cbd8295785ac12f74135fb9cad0174fea552c165 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
/*
 * Copyright (C) 2013 Dominik Schürmann <dominik@dominikschuermann.de>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.sufficientlysecure.keychain.demo;

import java.util.ArrayList;
import java.util.List;

import org.openintents.crypto.CryptoError;
import org.openintents.crypto.CryptoServiceConnection;
import org.openintents.crypto.CryptoSignatureResult;
import org.openintents.crypto.ICryptoCallback;
import org.openintents.crypto.ICryptoService;
import org.sufficientlysecure.keychain.demo.R;
import org.sufficientlysecure.keychain.integration.Constants;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.RemoteException;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.Scroller;
import android.widget.TextView;

public class CryptoProviderDemoActivity extends Activity {
    Activity mActivity;

    EditText mMessage;
    EditText mCiphertext;
    EditText mEncryptUserIds;

    private CryptoServiceConnection mCryptoServiceConnection;

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.crypto_provider_demo);

        mActivity = this;

        mMessage = (EditText) findViewById(R.id.crypto_provider_demo_message);
        mCiphertext = (EditText) findViewById(R.id.crypto_provider_demo_ciphertext);
        mEncryptUserIds = (EditText) findViewById(R.id.crypto_provider_demo_encrypt_user_id);

        selectCryptoProvider();
    }

    /**
     * Callback from remote crypto service
     */
    final ICryptoCallback.Stub encryptCallback = new ICryptoCallback.Stub() {

        @Override
        public void onSuccess(final byte[] outputBytes, CryptoSignatureResult signatureResult)
                throws RemoteException {
            Log.d(Constants.TAG, "onEncryptSignSuccess");

            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    mCiphertext.setText(new String(outputBytes));

                }
            });
        }

        @Override
        public void onError(CryptoError error) throws RemoteException {
            Log.e(Constants.TAG, "onError getErrorId:" + error.getErrorId());
            Log.e(Constants.TAG, "onError getMessage:" + error.getMessage());
        }

    };

    final ICryptoCallback.Stub decryptCallback = new ICryptoCallback.Stub() {

        @Override
        public void onSuccess(final byte[] outputBytes, final CryptoSignatureResult signatureResult)
                throws RemoteException {
            Log.d(Constants.TAG, "onDecryptVerifySuccess");

            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    mMessage.setText(new String(outputBytes) + "\n\n" + signatureResult.toString());

                }
            });

        }

        @Override
        public void onError(CryptoError error) throws RemoteException {
            Log.e(Constants.TAG, "onError getErrorId:" + error.getErrorId());
            Log.e(Constants.TAG, "onError getMessage:" + error.getMessage());
        }

    };

    public void encryptOnClick(View view) {
        byte[] inputBytes = mMessage.getText().toString().getBytes();

        try {
            mCryptoServiceConnection.getService().encrypt(inputBytes,
                    mEncryptUserIds.getText().toString().split(","), encryptCallback);
        } catch (RemoteException e) {
            Log.e(Constants.TAG, "CryptoProviderDemo", e);
        }
    }

    public void signOnClick(View view) {
        byte[] inputBytes = mMessage.getText().toString().getBytes();

        try {
            mCryptoServiceConnection.getService().sign(inputBytes, encryptCallback);
        } catch (RemoteException e) {
            Log.e(Constants.TAG, "CryptoProviderDemo", e);
        }
    }

    public void encryptAndSignOnClick(View view) {
        byte[] inputBytes = mMessage.getText().toString().getBytes();

        try {
            mCryptoServiceConnection.getService().encryptAndSign(inputBytes,
                    mEncryptUserIds.getText().toString().split(","), encryptCallback);
        } catch (RemoteException e) {
            Log.e(Constants.TAG, "CryptoProviderDemo", e);
        }
    }

    public void decryptOnClick(View view) {
        byte[] inputBytes = mCiphertext.getText().toString().getBytes();

        try {
            mCryptoServiceConnection.getService().decryptAndVerify(inputBytes, decryptCallback);
        } catch (RemoteException e) {
            Log.e(Constants.TAG, "CryptoProviderDemo", e);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        if (mCryptoServiceConnection != null) {
            mCryptoServiceConnection.unbindFromService();
        }
    }

    private static class CryptoProviderElement {
        private String packageName;
        private String simpleName;
        private Drawable icon;

        public CryptoProviderElement(String packageName, String simpleName, Drawable icon) {
            this.packageName = packageName;
            this.simpleName = simpleName;
            this.icon = icon;
        }

        @Override
        public String toString() {
            return simpleName;
        }
    }

    private void selectCryptoProvider() {
        Intent intent = new Intent(ICryptoService.class.getName());

        final ArrayList<CryptoProviderElement> providerList = new ArrayList<CryptoProviderElement>();

        List<ResolveInfo> resInfo = getPackageManager().queryIntentServices(intent, 0);
        if (!resInfo.isEmpty()) {
            for (ResolveInfo resolveInfo : resInfo) {
                if (resolveInfo.serviceInfo == null)
                    continue;

                String packageName = resolveInfo.serviceInfo.packageName;
                String simpleName = String.valueOf(resolveInfo.serviceInfo
                        .loadLabel(getPackageManager()));
                Drawable icon = resolveInfo.serviceInfo.loadIcon(getPackageManager());
                providerList.add(new CryptoProviderElement(packageName, simpleName, icon));
            }

            AlertDialog.Builder alert = new AlertDialog.Builder(this);
            alert.setTitle("Select Crypto Provider!");
            alert.setCancelable(false);

            if (!providerList.isEmpty()) {

                // Init ArrayAdapter with Crypto Providers
                ListAdapter adapter = new ArrayAdapter<CryptoProviderElement>(this,
                        android.R.layout.select_dialog_item, android.R.id.text1, providerList) {
                    public View getView(int position, View convertView, ViewGroup parent) {
                        // User super class to create the View
                        View v = super.getView(position, convertView, parent);
                        TextView tv = (TextView) v.findViewById(android.R.id.text1);

                        // Put the image on the TextView
                        tv.setCompoundDrawablesWithIntrinsicBounds(providerList.get(position).icon,
                                null, null, null);

                        // Add margin between image and text (support various screen densities)
                        int dp5 = (int) (5 * getResources().getDisplayMetrics().density + 0.5f);
                        tv.setCompoundDrawablePadding(dp5);

                        return v;
                    }
                };

                alert.setSingleChoiceItems(adapter, -1, new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int position) {
                        String packageName = providerList.get(position).packageName;

                        // bind to service
                        mCryptoServiceConnection = new CryptoServiceConnection(
                                CryptoProviderDemoActivity.this, packageName);
                        mCryptoServiceConnection.bindToService();

                        dialog.dismiss();
                    }
                });
            } else {
                alert.setMessage("No Crypto Provider installed!");
            }

            alert.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int id) {
                    dialog.cancel();
                    finish();
                }
            });

            AlertDialog ad = alert.create();
            ad.show();
        }
    }
}