blob: e9c24ddc7afb88b73be04595343a4f7da0784186 [file] [log] [blame]
Brian Carlstromb9a07c12011-04-11 09:03:51 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
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 */
16package android.security;
17
Brian Carlstromba1a6672011-05-24 21:54:37 -070018import android.app.Activity;
Brian Carlstrom67c30df2011-06-24 02:13:23 -070019import android.app.PendingIntent;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070020import android.content.ComponentName;
21import android.content.Context;
22import android.content.Intent;
23import android.content.ServiceConnection;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070024import android.os.IBinder;
25import android.os.Looper;
Robin Lee306fe082014-06-19 14:04:24 +000026import android.os.Process;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070027import android.os.RemoteException;
Robin Lee306fe082014-06-19 14:04:24 +000028import android.os.UserHandle;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070029import java.io.ByteArrayInputStream;
Brian Carlstromd7524722011-05-17 16:20:36 -070030import java.io.Closeable;
Kenny Root5423e682011-11-14 08:43:13 -080031import java.security.InvalidKeyException;
Brian Carlstrom93201f52011-06-09 15:05:35 -070032import java.security.Principal;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070033import java.security.PrivateKey;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070034import java.security.cert.Certificate;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070035import java.security.cert.CertificateException;
36import java.security.cert.CertificateFactory;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070037import java.security.cert.X509Certificate;
Brian Carlstromdb93b782011-07-01 00:12:17 -070038import java.util.List;
Kenny Rootb91773b2013-09-05 13:03:16 -070039import java.util.Locale;
Brian Carlstrom8e9929c2011-05-17 00:40:28 -070040import java.util.concurrent.BlockingQueue;
41import java.util.concurrent.LinkedBlockingQueue;
Kenny Root5423e682011-11-14 08:43:13 -080042
Kenny Root12e75222013-04-23 22:34:24 -070043import com.android.org.conscrypt.OpenSSLEngine;
44import com.android.org.conscrypt.TrustedCertificateStore;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070045
46/**
Brian Carlstrom93201f52011-06-09 15:05:35 -070047 * The {@code KeyChain} class provides access to private keys and
48 * their corresponding certificate chains in credential storage.
49 *
50 * <p>Applications accessing the {@code KeyChain} normally go through
51 * these steps:
52 *
53 * <ol>
54 *
55 * <li>Receive a callback from an {@link javax.net.ssl.X509KeyManager
56 * X509KeyManager} that a private key is requested.
57 *
58 * <li>Call {@link #choosePrivateKeyAlias
59 * choosePrivateKeyAlias} to allow the user to select from a
60 * list of currently available private keys and corresponding
61 * certificate chains. The chosen alias will be returned by the
62 * callback {@link KeyChainAliasCallback#alias}, or null if no private
63 * key is available or the user cancels the request.
64 *
65 * <li>Call {@link #getPrivateKey} and {@link #getCertificateChain} to
66 * retrieve the credentials to return to the corresponding {@link
67 * javax.net.ssl.X509KeyManager} callbacks.
68 *
69 * </ol>
70 *
71 * <p>An application may remember the value of a selected alias to
72 * avoid prompting the user with {@link #choosePrivateKeyAlias
73 * choosePrivateKeyAlias} on subsequent connections. If the alias is
74 * no longer valid, null will be returned on lookups using that value
Brian Carlstromca43c452011-06-29 18:53:17 -070075 *
76 * <p>An application can request the installation of private keys and
77 * certificates via the {@code Intent} provided by {@link
78 * #createInstallIntent}. Private keys installed via this {@code
79 * Intent} will be accessible via {@link #choosePrivateKeyAlias} while
80 * Certificate Authority (CA) certificates will be trusted by all
81 * applications through the default {@code X509TrustManager}.
Brian Carlstromb9a07c12011-04-11 09:03:51 -070082 */
Brian Carlstrom93201f52011-06-09 15:05:35 -070083// TODO reference intent for credential installation when public
Brian Carlstromb9a07c12011-04-11 09:03:51 -070084public final class KeyChain {
85
86 private static final String TAG = "KeyChain";
87
88 /**
89 * @hide Also used by KeyChainService implementation
90 */
91 public static final String ACCOUNT_TYPE = "com.android.keychain";
92
93 /**
Kenny Roota3659062014-03-17 16:21:53 -070094 * Package name for KeyChain chooser.
95 */
96 private static final String KEYCHAIN_PACKAGE = "com.android.keychain";
97
98 /**
Brian Carlstroma00a2b32011-06-29 10:42:35 -070099 * Action to bring up the KeyChainActivity
100 */
101 private static final String ACTION_CHOOSER = "com.android.keychain.CHOOSER";
102
103 /**
Kenny Root1a88d832014-02-07 09:12:48 -0800104 * Package name for the Certificate Installer.
105 */
106 private static final String CERT_INSTALLER_PACKAGE = "com.android.certinstaller";
107
108 /**
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700109 * Extra for use with {@link #ACTION_CHOOSER}
Brian Carlstromba1a6672011-05-24 21:54:37 -0700110 * @hide Also used by KeyChainActivity implementation
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700111 */
Brian Carlstromba1a6672011-05-24 21:54:37 -0700112 public static final String EXTRA_RESPONSE = "response";
113
114 /**
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700115 * Extra for use with {@link #ACTION_CHOOSER}
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700116 * @hide Also used by KeyChainActivity implementation
117 */
118 public static final String EXTRA_HOST = "host";
119
120 /**
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700121 * Extra for use with {@link #ACTION_CHOOSER}
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700122 * @hide Also used by KeyChainActivity implementation
123 */
124 public static final String EXTRA_PORT = "port";
125
126 /**
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700127 * Extra for use with {@link #ACTION_CHOOSER}
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700128 * @hide Also used by KeyChainActivity implementation
129 */
Robin Lee3798ed52015-02-03 17:55:31 +0000130 public static final String EXTRA_URL = "url";
131
132 /**
133 * Extra for use with {@link #ACTION_CHOOSER}
134 * @hide Also used by KeyChainActivity implementation
135 */
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700136 public static final String EXTRA_ALIAS = "alias";
137
138 /**
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700139 * Extra for use with {@link #ACTION_CHOOSER}
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700140 * @hide Also used by KeyChainActivity implementation
141 */
142 public static final String EXTRA_SENDER = "sender";
143
144 /**
Selim Gurun93ba4fe2012-02-14 11:48:49 -0800145 * Action to bring up the CertInstaller.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700146 */
147 private static final String ACTION_INSTALL = "android.credentials.INSTALL";
148
149 /**
150 * Optional extra to specify a {@code String} credential name on
151 * the {@code Intent} returned by {@link #createInstallIntent}.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700152 */
153 // Compatible with old com.android.certinstaller.CredentialHelper.CERT_NAME_KEY
154 public static final String EXTRA_NAME = "name";
155
156 /**
157 * Optional extra to specify an X.509 certificate to install on
158 * the {@code Intent} returned by {@link #createInstallIntent}.
159 * The extra value should be a PEM or ASN.1 DER encoded {@code
160 * byte[]}. An {@link X509Certificate} can be converted to DER
161 * encoded bytes with {@link X509Certificate#getEncoded}.
162 *
163 * <p>{@link #EXTRA_NAME} may be used to provide a default alias
164 * name for the installed certificate.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700165 */
166 // Compatible with old android.security.Credentials.CERTIFICATE
167 public static final String EXTRA_CERTIFICATE = "CERT";
168
169 /**
170 * Optional extra for use with the {@code Intent} returned by
171 * {@link #createInstallIntent} to specify a PKCS#12 key store to
172 * install. The extra value should be a {@code byte[]}. The bytes
173 * may come from an external source or be generated with {@link
Brian Carlstromca43c452011-06-29 18:53:17 -0700174 * java.security.KeyStore#store} on a "PKCS12" instance.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700175 *
176 * <p>The user will be prompted for the password to load the key store.
177 *
178 * <p>The key store will be scanned for {@link
179 * java.security.KeyStore.PrivateKeyEntry} entries and both the
180 * private key and associated certificate chain will be installed.
181 *
182 * <p>{@link #EXTRA_NAME} may be used to provide a default alias
183 * name for the installed credentials.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700184 */
185 // Compatible with old android.security.Credentials.PKCS12
186 public static final String EXTRA_PKCS12 = "PKCS12";
187
Selim Gurun93ba4fe2012-02-14 11:48:49 -0800188
189 /**
Selim Gurun93ba4fe2012-02-14 11:48:49 -0800190 * Broadcast Action: Indicates the trusted storage has changed. Sent when
191 * one of this happens:
192 *
193 * <ul>
194 * <li>a new CA is added,
195 * <li>an existing CA is removed or disabled,
196 * <li>a disabled CA is enabled,
197 * <li>trusted storage is reset (all user certs are cleared),
198 * <li>when permission to access a private key is changed.
199 * </ul>
200 */
201 public static final String ACTION_STORAGE_CHANGED = "android.security.STORAGE_CHANGED";
202
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700203 /**
204 * Returns an {@code Intent} that can be used for credential
205 * installation. The intent may be used without any extras, in
206 * which case the user will be able to install credentials from
207 * their own source.
208 *
209 * <p>Alternatively, {@link #EXTRA_CERTIFICATE} or {@link
210 * #EXTRA_PKCS12} maybe used to specify the bytes of an X.509
211 * certificate or a PKCS#12 key store for installation. These
Brian Carlstromca43c452011-06-29 18:53:17 -0700212 * extras may be combined with {@link #EXTRA_NAME} to provide a
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700213 * default alias name for credentials being installed.
214 *
215 * <p>When used with {@link Activity#startActivityForResult},
216 * {@link Activity#RESULT_OK} will be returned if a credential was
217 * successfully installed, otherwise {@link
218 * Activity#RESULT_CANCELED} will be returned.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700219 */
220 public static Intent createInstallIntent() {
221 Intent intent = new Intent(ACTION_INSTALL);
Kenny Root1a88d832014-02-07 09:12:48 -0800222 intent.setClassName(CERT_INSTALLER_PACKAGE,
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700223 "com.android.certinstaller.CertInstallerMain");
224 return intent;
225 }
226
227 /**
Brian Carlstromba1a6672011-05-24 21:54:37 -0700228 * Launches an {@code Activity} for the user to select the alias
229 * for a private key and certificate pair for authentication. The
230 * selected alias or null will be returned via the
Brian Carlstrom93201f52011-06-09 15:05:35 -0700231 * KeyChainAliasCallback callback.
232 *
Robin Lee3798ed52015-02-03 17:55:31 +0000233 * <p>The device or profile owner can intercept this before the activity
234 * is shown, to pick a specific private key alias.
235 *
236 * <p>{@code keyTypes} and {@code issuers} may be used to
237 * highlight suggested choices to the user, although to cope with
238 * sometimes erroneous values provided by servers, the user may be
239 * able to override these suggestions.
240 *
241 * <p>{@code host} and {@code port} may be used to give the user
242 * more context about the server requesting the credentials.
243 *
244 * <p>{@code alias} allows the chooser to preselect an existing
245 * alias which will still be subject to user confirmation.
246 *
247 * @param activity The {@link Activity} context to use for
248 * launching the new sub-Activity to prompt the user to select
249 * a private key; used only to call startActivity(); must not
250 * be null.
251 * @param response Callback to invoke when the request completes;
252 * must not be null
253 * @param keyTypes The acceptable types of asymmetric keys such as
254 * "RSA" or "DSA", or a null array.
255 * @param issuers The acceptable certificate issuers for the
256 * certificate matching the private key, or null.
257 * @param host The host name of the server requesting the
258 * certificate, or null if unavailable.
259 * @param port The port number of the server requesting the
260 * certificate, or -1 if unavailable.
261 * @param alias The alias to preselect if available, or null if
262 * unavailable.
263 */
264 public static void choosePrivateKeyAlias(Activity activity, KeyChainAliasCallback response,
265 String[] keyTypes, Principal[] issuers, String host, int port, String alias) {
266 choosePrivateKeyAlias(activity, response, keyTypes, issuers, host, port, null, alias);
267 }
268
269 /**
270 * Launches an {@code Activity} for the user to select the alias
271 * for a private key and certificate pair for authentication. The
272 * selected alias or null will be returned via the
273 * KeyChainAliasCallback callback.
274 *
275 * <p>The device or profile owner can intercept this before the activity
276 * is shown, to pick a specific private key alias.</p>
277 *
Brian Carlstrom93201f52011-06-09 15:05:35 -0700278 * <p>{@code keyTypes} and {@code issuers} may be used to
279 * highlight suggested choices to the user, although to cope with
280 * sometimes erroneous values provided by servers, the user may be
281 * able to override these suggestions.
282 *
283 * <p>{@code host} and {@code port} may be used to give the user
284 * more context about the server requesting the credentials.
285 *
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700286 * <p>{@code alias} allows the chooser to preselect an existing
287 * alias which will still be subject to user confirmation.
288 *
Brian Carlstrom93201f52011-06-09 15:05:35 -0700289 * @param activity The {@link Activity} context to use for
290 * launching the new sub-Activity to prompt the user to select
291 * a private key; used only to call startActivity(); must not
292 * be null.
293 * @param response Callback to invoke when the request completes;
294 * must not be null
295 * @param keyTypes The acceptable types of asymmetric keys such as
Alex Klyubincd2329d2015-01-14 16:45:51 -0800296 * "EC" or "RSA", or a null array.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700297 * @param issuers The acceptable certificate issuers for the
298 * certificate matching the private key, or null.
299 * @param host The host name of the server requesting the
300 * certificate, or null if unavailable.
301 * @param port The port number of the server requesting the
302 * certificate, or -1 if unavailable.
Robin Lee3798ed52015-02-03 17:55:31 +0000303 * @param url The full url the server is requesting the certificate
304 * for, or null if unavailable.
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700305 * @param alias The alias to preselect if available, or null if
306 * unavailable.
Brian Carlstromba1a6672011-05-24 21:54:37 -0700307 */
Brian Carlstrom93201f52011-06-09 15:05:35 -0700308 public static void choosePrivateKeyAlias(Activity activity, KeyChainAliasCallback response,
309 String[] keyTypes, Principal[] issuers,
Robin Lee3798ed52015-02-03 17:55:31 +0000310 String host, int port, String url,
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700311 String alias) {
Brian Carlstrom93201f52011-06-09 15:05:35 -0700312 /*
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700313 * TODO currently keyTypes, issuers are unused. They are meant
314 * to follow the semantics and purpose of X509KeyManager
315 * method arguments.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700316 *
317 * keyTypes would allow the list to be filtered and typically
318 * will be set correctly by the server. In practice today,
Alex Klyubincd2329d2015-01-14 16:45:51 -0800319 * most all users will want only RSA or EC, and usually
Brian Carlstrom93201f52011-06-09 15:05:35 -0700320 * only a small number of certs will be available.
321 *
322 * issuers is typically not useful. Some servers historically
323 * will send the entire list of public CAs known to the
324 * server. Others will send none. If this is used, if there
325 * are no matches after applying the constraint, it should be
326 * ignored.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700327 */
Brian Carlstromba1a6672011-05-24 21:54:37 -0700328 if (activity == null) {
329 throw new NullPointerException("activity == null");
330 }
331 if (response == null) {
332 throw new NullPointerException("response == null");
333 }
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700334 Intent intent = new Intent(ACTION_CHOOSER);
Kenny Roota3659062014-03-17 16:21:53 -0700335 intent.setPackage(KEYCHAIN_PACKAGE);
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700336 intent.putExtra(EXTRA_RESPONSE, new AliasResponse(response));
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700337 intent.putExtra(EXTRA_HOST, host);
338 intent.putExtra(EXTRA_PORT, port);
Robin Lee3798ed52015-02-03 17:55:31 +0000339 intent.putExtra(EXTRA_URL, url);
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700340 intent.putExtra(EXTRA_ALIAS, alias);
341 // the PendingIntent is used to get calling package name
342 intent.putExtra(EXTRA_SENDER, PendingIntent.getActivity(activity, 0, new Intent(), 0));
Brian Carlstromba1a6672011-05-24 21:54:37 -0700343 activity.startActivity(intent);
344 }
345
Brian Carlstrom93201f52011-06-09 15:05:35 -0700346 private static class AliasResponse extends IKeyChainAliasCallback.Stub {
Brian Carlstrom93201f52011-06-09 15:05:35 -0700347 private final KeyChainAliasCallback keyChainAliasResponse;
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700348 private AliasResponse(KeyChainAliasCallback keyChainAliasResponse) {
Brian Carlstromba1a6672011-05-24 21:54:37 -0700349 this.keyChainAliasResponse = keyChainAliasResponse;
350 }
351 @Override public void alias(String alias) {
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700352 keyChainAliasResponse.alias(alias);
Brian Carlstromba1a6672011-05-24 21:54:37 -0700353 }
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700354 }
355
356 /**
Brian Carlstromba1a6672011-05-24 21:54:37 -0700357 * Returns the {@code PrivateKey} for the requested alias, or null
358 * if no there is no result.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700359 *
Brian Carlstrom93201f52011-06-09 15:05:35 -0700360 * @param alias The alias of the desired private key, typically
361 * returned via {@link KeyChainAliasCallback#alias}.
362 * @throws KeyChainException if the alias was valid but there was some problem accessing it.
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700363 */
Brian Carlstromba1a6672011-05-24 21:54:37 -0700364 public static PrivateKey getPrivateKey(Context context, String alias)
Brian Carlstrom93201f52011-06-09 15:05:35 -0700365 throws KeyChainException, InterruptedException {
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700366 if (alias == null) {
367 throw new NullPointerException("alias == null");
368 }
Brian Carlstromd7524722011-05-17 16:20:36 -0700369 KeyChainConnection keyChainConnection = bind(context);
Brian Carlstrom8e9929c2011-05-17 00:40:28 -0700370 try {
Kenny Root5423e682011-11-14 08:43:13 -0800371 final IKeyChainService keyChainService = keyChainConnection.getService();
372 final String keyId = keyChainService.requestPrivateKey(alias);
373 if (keyId == null) {
374 throw new KeyChainException("keystore had a problem");
375 }
376
377 final OpenSSLEngine engine = OpenSSLEngine.getInstance("keystore");
378 return engine.getPrivateKeyById(keyId);
Brian Carlstrom93201f52011-06-09 15:05:35 -0700379 } catch (RemoteException e) {
380 throw new KeyChainException(e);
381 } catch (RuntimeException e) {
382 // only certain RuntimeExceptions can be propagated across the IKeyChainService call
383 throw new KeyChainException(e);
Kenny Root5423e682011-11-14 08:43:13 -0800384 } catch (InvalidKeyException e) {
385 throw new KeyChainException(e);
Brian Carlstromba1a6672011-05-24 21:54:37 -0700386 } finally {
387 keyChainConnection.close();
388 }
389 }
390
391 /**
392 * Returns the {@code X509Certificate} chain for the requested
393 * alias, or null if no there is no result.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700394 *
Brian Carlstrom93201f52011-06-09 15:05:35 -0700395 * @param alias The alias of the desired certificate chain, typically
396 * returned via {@link KeyChainAliasCallback#alias}.
397 * @throws KeyChainException if the alias was valid but there was some problem accessing it.
Brian Carlstromba1a6672011-05-24 21:54:37 -0700398 */
399 public static X509Certificate[] getCertificateChain(Context context, String alias)
Brian Carlstrom93201f52011-06-09 15:05:35 -0700400 throws KeyChainException, InterruptedException {
Brian Carlstromba1a6672011-05-24 21:54:37 -0700401 if (alias == null) {
402 throw new NullPointerException("alias == null");
403 }
404 KeyChainConnection keyChainConnection = bind(context);
405 try {
Brian Carlstromba1a6672011-05-24 21:54:37 -0700406 IKeyChainService keyChainService = keyChainConnection.getService();
Kenny Root0150e482013-02-13 15:22:50 -0800407
408 final byte[] certificateBytes = keyChainService.getCertificate(alias);
409 if (certificateBytes == null) {
410 return null;
411 }
412
Brian Carlstromdb93b782011-07-01 00:12:17 -0700413 TrustedCertificateStore store = new TrustedCertificateStore();
Kenny Root54e03af2012-08-07 10:04:26 -0700414 List<X509Certificate> chain = store
415 .getCertificateChain(toCertificate(certificateBytes));
Brian Carlstromdb93b782011-07-01 00:12:17 -0700416 return chain.toArray(new X509Certificate[chain.size()]);
Kenny Rootcfba6a02013-05-06 15:00:58 -0700417 } catch (CertificateException e) {
418 throw new KeyChainException(e);
Brian Carlstrom93201f52011-06-09 15:05:35 -0700419 } catch (RemoteException e) {
420 throw new KeyChainException(e);
421 } catch (RuntimeException e) {
422 // only certain RuntimeExceptions can be propagated across the IKeyChainService call
423 throw new KeyChainException(e);
Brian Carlstrom8e9929c2011-05-17 00:40:28 -0700424 } finally {
Brian Carlstromd7524722011-05-17 16:20:36 -0700425 keyChainConnection.close();
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700426 }
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700427 }
428
Kenny Rootbf556ac2013-04-01 15:10:22 -0700429 /**
430 * Returns {@code true} if the current device's {@code KeyChain} supports a
431 * specific {@code PrivateKey} type indicated by {@code algorithm} (e.g.,
432 * "RSA").
433 */
Kenny Root5b7e90a2013-04-02 11:23:41 -0700434 public static boolean isKeyAlgorithmSupported(String algorithm) {
Kenny Rootb91773b2013-09-05 13:03:16 -0700435 final String algUpper = algorithm.toUpperCase(Locale.US);
Kenny Root9d2d6b62014-11-26 09:08:40 -0800436 return "EC".equals(algUpper) || "RSA".equals(algUpper);
Kenny Rootbf556ac2013-04-01 15:10:22 -0700437 }
438
439 /**
440 * Returns {@code true} if the current device's {@code KeyChain} binds any
441 * {@code PrivateKey} of the given {@code algorithm} to the device once
442 * imported or generated. This can be used to tell if there is special
443 * hardware support that can be used to bind keys to the device in a way
444 * that makes it non-exportable.
445 */
Kenny Root5b7e90a2013-04-02 11:23:41 -0700446 public static boolean isBoundKeyAlgorithm(String algorithm) {
447 if (!isKeyAlgorithmSupported(algorithm)) {
Kenny Rootbf556ac2013-04-01 15:10:22 -0700448 return false;
449 }
450
Kenny Rootb91773b2013-09-05 13:03:16 -0700451 return KeyStore.getInstance().isHardwareBacked(algorithm);
Kenny Rootbf556ac2013-04-01 15:10:22 -0700452 }
453
Zoltan Szatmary-Banf0ae1352014-08-18 10:48:33 +0100454 /** @hide */
455 public static X509Certificate toCertificate(byte[] bytes) {
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700456 if (bytes == null) {
Brian Carlstrom8e9929c2011-05-17 00:40:28 -0700457 throw new IllegalArgumentException("bytes == null");
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700458 }
459 try {
460 CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
461 Certificate cert = certFactory.generateCertificate(new ByteArrayInputStream(bytes));
462 return (X509Certificate) cert;
463 } catch (CertificateException e) {
464 throw new AssertionError(e);
465 }
466 }
467
Brian Carlstromd7524722011-05-17 16:20:36 -0700468 /**
469 * @hide for reuse by CertInstaller and Settings.
470 * @see KeyChain#bind
471 */
472 public final static class KeyChainConnection implements Closeable {
473 private final Context context;
474 private final ServiceConnection serviceConnection;
475 private final IKeyChainService service;
476 private KeyChainConnection(Context context,
477 ServiceConnection serviceConnection,
478 IKeyChainService service) {
479 this.context = context;
480 this.serviceConnection = serviceConnection;
481 this.service = service;
482 }
483 @Override public void close() {
484 context.unbindService(serviceConnection);
485 }
486 public IKeyChainService getService() {
487 return service;
488 }
489 }
490
491 /**
492 * @hide for reuse by CertInstaller and Settings.
493 *
494 * Caller should call unbindService on the result when finished.
495 */
496 public static KeyChainConnection bind(Context context) throws InterruptedException {
Robin Lee306fe082014-06-19 14:04:24 +0000497 return bindAsUser(context, Process.myUserHandle());
498 }
499
500 /**
501 * @hide
502 */
503 public static KeyChainConnection bindAsUser(Context context, UserHandle user)
504 throws InterruptedException {
Brian Carlstromd7524722011-05-17 16:20:36 -0700505 if (context == null) {
506 throw new NullPointerException("context == null");
507 }
508 ensureNotOnMainThread(context);
509 final BlockingQueue<IKeyChainService> q = new LinkedBlockingQueue<IKeyChainService>(1);
510 ServiceConnection keyChainServiceConnection = new ServiceConnection() {
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700511 volatile boolean mConnectedAtLeastOnce = false;
Brian Carlstromd7524722011-05-17 16:20:36 -0700512 @Override public void onServiceConnected(ComponentName name, IBinder service) {
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700513 if (!mConnectedAtLeastOnce) {
514 mConnectedAtLeastOnce = true;
515 try {
516 q.put(IKeyChainService.Stub.asInterface(service));
517 } catch (InterruptedException e) {
518 // will never happen, since the queue starts with one available slot
519 }
Brian Carlstromd7524722011-05-17 16:20:36 -0700520 }
521 }
522 @Override public void onServiceDisconnected(ComponentName name) {}
523 };
Maggie Benthallda51e682013-08-08 22:35:44 -0400524 Intent intent = new Intent(IKeyChainService.class.getName());
525 ComponentName comp = intent.resolveSystemService(context.getPackageManager(), 0);
526 intent.setComponent(comp);
Robin Lee306fe082014-06-19 14:04:24 +0000527 boolean isBound = context.bindServiceAsUser(intent,
528 keyChainServiceConnection,
529 Context.BIND_AUTO_CREATE,
530 user);
Brian Carlstromd7524722011-05-17 16:20:36 -0700531 if (!isBound) {
532 throw new AssertionError("could not bind to KeyChainService");
533 }
534 return new KeyChainConnection(context, keyChainServiceConnection, q.take());
535 }
536
Brian Carlstrom8e9929c2011-05-17 00:40:28 -0700537 private static void ensureNotOnMainThread(Context context) {
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700538 Looper looper = Looper.myLooper();
Brian Carlstrom8e9929c2011-05-17 00:40:28 -0700539 if (looper != null && looper == context.getMainLooper()) {
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700540 throw new IllegalStateException(
541 "calling this from your main thread can lead to deadlock");
542 }
543 }
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700544}