summaryrefslogtreecommitdiff
path: root/samples/KeyChainDemo/src/com/example/android/keychain/KeyChainDemoActivity.java
blob: a2028b8644a9153c500a27cf645b5b4b0e14904e (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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
/*
 * Copyright 2012 The Android Open Source Project
 *
 * 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 com.example.android.keychain;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.Bundle;
import android.security.KeyChain;
import android.security.KeyChainAliasCallback;
import android.security.KeyChainException;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;

public class KeyChainDemoActivity extends Activity implements
        KeyChainAliasCallback {

    /**
     * The file name of the PKCS12 file used
     */
    public static final String PKCS12_FILENAME = "keychain.p12";

    /**
     * The pass phrase of the PKCS12 file
     */
    public static final String PKCS12_PASSWORD = "changeit";

    /**
     * Intent extra name to indicate to stop server
     */
    public static final String EXTRA_STOP_SERVER = "stop_server";

    // Log tag for this class
    private static final String TAG = "KeyChainApiActivity";

    // Alias for certificate
    private static final String DEFAULT_ALIAS = "My Key Chain";

    // Name of the application preference
    private static final String KEYCHAIN_PREF = "keychain";

    // Name of preference name that saves the alias
    private static final String KEYCHAIN_PREF_ALIAS = "alias";

    // Request code used when starting the activity using the KeyChain install
    // intent
    private static final int INSTALL_KEYCHAIN_CODE = 1;

    // Test SSL URL
    private static final String TEST_SSL_URL = "https://localhost:8080";

    // Button to start/stop the simple SSL web server
    private Button serverButton;

    // Button to install the key chain
    private Button keyChainButton;

    // Button to launch the browser for testing https://localhost:8080
    private Button testSslButton;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Set the view using the main.xml layout
        setContentView(R.layout.main);

        // Check whether the key chain is installed or not. This takes time and
        // should be done in another thread other than the main thread.
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (isKeyChainAccessible()) {
                    // Key chain installed. Disable the install button and print
                    // the key chain information
                    disableKeyChainButton();
                    printInfo();
                } else {
                    Log.d(TAG, "Key Chain is not accessible");
                }
            }
        }).start();

        // Setup the key chain installation button
        keyChainButton = (Button) findViewById(R.id.keychain_button);
        keyChainButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                installPkcs12();
            }
        });

        // Setup the simple SSL web server start/stop button
        serverButton = (Button) findViewById(R.id.server_button);
        serverButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (serverButton.getText().equals(
                        getResources().getString(R.string.server_start))) {
                    serverButton.setText(R.string.server_stop);
                    startServer();
                } else {
                    serverButton.setText(R.string.server_start);
                    stopServer();
                }
            }
        });

        // Setup the test SSL page button
        testSslButton = (Button) findViewById(R.id.test_ssl_button);
        testSslButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(Intent.ACTION_VIEW, Uri
                        .parse(TEST_SSL_URL));
                startActivity(i);
            }
        });
    }

    /**
     * This will be called when the user click on the notification to stop the
     * SSL server
     */
    @Override
    protected void onNewIntent(Intent intent) {
        Log.d(TAG, "In onNewIntent()");
        super.onNewIntent(intent);
        boolean isStopServer = intent.getBooleanExtra(EXTRA_STOP_SERVER, false);
        if (isStopServer) {
            serverButton.setText(R.string.server_start);
            stopServer();
        }
    }

    /**
     * This implements the KeyChainAliasCallback
     */
    @Override
    public void alias(String alias) {
        if (alias != null) {
            setAlias(alias); // Set the alias in the application preference
            disableKeyChainButton();
            printInfo();
        } else {
            Log.d(TAG, "User hit Disallow");
        }
    }

    /**
     * This method returns the alias of the key chain from the application
     * preference
     *
     * @return The alias of the key chain
     */
    private String getAlias() {
        SharedPreferences pref = getSharedPreferences(KEYCHAIN_PREF,
                MODE_PRIVATE);
        return pref.getString(KEYCHAIN_PREF_ALIAS, DEFAULT_ALIAS);
    }

    /**
     * This method sets the alias of the key chain to the application preference
     */
    private void setAlias(String alias) {
        SharedPreferences pref = getSharedPreferences(KEYCHAIN_PREF,
                MODE_PRIVATE);
        Editor editor = pref.edit();
        editor.putString(KEYCHAIN_PREF_ALIAS, alias);
        editor.commit();
    }

    /**
     * This method prints the key chain information.
     */
    private void printInfo() {
        String alias = getAlias();
        X509Certificate[] certs = getCertificateChain(alias);
        final PrivateKey privateKey = getPrivateKey(alias);
        final StringBuffer sb = new StringBuffer();
        for (X509Certificate cert : certs) {
            sb.append(cert.getIssuerDN());
            sb.append("\n");
        }
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                TextView certTv = (TextView) findViewById(R.id.cert);
                TextView privateKeyTv = (TextView) findViewById(R.id.private_key);
                certTv.setText(sb.toString());
                privateKeyTv.setText(privateKey.getFormat() + ":" + privateKey);
            }
        });
    }

    /**
     * This method will launch an intent to install the key chain
     */
    private void installPkcs12() {
        try {
            BufferedInputStream bis = new BufferedInputStream(getAssets().open(
                    PKCS12_FILENAME));
            byte[] keychain = new byte[bis.available()];
            bis.read(keychain);

            Intent installIntent = KeyChain.createInstallIntent();
            installIntent.putExtra(KeyChain.EXTRA_PKCS12, keychain);
            installIntent.putExtra(KeyChain.EXTRA_NAME, DEFAULT_ALIAS);
            startActivityForResult(installIntent, INSTALL_KEYCHAIN_CODE);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == INSTALL_KEYCHAIN_CODE) {
            switch (resultCode) {
                case Activity.RESULT_OK:
                    chooseCert();
                    break;
                default:
                    super.onActivityResult(requestCode, resultCode, data);
            }
        }
    }

    private void chooseCert() {
        KeyChain.choosePrivateKeyAlias(this, this, // Callback
                new String[] {}, // Any key types.
                null, // Any issuers.
                "localhost", // Any host
                -1, // Any port
                DEFAULT_ALIAS);
    }

    private X509Certificate[] getCertificateChain(String alias) {
        try {
            return KeyChain.getCertificateChain(this, alias);
        } catch (KeyChainException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return null;
    }

    private PrivateKey getPrivateKey(String alias) {
        try {
            return KeyChain.getPrivateKey(this, alias);
        } catch (KeyChainException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * This method checks if the key chain is installed
     *
     * @return true if the key chain is not installed or allowed
     */
    private boolean isKeyChainAccessible() {
        return getCertificateChain(getAlias()) != null
                && getPrivateKey(getAlias()) != null;
    }

    /**
     * This method starts the background service of the simple SSL web server
     */
    private void startServer() {
        Intent secureWebServerIntent = new Intent(this,
                SecureWebServerService.class);
        startService(secureWebServerIntent);
    }

    /**
     * This method stops the background service of the simple SSL web server
     */
    private void stopServer() {
        Intent secureWebServerIntent = new Intent(this,
                SecureWebServerService.class);
        stopService(secureWebServerIntent);
    }

    /**
     * This is a convenient method to disable the key chain install button
     */
    private void disableKeyChainButton() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                keyChainButton.setText(R.string.keychain_installed);
                keyChainButton.setEnabled(false);
            }
        });
    }

}