blob: 8ad973d4fd028b87dff0123b0993ef982b7d9d54 [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;
26import android.os.RemoteException;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070027import java.io.ByteArrayInputStream;
Brian Carlstromd7524722011-05-17 16:20:36 -070028import java.io.Closeable;
Kenny Root5423e682011-11-14 08:43:13 -080029import java.security.InvalidKeyException;
Brian Carlstrom93201f52011-06-09 15:05:35 -070030import java.security.Principal;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070031import java.security.PrivateKey;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070032import java.security.cert.Certificate;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070033import java.security.cert.CertificateException;
34import java.security.cert.CertificateFactory;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070035import java.security.cert.X509Certificate;
Brian Carlstromdb93b782011-07-01 00:12:17 -070036import java.util.List;
Kenny Rootb91773b2013-09-05 13:03:16 -070037import java.util.Locale;
Brian Carlstrom8e9929c2011-05-17 00:40:28 -070038import java.util.concurrent.BlockingQueue;
39import java.util.concurrent.LinkedBlockingQueue;
Kenny Root5423e682011-11-14 08:43:13 -080040
Kenny Root12e75222013-04-23 22:34:24 -070041import com.android.org.conscrypt.OpenSSLEngine;
42import com.android.org.conscrypt.TrustedCertificateStore;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070043
44/**
Brian Carlstrom93201f52011-06-09 15:05:35 -070045 * The {@code KeyChain} class provides access to private keys and
46 * their corresponding certificate chains in credential storage.
47 *
48 * <p>Applications accessing the {@code KeyChain} normally go through
49 * these steps:
50 *
51 * <ol>
52 *
53 * <li>Receive a callback from an {@link javax.net.ssl.X509KeyManager
54 * X509KeyManager} that a private key is requested.
55 *
56 * <li>Call {@link #choosePrivateKeyAlias
57 * choosePrivateKeyAlias} to allow the user to select from a
58 * list of currently available private keys and corresponding
59 * certificate chains. The chosen alias will be returned by the
60 * callback {@link KeyChainAliasCallback#alias}, or null if no private
61 * key is available or the user cancels the request.
62 *
63 * <li>Call {@link #getPrivateKey} and {@link #getCertificateChain} to
64 * retrieve the credentials to return to the corresponding {@link
65 * javax.net.ssl.X509KeyManager} callbacks.
66 *
67 * </ol>
68 *
69 * <p>An application may remember the value of a selected alias to
70 * avoid prompting the user with {@link #choosePrivateKeyAlias
71 * choosePrivateKeyAlias} on subsequent connections. If the alias is
72 * no longer valid, null will be returned on lookups using that value
Brian Carlstromca43c452011-06-29 18:53:17 -070073 *
74 * <p>An application can request the installation of private keys and
75 * certificates via the {@code Intent} provided by {@link
76 * #createInstallIntent}. Private keys installed via this {@code
77 * Intent} will be accessible via {@link #choosePrivateKeyAlias} while
78 * Certificate Authority (CA) certificates will be trusted by all
79 * applications through the default {@code X509TrustManager}.
Brian Carlstromb9a07c12011-04-11 09:03:51 -070080 */
Brian Carlstrom93201f52011-06-09 15:05:35 -070081// TODO reference intent for credential installation when public
Brian Carlstromb9a07c12011-04-11 09:03:51 -070082public final class KeyChain {
83
84 private static final String TAG = "KeyChain";
85
86 /**
87 * @hide Also used by KeyChainService implementation
88 */
89 public static final String ACCOUNT_TYPE = "com.android.keychain";
90
91 /**
Brian Carlstroma00a2b32011-06-29 10:42:35 -070092 * Action to bring up the KeyChainActivity
93 */
94 private static final String ACTION_CHOOSER = "com.android.keychain.CHOOSER";
95
96 /**
97 * Extra for use with {@link #ACTION_CHOOSER}
Brian Carlstromba1a6672011-05-24 21:54:37 -070098 * @hide Also used by KeyChainActivity implementation
Brian Carlstromb9a07c12011-04-11 09:03:51 -070099 */
Brian Carlstromba1a6672011-05-24 21:54:37 -0700100 public static final String EXTRA_RESPONSE = "response";
101
102 /**
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700103 * Extra for use with {@link #ACTION_CHOOSER}
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700104 * @hide Also used by KeyChainActivity implementation
105 */
106 public static final String EXTRA_HOST = "host";
107
108 /**
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700109 * Extra for use with {@link #ACTION_CHOOSER}
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700110 * @hide Also used by KeyChainActivity implementation
111 */
112 public static final String EXTRA_PORT = "port";
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_ALIAS = "alias";
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_SENDER = "sender";
125
126 /**
Selim Gurun93ba4fe2012-02-14 11:48:49 -0800127 * Action to bring up the CertInstaller.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700128 */
129 private static final String ACTION_INSTALL = "android.credentials.INSTALL";
130
131 /**
132 * Optional extra to specify a {@code String} credential name on
133 * the {@code Intent} returned by {@link #createInstallIntent}.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700134 */
135 // Compatible with old com.android.certinstaller.CredentialHelper.CERT_NAME_KEY
136 public static final String EXTRA_NAME = "name";
137
138 /**
139 * Optional extra to specify an X.509 certificate to install on
140 * the {@code Intent} returned by {@link #createInstallIntent}.
141 * The extra value should be a PEM or ASN.1 DER encoded {@code
142 * byte[]}. An {@link X509Certificate} can be converted to DER
143 * encoded bytes with {@link X509Certificate#getEncoded}.
144 *
145 * <p>{@link #EXTRA_NAME} may be used to provide a default alias
146 * name for the installed certificate.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700147 */
148 // Compatible with old android.security.Credentials.CERTIFICATE
149 public static final String EXTRA_CERTIFICATE = "CERT";
150
151 /**
152 * Optional extra for use with the {@code Intent} returned by
153 * {@link #createInstallIntent} to specify a PKCS#12 key store to
154 * install. The extra value should be a {@code byte[]}. The bytes
155 * may come from an external source or be generated with {@link
Brian Carlstromca43c452011-06-29 18:53:17 -0700156 * java.security.KeyStore#store} on a "PKCS12" instance.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700157 *
158 * <p>The user will be prompted for the password to load the key store.
159 *
160 * <p>The key store will be scanned for {@link
161 * java.security.KeyStore.PrivateKeyEntry} entries and both the
162 * private key and associated certificate chain will be installed.
163 *
164 * <p>{@link #EXTRA_NAME} may be used to provide a default alias
165 * name for the installed credentials.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700166 */
167 // Compatible with old android.security.Credentials.PKCS12
168 public static final String EXTRA_PKCS12 = "PKCS12";
169
Selim Gurun93ba4fe2012-02-14 11:48:49 -0800170
171 /**
Selim Gurun93ba4fe2012-02-14 11:48:49 -0800172 * Broadcast Action: Indicates the trusted storage has changed. Sent when
173 * one of this happens:
174 *
175 * <ul>
176 * <li>a new CA is added,
177 * <li>an existing CA is removed or disabled,
178 * <li>a disabled CA is enabled,
179 * <li>trusted storage is reset (all user certs are cleared),
180 * <li>when permission to access a private key is changed.
181 * </ul>
182 */
183 public static final String ACTION_STORAGE_CHANGED = "android.security.STORAGE_CHANGED";
184
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700185 /**
186 * Returns an {@code Intent} that can be used for credential
187 * installation. The intent may be used without any extras, in
188 * which case the user will be able to install credentials from
189 * their own source.
190 *
191 * <p>Alternatively, {@link #EXTRA_CERTIFICATE} or {@link
192 * #EXTRA_PKCS12} maybe used to specify the bytes of an X.509
193 * certificate or a PKCS#12 key store for installation. These
Brian Carlstromca43c452011-06-29 18:53:17 -0700194 * extras may be combined with {@link #EXTRA_NAME} to provide a
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700195 * default alias name for credentials being installed.
196 *
197 * <p>When used with {@link Activity#startActivityForResult},
198 * {@link Activity#RESULT_OK} will be returned if a credential was
199 * successfully installed, otherwise {@link
200 * Activity#RESULT_CANCELED} will be returned.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700201 */
202 public static Intent createInstallIntent() {
203 Intent intent = new Intent(ACTION_INSTALL);
204 intent.setClassName("com.android.certinstaller",
205 "com.android.certinstaller.CertInstallerMain");
206 return intent;
207 }
208
209 /**
Brian Carlstromba1a6672011-05-24 21:54:37 -0700210 * Launches an {@code Activity} for the user to select the alias
211 * for a private key and certificate pair for authentication. The
212 * selected alias or null will be returned via the
Brian Carlstrom93201f52011-06-09 15:05:35 -0700213 * KeyChainAliasCallback callback.
214 *
215 * <p>{@code keyTypes} and {@code issuers} may be used to
216 * highlight suggested choices to the user, although to cope with
217 * sometimes erroneous values provided by servers, the user may be
218 * able to override these suggestions.
219 *
220 * <p>{@code host} and {@code port} may be used to give the user
221 * more context about the server requesting the credentials.
222 *
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700223 * <p>{@code alias} allows the chooser to preselect an existing
224 * alias which will still be subject to user confirmation.
225 *
Brian Carlstrom93201f52011-06-09 15:05:35 -0700226 * @param activity The {@link Activity} context to use for
227 * launching the new sub-Activity to prompt the user to select
228 * a private key; used only to call startActivity(); must not
229 * be null.
230 * @param response Callback to invoke when the request completes;
231 * must not be null
232 * @param keyTypes The acceptable types of asymmetric keys such as
233 * "RSA" or "DSA", or a null array.
234 * @param issuers The acceptable certificate issuers for the
235 * certificate matching the private key, or null.
236 * @param host The host name of the server requesting the
237 * certificate, or null if unavailable.
238 * @param port The port number of the server requesting the
239 * certificate, or -1 if unavailable.
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700240 * @param alias The alias to preselect if available, or null if
241 * unavailable.
Brian Carlstromba1a6672011-05-24 21:54:37 -0700242 */
Brian Carlstrom93201f52011-06-09 15:05:35 -0700243 public static void choosePrivateKeyAlias(Activity activity, KeyChainAliasCallback response,
244 String[] keyTypes, Principal[] issuers,
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700245 String host, int port,
246 String alias) {
Brian Carlstrom93201f52011-06-09 15:05:35 -0700247 /*
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700248 * TODO currently keyTypes, issuers are unused. They are meant
249 * to follow the semantics and purpose of X509KeyManager
250 * method arguments.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700251 *
252 * keyTypes would allow the list to be filtered and typically
253 * will be set correctly by the server. In practice today,
254 * most all users will want only RSA, rarely DSA, and usually
255 * only a small number of certs will be available.
256 *
257 * issuers is typically not useful. Some servers historically
258 * will send the entire list of public CAs known to the
259 * server. Others will send none. If this is used, if there
260 * are no matches after applying the constraint, it should be
261 * ignored.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700262 */
Brian Carlstromba1a6672011-05-24 21:54:37 -0700263 if (activity == null) {
264 throw new NullPointerException("activity == null");
265 }
266 if (response == null) {
267 throw new NullPointerException("response == null");
268 }
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700269 Intent intent = new Intent(ACTION_CHOOSER);
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700270 intent.putExtra(EXTRA_RESPONSE, new AliasResponse(response));
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700271 intent.putExtra(EXTRA_HOST, host);
272 intent.putExtra(EXTRA_PORT, port);
273 intent.putExtra(EXTRA_ALIAS, alias);
274 // the PendingIntent is used to get calling package name
275 intent.putExtra(EXTRA_SENDER, PendingIntent.getActivity(activity, 0, new Intent(), 0));
Brian Carlstromba1a6672011-05-24 21:54:37 -0700276 activity.startActivity(intent);
277 }
278
Brian Carlstrom93201f52011-06-09 15:05:35 -0700279 private static class AliasResponse extends IKeyChainAliasCallback.Stub {
Brian Carlstrom93201f52011-06-09 15:05:35 -0700280 private final KeyChainAliasCallback keyChainAliasResponse;
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700281 private AliasResponse(KeyChainAliasCallback keyChainAliasResponse) {
Brian Carlstromba1a6672011-05-24 21:54:37 -0700282 this.keyChainAliasResponse = keyChainAliasResponse;
283 }
284 @Override public void alias(String alias) {
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700285 keyChainAliasResponse.alias(alias);
Brian Carlstromba1a6672011-05-24 21:54:37 -0700286 }
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700287 }
288
289 /**
Brian Carlstromba1a6672011-05-24 21:54:37 -0700290 * Returns the {@code PrivateKey} for the requested alias, or null
291 * if no there is no result.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700292 *
Brian Carlstrom93201f52011-06-09 15:05:35 -0700293 * @param alias The alias of the desired private key, typically
294 * returned via {@link KeyChainAliasCallback#alias}.
295 * @throws KeyChainException if the alias was valid but there was some problem accessing it.
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700296 */
Brian Carlstromba1a6672011-05-24 21:54:37 -0700297 public static PrivateKey getPrivateKey(Context context, String alias)
Brian Carlstrom93201f52011-06-09 15:05:35 -0700298 throws KeyChainException, InterruptedException {
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700299 if (alias == null) {
300 throw new NullPointerException("alias == null");
301 }
Brian Carlstromd7524722011-05-17 16:20:36 -0700302 KeyChainConnection keyChainConnection = bind(context);
Brian Carlstrom8e9929c2011-05-17 00:40:28 -0700303 try {
Kenny Root5423e682011-11-14 08:43:13 -0800304 final IKeyChainService keyChainService = keyChainConnection.getService();
305 final String keyId = keyChainService.requestPrivateKey(alias);
306 if (keyId == null) {
307 throw new KeyChainException("keystore had a problem");
308 }
309
310 final OpenSSLEngine engine = OpenSSLEngine.getInstance("keystore");
311 return engine.getPrivateKeyById(keyId);
Brian Carlstrom93201f52011-06-09 15:05:35 -0700312 } catch (RemoteException e) {
313 throw new KeyChainException(e);
314 } catch (RuntimeException e) {
315 // only certain RuntimeExceptions can be propagated across the IKeyChainService call
316 throw new KeyChainException(e);
Kenny Root5423e682011-11-14 08:43:13 -0800317 } catch (InvalidKeyException e) {
318 throw new KeyChainException(e);
Brian Carlstromba1a6672011-05-24 21:54:37 -0700319 } finally {
320 keyChainConnection.close();
321 }
322 }
323
324 /**
325 * Returns the {@code X509Certificate} chain for the requested
326 * alias, or null if no there is no result.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700327 *
Brian Carlstrom93201f52011-06-09 15:05:35 -0700328 * @param alias The alias of the desired certificate chain, typically
329 * returned via {@link KeyChainAliasCallback#alias}.
330 * @throws KeyChainException if the alias was valid but there was some problem accessing it.
Brian Carlstromba1a6672011-05-24 21:54:37 -0700331 */
332 public static X509Certificate[] getCertificateChain(Context context, String alias)
Brian Carlstrom93201f52011-06-09 15:05:35 -0700333 throws KeyChainException, InterruptedException {
Brian Carlstromba1a6672011-05-24 21:54:37 -0700334 if (alias == null) {
335 throw new NullPointerException("alias == null");
336 }
337 KeyChainConnection keyChainConnection = bind(context);
338 try {
Brian Carlstromba1a6672011-05-24 21:54:37 -0700339 IKeyChainService keyChainService = keyChainConnection.getService();
Kenny Root0150e482013-02-13 15:22:50 -0800340
341 final byte[] certificateBytes = keyChainService.getCertificate(alias);
342 if (certificateBytes == null) {
343 return null;
344 }
345
Brian Carlstromdb93b782011-07-01 00:12:17 -0700346 TrustedCertificateStore store = new TrustedCertificateStore();
Kenny Root54e03af2012-08-07 10:04:26 -0700347 List<X509Certificate> chain = store
348 .getCertificateChain(toCertificate(certificateBytes));
Brian Carlstromdb93b782011-07-01 00:12:17 -0700349 return chain.toArray(new X509Certificate[chain.size()]);
Kenny Rootcfba6a02013-05-06 15:00:58 -0700350 } catch (CertificateException e) {
351 throw new KeyChainException(e);
Brian Carlstrom93201f52011-06-09 15:05:35 -0700352 } catch (RemoteException e) {
353 throw new KeyChainException(e);
354 } catch (RuntimeException e) {
355 // only certain RuntimeExceptions can be propagated across the IKeyChainService call
356 throw new KeyChainException(e);
Brian Carlstrom8e9929c2011-05-17 00:40:28 -0700357 } finally {
Brian Carlstromd7524722011-05-17 16:20:36 -0700358 keyChainConnection.close();
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700359 }
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700360 }
361
Kenny Rootbf556ac2013-04-01 15:10:22 -0700362 /**
363 * Returns {@code true} if the current device's {@code KeyChain} supports a
364 * specific {@code PrivateKey} type indicated by {@code algorithm} (e.g.,
365 * "RSA").
366 */
Kenny Root5b7e90a2013-04-02 11:23:41 -0700367 public static boolean isKeyAlgorithmSupported(String algorithm) {
Kenny Rootb91773b2013-09-05 13:03:16 -0700368 final String algUpper = algorithm.toUpperCase(Locale.US);
369 return "DSA".equals(algUpper) || "EC".equals(algUpper) || "RSA".equals(algUpper);
Kenny Rootbf556ac2013-04-01 15:10:22 -0700370 }
371
372 /**
373 * Returns {@code true} if the current device's {@code KeyChain} binds any
374 * {@code PrivateKey} of the given {@code algorithm} to the device once
375 * imported or generated. This can be used to tell if there is special
376 * hardware support that can be used to bind keys to the device in a way
377 * that makes it non-exportable.
378 */
Kenny Root5b7e90a2013-04-02 11:23:41 -0700379 public static boolean isBoundKeyAlgorithm(String algorithm) {
380 if (!isKeyAlgorithmSupported(algorithm)) {
Kenny Rootbf556ac2013-04-01 15:10:22 -0700381 return false;
382 }
383
Kenny Rootb91773b2013-09-05 13:03:16 -0700384 return KeyStore.getInstance().isHardwareBacked(algorithm);
Kenny Rootbf556ac2013-04-01 15:10:22 -0700385 }
386
Brian Carlstrom8e9929c2011-05-17 00:40:28 -0700387 private static X509Certificate toCertificate(byte[] bytes) {
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700388 if (bytes == null) {
Brian Carlstrom8e9929c2011-05-17 00:40:28 -0700389 throw new IllegalArgumentException("bytes == null");
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700390 }
391 try {
392 CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
393 Certificate cert = certFactory.generateCertificate(new ByteArrayInputStream(bytes));
394 return (X509Certificate) cert;
395 } catch (CertificateException e) {
396 throw new AssertionError(e);
397 }
398 }
399
Brian Carlstromd7524722011-05-17 16:20:36 -0700400 /**
401 * @hide for reuse by CertInstaller and Settings.
402 * @see KeyChain#bind
403 */
404 public final static class KeyChainConnection implements Closeable {
405 private final Context context;
406 private final ServiceConnection serviceConnection;
407 private final IKeyChainService service;
408 private KeyChainConnection(Context context,
409 ServiceConnection serviceConnection,
410 IKeyChainService service) {
411 this.context = context;
412 this.serviceConnection = serviceConnection;
413 this.service = service;
414 }
415 @Override public void close() {
416 context.unbindService(serviceConnection);
417 }
418 public IKeyChainService getService() {
419 return service;
420 }
421 }
422
423 /**
424 * @hide for reuse by CertInstaller and Settings.
425 *
426 * Caller should call unbindService on the result when finished.
427 */
428 public static KeyChainConnection bind(Context context) throws InterruptedException {
429 if (context == null) {
430 throw new NullPointerException("context == null");
431 }
432 ensureNotOnMainThread(context);
433 final BlockingQueue<IKeyChainService> q = new LinkedBlockingQueue<IKeyChainService>(1);
434 ServiceConnection keyChainServiceConnection = new ServiceConnection() {
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700435 volatile boolean mConnectedAtLeastOnce = false;
Brian Carlstromd7524722011-05-17 16:20:36 -0700436 @Override public void onServiceConnected(ComponentName name, IBinder service) {
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700437 if (!mConnectedAtLeastOnce) {
438 mConnectedAtLeastOnce = true;
439 try {
440 q.put(IKeyChainService.Stub.asInterface(service));
441 } catch (InterruptedException e) {
442 // will never happen, since the queue starts with one available slot
443 }
Brian Carlstromd7524722011-05-17 16:20:36 -0700444 }
445 }
446 @Override public void onServiceDisconnected(ComponentName name) {}
447 };
Maggie Benthallda51e682013-08-08 22:35:44 -0400448 Intent intent = new Intent(IKeyChainService.class.getName());
449 ComponentName comp = intent.resolveSystemService(context.getPackageManager(), 0);
450 intent.setComponent(comp);
451 boolean isBound = context.bindService(intent,
Brian Carlstromd7524722011-05-17 16:20:36 -0700452 keyChainServiceConnection,
453 Context.BIND_AUTO_CREATE);
454 if (!isBound) {
455 throw new AssertionError("could not bind to KeyChainService");
456 }
457 return new KeyChainConnection(context, keyChainServiceConnection, q.take());
458 }
459
Brian Carlstrom8e9929c2011-05-17 00:40:28 -0700460 private static void ensureNotOnMainThread(Context context) {
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700461 Looper looper = Looper.myLooper();
Brian Carlstrom8e9929c2011-05-17 00:40:28 -0700462 if (looper != null && looper == context.getMainLooper()) {
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700463 throw new IllegalStateException(
464 "calling this from your main thread can lead to deadlock");
465 }
466 }
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700467}