aboutsummaryrefslogtreecommitdiffstats
path: root/src/org/apg/ui/SignKeyActivity.java
blob: ab145c921d60a46ff80301d69c37dda2c10d0453 (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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
package org.apg.ui;

import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SignatureException;
import java.util.Iterator;

import org.apg.Apg;
import org.apg.Constants;
import org.apg.HkpKeyServer;
import org.apg.Id;
import org.apg.Constants.extras;
import org.apg.Id.dialog;
import org.apg.Id.message;
import org.apg.Id.request;
import org.apg.Id.return_value;
import org.spongycastle.jce.provider.BouncyCastleProvider;
import org.spongycastle.openpgp.PGPException;
import org.spongycastle.openpgp.PGPPrivateKey;
import org.spongycastle.openpgp.PGPPublicKey;
import org.spongycastle.openpgp.PGPPublicKeyRing;
import org.spongycastle.openpgp.PGPSecretKey;
import org.spongycastle.openpgp.PGPSignature;
import org.spongycastle.openpgp.PGPSignatureGenerator;
import org.spongycastle.openpgp.PGPSignatureSubpacketGenerator;
import org.spongycastle.openpgp.PGPSignatureSubpacketVector;
import org.spongycastle.openpgp.PGPUtil;
import org.apg.R;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Spinner;
import android.widget.Toast;

/**
 * gpg --sign-key
 * 
 * signs the specified public key with the specified secret master key
 */
public class SignKeyActivity extends BaseActivity {
    private static final String TAG = "SignKeyActivity";

    private long pubKeyId = 0;
    private long masterKeyId = 0;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // check we havent already signed it
        setContentView(R.layout.sign_key_layout);

        final Spinner keyServer = (Spinner) findViewById(R.id.keyServer);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, mPreferences.getKeyServers());
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        keyServer.setAdapter(adapter);

        final CheckBox sendKey = (CheckBox) findViewById(R.id.sendKey);
        if (!sendKey.isChecked()) {
            keyServer.setEnabled(false);
        } else {
            keyServer.setEnabled(true);
        }

        sendKey.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (!isChecked) {
                    keyServer.setEnabled(false);
                } else {
                    keyServer.setEnabled(true);
                }
            }
        });

        Button sign = (Button) findViewById(R.id.sign);
        sign.setEnabled(false); // disabled until the user selects a key to sign with
        sign.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (pubKeyId != 0) {
                    initiateSigning();
                }
            }
        });
        
        pubKeyId = getIntent().getLongExtra(Apg.EXTRA_KEY_ID, 0);
        if (pubKeyId == 0) {
            finish(); // nothing to do if we dont know what key to sign
        } else {
            // kick off the SecretKey selection activity so the user chooses which key to sign with first
            Intent intent = new Intent(this, SelectSecretKeyListActivity.class);
            startActivityForResult(intent, Id.request.secret_keys);
        }
    }

    /**
     * handles the UI bits of the signing process on the UI thread
     */
    private void initiateSigning() {
        PGPPublicKeyRing pubring = Apg.getPublicKeyRing(pubKeyId);
        if (pubring != null) {
            // if we have already signed this key, dont bother doing it again
            boolean alreadySigned = false;
    
            @SuppressWarnings("unchecked")
            Iterator<PGPSignature> itr = pubring.getPublicKey(pubKeyId).getSignatures();
            while (itr.hasNext()) {
                PGPSignature sig = itr.next();
                if (sig.getKeyID() == masterKeyId) {
                    alreadySigned = true;
                    break;
                }
            }
    
            if (!alreadySigned) {
                /*
                 * get the user's passphrase for this key (if required)
                 */
                String passphrase = Apg.getCachedPassPhrase(masterKeyId);
                if (passphrase == null) {
                    showDialog(Id.dialog.pass_phrase);
                    return; // bail out; need to wait until the user has entered the passphrase before trying again
                } else {
                    startSigning();
                }
            } else {
                final Bundle status = new Bundle();
                Message msg = new Message();

                status.putString(Apg.EXTRA_ERROR, "Key has already been signed");

                status.putInt(Constants.extras.STATUS, Id.message.done);
                
                msg.setData(status);
                sendMessage(msg);
                
                setResult(Id.return_value.error);
                finish();
            }
        }
    }
    
    @Override
    public long getSecretKeyId() {
        return masterKeyId;
    }
    
    @Override
    public void passPhraseCallback(long keyId, String passPhrase) {
        super.passPhraseCallback(keyId, passPhrase);
        startSigning();
    }
    
    /**
     * kicks off the actual signing process on a background thread
     */
    private void startSigning() {
        showDialog(Id.dialog.signing);
        startThread();
    }
    
    @Override
    public void run() {
        final Bundle status = new Bundle();
        Message msg = new Message();

        try {
            String passphrase = Apg.getCachedPassPhrase(masterKeyId);
            if (passphrase == null || passphrase.length() <= 0) {
                status.putString(Apg.EXTRA_ERROR, "Unable to obtain passphrase");
            } else {
                PGPPublicKeyRing pubring = Apg.getPublicKeyRing(pubKeyId);
                
                /*
                 * sign the incoming key
                 */
                PGPSecretKey secretKey = Apg.getSecretKey(masterKeyId);
                PGPPrivateKey signingKey = secretKey.extractPrivateKey(passphrase.toCharArray(), BouncyCastleProvider.PROVIDER_NAME);
                PGPSignatureGenerator sGen = new PGPSignatureGenerator(secretKey.getPublicKey().getAlgorithm(), PGPUtil.SHA256, BouncyCastleProvider.PROVIDER_NAME);
                sGen.initSign(PGPSignature.DIRECT_KEY, signingKey);
    
                PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator();
    
                PGPSignatureSubpacketVector packetVector = spGen.generate();
                sGen.setHashedSubpackets(packetVector);
    
                PGPPublicKey signedKey = PGPPublicKey.addCertification(pubring.getPublicKey(pubKeyId), sGen.generate());
                pubring = PGPPublicKeyRing.insertPublicKey(pubring, signedKey);
    
                // check if we need to send the key to the server or not
                CheckBox sendKey = (CheckBox) findViewById(R.id.sendKey);
                if (sendKey.isChecked()) {
                    Spinner keyServer = (Spinner) findViewById(R.id.keyServer);
                    HkpKeyServer server = new HkpKeyServer((String) keyServer.getSelectedItem());
    
                    /*
                     * upload the newly signed key to the key server
                     */
    
                    Apg.uploadKeyRingToServer(server, pubring);
                }
    
                // store the signed key in our local cache
                int retval = Apg.storeKeyRingInCache(pubring);
                if (retval != Id.return_value.ok && retval != Id.return_value.updated) {
                    status.putString(Apg.EXTRA_ERROR, "Failed to store signed key in local cache");
                }
            }
        } catch (PGPException e) {
            Log.e(TAG, "Failed to sign key", e);
            status.putString(Apg.EXTRA_ERROR, "Failed to sign key");
            status.putInt(Constants.extras.STATUS, Id.message.done);
            return;
        } catch (NoSuchAlgorithmException e) {
            Log.e(TAG, "Failed to sign key", e);
            status.putString(Apg.EXTRA_ERROR, "Failed to sign key");
            status.putInt(Constants.extras.STATUS, Id.message.done);
            return;
        } catch (NoSuchProviderException e) {
            Log.e(TAG, "Failed to sign key", e);
            status.putString(Apg.EXTRA_ERROR, "Failed to sign key");
            status.putInt(Constants.extras.STATUS, Id.message.done);
            return;
        } catch (SignatureException e) {
            Log.e(TAG, "Failed to sign key", e);
            status.putString(Apg.EXTRA_ERROR, "Failed to sign key");
            status.putInt(Constants.extras.STATUS, Id.message.done);
            return;
        }
        
        status.putInt(Constants.extras.STATUS, Id.message.done);
        
        msg.setData(status);
        sendMessage(msg);
        
        if (status.containsKey(Apg.EXTRA_ERROR)) {
            setResult(Id.return_value.error);
        } else {
            setResult(Id.return_value.ok);
        }
        
        finish();
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case Id.request.secret_keys: {
                if (resultCode == RESULT_OK) {
                    masterKeyId = data.getLongExtra(Apg.EXTRA_KEY_ID, 0);
                    
                    // re-enable the sign button so the user can initiate the sign process
                    Button sign = (Button) findViewById(R.id.sign);
                    sign.setEnabled(true);
                }
                
                break;
            }
            
            default: {
                super.onActivityResult(requestCode, resultCode, data);
            }
        }
    }
    
    @Override
    public void doneCallback(Message msg) {
        super.doneCallback(msg);
        
        removeDialog(Id.dialog.signing);

        Bundle data = msg.getData();
        String error = data.getString(Apg.EXTRA_ERROR);
        if (error != null) {
            Toast.makeText(this, getString(R.string.errorMessage, error), Toast.LENGTH_SHORT).show();
            return;
        }

        Toast.makeText(this, R.string.keySignSuccess, Toast.LENGTH_SHORT).show();
        finish();
    }
}