blob: 059d8e6dbf0089c715d5e8f814af6c001433584a [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
Alex Klyubin54bb1592015-05-11 12:30:03 -070018import android.annotation.NonNull;
19import android.annotation.Nullable;
Brian Carlstromba1a6672011-05-24 21:54:37 -070020import android.app.Activity;
Brian Carlstrom67c30df2011-06-24 02:13:23 -070021import android.app.PendingIntent;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070022import android.content.ComponentName;
23import android.content.Context;
24import android.content.Intent;
25import android.content.ServiceConnection;
Robin Lee39087b12015-05-05 15:57:17 +010026import android.net.Uri;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070027import android.os.IBinder;
28import android.os.Looper;
Robin Lee306fe082014-06-19 14:04:24 +000029import android.os.Process;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070030import android.os.RemoteException;
Robin Lee306fe082014-06-19 14:04:24 +000031import android.os.UserHandle;
Alex Klyubin469cbf52015-06-04 12:36:27 -070032import android.security.keystore.KeyInfo;
Alex Klyubin3f8d4d82015-05-13 09:15:00 -070033import android.security.keystore.KeyProperties;
34
Brian Carlstromb9a07c12011-04-11 09:03:51 -070035import java.io.ByteArrayInputStream;
Brian Carlstromd7524722011-05-17 16:20:36 -070036import java.io.Closeable;
Kenny Root5423e682011-11-14 08:43:13 -080037import java.security.InvalidKeyException;
Alex Klyubin469cbf52015-06-04 12:36:27 -070038import java.security.KeyFactory;
Brian Carlstrom93201f52011-06-09 15:05:35 -070039import java.security.Principal;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070040import java.security.PrivateKey;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070041import java.security.cert.Certificate;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070042import java.security.cert.CertificateException;
43import java.security.cert.CertificateFactory;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070044import java.security.cert.X509Certificate;
Brian Carlstromdb93b782011-07-01 00:12:17 -070045import java.util.List;
Kenny Rootb91773b2013-09-05 13:03:16 -070046import java.util.Locale;
Brian Carlstrom8e9929c2011-05-17 00:40:28 -070047import java.util.concurrent.BlockingQueue;
48import java.util.concurrent.LinkedBlockingQueue;
Kenny Root5423e682011-11-14 08:43:13 -080049
Kenny Root12e75222013-04-23 22:34:24 -070050import com.android.org.conscrypt.OpenSSLEngine;
51import com.android.org.conscrypt.TrustedCertificateStore;
Brian Carlstromb9a07c12011-04-11 09:03:51 -070052
53/**
Brian Carlstrom93201f52011-06-09 15:05:35 -070054 * The {@code KeyChain} class provides access to private keys and
55 * their corresponding certificate chains in credential storage.
56 *
57 * <p>Applications accessing the {@code KeyChain} normally go through
58 * these steps:
59 *
60 * <ol>
61 *
62 * <li>Receive a callback from an {@link javax.net.ssl.X509KeyManager
63 * X509KeyManager} that a private key is requested.
64 *
65 * <li>Call {@link #choosePrivateKeyAlias
66 * choosePrivateKeyAlias} to allow the user to select from a
67 * list of currently available private keys and corresponding
68 * certificate chains. The chosen alias will be returned by the
69 * callback {@link KeyChainAliasCallback#alias}, or null if no private
70 * key is available or the user cancels the request.
71 *
72 * <li>Call {@link #getPrivateKey} and {@link #getCertificateChain} to
73 * retrieve the credentials to return to the corresponding {@link
74 * javax.net.ssl.X509KeyManager} callbacks.
75 *
76 * </ol>
77 *
78 * <p>An application may remember the value of a selected alias to
79 * avoid prompting the user with {@link #choosePrivateKeyAlias
80 * choosePrivateKeyAlias} on subsequent connections. If the alias is
81 * no longer valid, null will be returned on lookups using that value
Brian Carlstromca43c452011-06-29 18:53:17 -070082 *
83 * <p>An application can request the installation of private keys and
84 * certificates via the {@code Intent} provided by {@link
85 * #createInstallIntent}. Private keys installed via this {@code
86 * Intent} will be accessible via {@link #choosePrivateKeyAlias} while
87 * Certificate Authority (CA) certificates will be trusted by all
88 * applications through the default {@code X509TrustManager}.
Brian Carlstromb9a07c12011-04-11 09:03:51 -070089 */
Brian Carlstrom93201f52011-06-09 15:05:35 -070090// TODO reference intent for credential installation when public
Brian Carlstromb9a07c12011-04-11 09:03:51 -070091public final class KeyChain {
92
93 private static final String TAG = "KeyChain";
94
95 /**
96 * @hide Also used by KeyChainService implementation
97 */
98 public static final String ACCOUNT_TYPE = "com.android.keychain";
99
100 /**
Kenny Roota3659062014-03-17 16:21:53 -0700101 * Package name for KeyChain chooser.
102 */
103 private static final String KEYCHAIN_PACKAGE = "com.android.keychain";
104
105 /**
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700106 * Action to bring up the KeyChainActivity
107 */
108 private static final String ACTION_CHOOSER = "com.android.keychain.CHOOSER";
109
110 /**
Kenny Root1a88d832014-02-07 09:12:48 -0800111 * Package name for the Certificate Installer.
112 */
113 private static final String CERT_INSTALLER_PACKAGE = "com.android.certinstaller";
114
115 /**
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700116 * Extra for use with {@link #ACTION_CHOOSER}
Brian Carlstromba1a6672011-05-24 21:54:37 -0700117 * @hide Also used by KeyChainActivity implementation
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700118 */
Brian Carlstromba1a6672011-05-24 21:54:37 -0700119 public static final String EXTRA_RESPONSE = "response";
120
121 /**
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700122 * Extra for use with {@link #ACTION_CHOOSER}
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700123 * @hide Also used by KeyChainActivity implementation
124 */
Robin Lee39087b12015-05-05 15:57:17 +0100125 public static final String EXTRA_URI = "uri";
Robin Lee3798ed52015-02-03 17:55:31 +0000126
127 /**
128 * Extra for use with {@link #ACTION_CHOOSER}
129 * @hide Also used by KeyChainActivity implementation
130 */
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700131 public static final String EXTRA_ALIAS = "alias";
132
133 /**
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700134 * Extra for use with {@link #ACTION_CHOOSER}
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700135 * @hide Also used by KeyChainActivity implementation
136 */
137 public static final String EXTRA_SENDER = "sender";
138
139 /**
Selim Gurun93ba4fe2012-02-14 11:48:49 -0800140 * Action to bring up the CertInstaller.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700141 */
142 private static final String ACTION_INSTALL = "android.credentials.INSTALL";
143
144 /**
145 * Optional extra to specify a {@code String} credential name on
146 * the {@code Intent} returned by {@link #createInstallIntent}.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700147 */
148 // Compatible with old com.android.certinstaller.CredentialHelper.CERT_NAME_KEY
149 public static final String EXTRA_NAME = "name";
150
151 /**
152 * Optional extra to specify an X.509 certificate to install on
153 * the {@code Intent} returned by {@link #createInstallIntent}.
154 * The extra value should be a PEM or ASN.1 DER encoded {@code
155 * byte[]}. An {@link X509Certificate} can be converted to DER
156 * encoded bytes with {@link X509Certificate#getEncoded}.
157 *
158 * <p>{@link #EXTRA_NAME} may be used to provide a default alias
159 * name for the installed certificate.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700160 */
161 // Compatible with old android.security.Credentials.CERTIFICATE
162 public static final String EXTRA_CERTIFICATE = "CERT";
163
164 /**
165 * Optional extra for use with the {@code Intent} returned by
166 * {@link #createInstallIntent} to specify a PKCS#12 key store to
167 * install. The extra value should be a {@code byte[]}. The bytes
168 * may come from an external source or be generated with {@link
Brian Carlstromca43c452011-06-29 18:53:17 -0700169 * java.security.KeyStore#store} on a "PKCS12" instance.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700170 *
171 * <p>The user will be prompted for the password to load the key store.
172 *
173 * <p>The key store will be scanned for {@link
174 * java.security.KeyStore.PrivateKeyEntry} entries and both the
175 * private key and associated certificate chain will be installed.
176 *
177 * <p>{@link #EXTRA_NAME} may be used to provide a default alias
178 * name for the installed credentials.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700179 */
180 // Compatible with old android.security.Credentials.PKCS12
181 public static final String EXTRA_PKCS12 = "PKCS12";
182
Selim Gurun93ba4fe2012-02-14 11:48:49 -0800183
184 /**
Selim Gurun93ba4fe2012-02-14 11:48:49 -0800185 * Broadcast Action: Indicates the trusted storage has changed. Sent when
186 * one of this happens:
187 *
188 * <ul>
189 * <li>a new CA is added,
190 * <li>an existing CA is removed or disabled,
191 * <li>a disabled CA is enabled,
192 * <li>trusted storage is reset (all user certs are cleared),
193 * <li>when permission to access a private key is changed.
194 * </ul>
195 */
196 public static final String ACTION_STORAGE_CHANGED = "android.security.STORAGE_CHANGED";
197
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700198 /**
199 * Returns an {@code Intent} that can be used for credential
200 * installation. The intent may be used without any extras, in
201 * which case the user will be able to install credentials from
202 * their own source.
203 *
204 * <p>Alternatively, {@link #EXTRA_CERTIFICATE} or {@link
205 * #EXTRA_PKCS12} maybe used to specify the bytes of an X.509
206 * certificate or a PKCS#12 key store for installation. These
Brian Carlstromca43c452011-06-29 18:53:17 -0700207 * extras may be combined with {@link #EXTRA_NAME} to provide a
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700208 * default alias name for credentials being installed.
209 *
210 * <p>When used with {@link Activity#startActivityForResult},
211 * {@link Activity#RESULT_OK} will be returned if a credential was
212 * successfully installed, otherwise {@link
213 * Activity#RESULT_CANCELED} will be returned.
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700214 */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700215 @NonNull
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700216 public static Intent createInstallIntent() {
217 Intent intent = new Intent(ACTION_INSTALL);
Kenny Root1a88d832014-02-07 09:12:48 -0800218 intent.setClassName(CERT_INSTALLER_PACKAGE,
Brian Carlstroma00a2b32011-06-29 10:42:35 -0700219 "com.android.certinstaller.CertInstallerMain");
220 return intent;
221 }
222
223 /**
Brian Carlstromba1a6672011-05-24 21:54:37 -0700224 * Launches an {@code Activity} for the user to select the alias
225 * for a private key and certificate pair for authentication. The
226 * selected alias or null will be returned via the
Brian Carlstrom93201f52011-06-09 15:05:35 -0700227 * KeyChainAliasCallback callback.
228 *
Robin Lee3798ed52015-02-03 17:55:31 +0000229 * <p>The device or profile owner can intercept this before the activity
230 * is shown, to pick a specific private key alias.
231 *
232 * <p>{@code keyTypes} and {@code issuers} may be used to
233 * highlight suggested choices to the user, although to cope with
234 * sometimes erroneous values provided by servers, the user may be
235 * able to override these suggestions.
236 *
237 * <p>{@code host} and {@code port} may be used to give the user
238 * more context about the server requesting the credentials.
239 *
240 * <p>{@code alias} allows the chooser to preselect an existing
241 * alias which will still be subject to user confirmation.
242 *
243 * @param activity The {@link Activity} context to use for
244 * launching the new sub-Activity to prompt the user to select
245 * a private key; used only to call startActivity(); must not
246 * be null.
247 * @param response Callback to invoke when the request completes;
248 * must not be null
249 * @param keyTypes The acceptable types of asymmetric keys such as
250 * "RSA" or "DSA", or a null array.
251 * @param issuers The acceptable certificate issuers for the
252 * certificate matching the private key, or null.
253 * @param host The host name of the server requesting the
254 * certificate, or null if unavailable.
255 * @param port The port number of the server requesting the
256 * certificate, or -1 if unavailable.
257 * @param alias The alias to preselect if available, or null if
258 * unavailable.
259 */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700260 public static void choosePrivateKeyAlias(@NonNull Activity activity,
261 @NonNull KeyChainAliasCallback response,
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700262 @KeyProperties.KeyAlgorithmEnum String[] keyTypes, Principal[] issuers,
Alex Klyubin54bb1592015-05-11 12:30:03 -0700263 @Nullable String host, int port, @Nullable String alias) {
Robin Lee39087b12015-05-05 15:57:17 +0100264 Uri uri = null;
265 if (host != null) {
266 uri = new Uri.Builder()
267 .authority(host + (port != -1 ? ":" + port : ""))
268 .build();
269 }
270 choosePrivateKeyAlias(activity, response, keyTypes, issuers, uri, alias);
Robin Lee3798ed52015-02-03 17:55:31 +0000271 }
272
273 /**
274 * Launches an {@code Activity} for the user to select the alias
275 * for a private key and certificate pair for authentication. The
276 * selected alias or null will be returned via the
277 * KeyChainAliasCallback callback.
278 *
279 * <p>The device or profile owner can intercept this before the activity
280 * is shown, to pick a specific private key alias.</p>
281 *
Brian Carlstrom93201f52011-06-09 15:05:35 -0700282 * <p>{@code keyTypes} and {@code issuers} may be used to
283 * highlight suggested choices to the user, although to cope with
284 * sometimes erroneous values provided by servers, the user may be
285 * able to override these suggestions.
286 *
287 * <p>{@code host} and {@code port} may be used to give the user
288 * more context about the server requesting the credentials.
289 *
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700290 * <p>{@code alias} allows the chooser to preselect an existing
291 * alias which will still be subject to user confirmation.
292 *
Brian Carlstrom93201f52011-06-09 15:05:35 -0700293 * @param activity The {@link Activity} context to use for
294 * launching the new sub-Activity to prompt the user to select
295 * a private key; used only to call startActivity(); must not
296 * be null.
297 * @param response Callback to invoke when the request completes;
298 * must not be null
299 * @param keyTypes The acceptable types of asymmetric keys such as
Alex Klyubincd2329d2015-01-14 16:45:51 -0800300 * "EC" or "RSA", or a null array.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700301 * @param issuers The acceptable certificate issuers for the
302 * certificate matching the private key, or null.
Robin Lee39087b12015-05-05 15:57:17 +0100303 * @param uri The full URI the server is requesting the certificate
Robin Lee3798ed52015-02-03 17:55:31 +0000304 * 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 */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700308 public static void choosePrivateKeyAlias(@NonNull Activity activity,
309 @NonNull KeyChainAliasCallback response,
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700310 @KeyProperties.KeyAlgorithmEnum String[] keyTypes, Principal[] issuers,
Robin Lee39087b12015-05-05 15:57:17 +0100311 @Nullable Uri uri, @Nullable 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));
Robin Lee39087b12015-05-05 15:57:17 +0100337 intent.putExtra(EXTRA_URI, uri);
Brian Carlstrom67c30df2011-06-24 02:13:23 -0700338 intent.putExtra(EXTRA_ALIAS, alias);
339 // the PendingIntent is used to get calling package name
340 intent.putExtra(EXTRA_SENDER, PendingIntent.getActivity(activity, 0, new Intent(), 0));
Brian Carlstromba1a6672011-05-24 21:54:37 -0700341 activity.startActivity(intent);
342 }
343
Brian Carlstrom93201f52011-06-09 15:05:35 -0700344 private static class AliasResponse extends IKeyChainAliasCallback.Stub {
Brian Carlstrom93201f52011-06-09 15:05:35 -0700345 private final KeyChainAliasCallback keyChainAliasResponse;
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700346 private AliasResponse(KeyChainAliasCallback keyChainAliasResponse) {
Brian Carlstromba1a6672011-05-24 21:54:37 -0700347 this.keyChainAliasResponse = keyChainAliasResponse;
348 }
349 @Override public void alias(String alias) {
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700350 keyChainAliasResponse.alias(alias);
Brian Carlstromba1a6672011-05-24 21:54:37 -0700351 }
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700352 }
353
354 /**
Brian Carlstromba1a6672011-05-24 21:54:37 -0700355 * Returns the {@code PrivateKey} for the requested alias, or null
356 * if no there is no result.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700357 *
Brian Carlstrom93201f52011-06-09 15:05:35 -0700358 * @param alias The alias of the desired private key, typically
359 * returned via {@link KeyChainAliasCallback#alias}.
360 * @throws KeyChainException if the alias was valid but there was some problem accessing it.
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700361 */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700362 @Nullable
363 public static PrivateKey getPrivateKey(@NonNull Context context, @NonNull String alias)
Brian Carlstrom93201f52011-06-09 15:05:35 -0700364 throws KeyChainException, InterruptedException {
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700365 if (alias == null) {
366 throw new NullPointerException("alias == null");
367 }
Brian Carlstromd7524722011-05-17 16:20:36 -0700368 KeyChainConnection keyChainConnection = bind(context);
Brian Carlstrom8e9929c2011-05-17 00:40:28 -0700369 try {
Kenny Root5423e682011-11-14 08:43:13 -0800370 final IKeyChainService keyChainService = keyChainConnection.getService();
371 final String keyId = keyChainService.requestPrivateKey(alias);
372 if (keyId == null) {
373 throw new KeyChainException("keystore had a problem");
374 }
375
376 final OpenSSLEngine engine = OpenSSLEngine.getInstance("keystore");
377 return engine.getPrivateKeyById(keyId);
Brian Carlstrom93201f52011-06-09 15:05:35 -0700378 } catch (RemoteException e) {
379 throw new KeyChainException(e);
380 } catch (RuntimeException e) {
381 // only certain RuntimeExceptions can be propagated across the IKeyChainService call
382 throw new KeyChainException(e);
Kenny Root5423e682011-11-14 08:43:13 -0800383 } catch (InvalidKeyException e) {
384 throw new KeyChainException(e);
Brian Carlstromba1a6672011-05-24 21:54:37 -0700385 } finally {
386 keyChainConnection.close();
387 }
388 }
389
390 /**
391 * Returns the {@code X509Certificate} chain for the requested
392 * alias, or null if no there is no result.
Brian Carlstrom93201f52011-06-09 15:05:35 -0700393 *
Brian Carlstrom93201f52011-06-09 15:05:35 -0700394 * @param alias The alias of the desired certificate chain, typically
395 * returned via {@link KeyChainAliasCallback#alias}.
396 * @throws KeyChainException if the alias was valid but there was some problem accessing it.
Brian Carlstromba1a6672011-05-24 21:54:37 -0700397 */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700398 @Nullable
399 public static X509Certificate[] getCertificateChain(@NonNull Context context,
400 @NonNull String alias) 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 */
Alex Klyubin4d5443f2015-05-06 15:43:52 -0700434 public static boolean isKeyAlgorithmSupported(
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700435 @NonNull @KeyProperties.KeyAlgorithmEnum String algorithm) {
Kenny Rootb91773b2013-09-05 13:03:16 -0700436 final String algUpper = algorithm.toUpperCase(Locale.US);
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700437 return KeyProperties.KEY_ALGORITHM_EC.equals(algUpper)
438 || KeyProperties.KEY_ALGORITHM_RSA.equals(algUpper);
Kenny Rootbf556ac2013-04-01 15:10:22 -0700439 }
440
441 /**
442 * Returns {@code true} if the current device's {@code KeyChain} binds any
443 * {@code PrivateKey} of the given {@code algorithm} to the device once
444 * imported or generated. This can be used to tell if there is special
445 * hardware support that can be used to bind keys to the device in a way
446 * that makes it non-exportable.
Alex Klyubin469cbf52015-06-04 12:36:27 -0700447 *
448 * @deprecated Whether the key is bound to the secure hardware is known only
449 * once the key has been imported. To find out, use:
450 * <pre>{@code
451 * PrivateKey key = ...; // private key from KeyChain
452 *
453 * KeyFactory keyFactory =
454 * KeyFactory.getInstance(key.getAlgorithm(), "AndroidKeyStore");
455 * KeyInfo keyInfo = keyFactory.getKeySpec(key, KeyInfo.class);
456 * if (keyInfo.isInsideSecureHardware()) &#123;
457 * // The key is bound to the secure hardware of this Android
458 * &#125;}</pre>
Kenny Rootbf556ac2013-04-01 15:10:22 -0700459 */
Alex Klyubin469cbf52015-06-04 12:36:27 -0700460 @Deprecated
Alex Klyubin4d5443f2015-05-06 15:43:52 -0700461 public static boolean isBoundKeyAlgorithm(
Alex Klyubin3f8d4d82015-05-13 09:15:00 -0700462 @NonNull @KeyProperties.KeyAlgorithmEnum String algorithm) {
Kenny Root5b7e90a2013-04-02 11:23:41 -0700463 if (!isKeyAlgorithmSupported(algorithm)) {
Kenny Rootbf556ac2013-04-01 15:10:22 -0700464 return false;
465 }
466
Kenny Rootb91773b2013-09-05 13:03:16 -0700467 return KeyStore.getInstance().isHardwareBacked(algorithm);
Kenny Rootbf556ac2013-04-01 15:10:22 -0700468 }
469
Zoltan Szatmary-Banf0ae1352014-08-18 10:48:33 +0100470 /** @hide */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700471 @NonNull
472 public static X509Certificate toCertificate(@NonNull byte[] bytes) {
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700473 if (bytes == null) {
Brian Carlstrom8e9929c2011-05-17 00:40:28 -0700474 throw new IllegalArgumentException("bytes == null");
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700475 }
476 try {
477 CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
478 Certificate cert = certFactory.generateCertificate(new ByteArrayInputStream(bytes));
479 return (X509Certificate) cert;
480 } catch (CertificateException e) {
481 throw new AssertionError(e);
482 }
483 }
484
Brian Carlstromd7524722011-05-17 16:20:36 -0700485 /**
486 * @hide for reuse by CertInstaller and Settings.
487 * @see KeyChain#bind
488 */
489 public final static class KeyChainConnection implements Closeable {
490 private final Context context;
491 private final ServiceConnection serviceConnection;
492 private final IKeyChainService service;
493 private KeyChainConnection(Context context,
494 ServiceConnection serviceConnection,
495 IKeyChainService service) {
496 this.context = context;
497 this.serviceConnection = serviceConnection;
498 this.service = service;
499 }
500 @Override public void close() {
501 context.unbindService(serviceConnection);
502 }
503 public IKeyChainService getService() {
504 return service;
505 }
506 }
507
508 /**
509 * @hide for reuse by CertInstaller and Settings.
510 *
511 * Caller should call unbindService on the result when finished.
512 */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700513 public static KeyChainConnection bind(@NonNull Context context) throws InterruptedException {
Robin Lee306fe082014-06-19 14:04:24 +0000514 return bindAsUser(context, Process.myUserHandle());
515 }
516
517 /**
518 * @hide
519 */
Alex Klyubin54bb1592015-05-11 12:30:03 -0700520 public static KeyChainConnection bindAsUser(@NonNull Context context, UserHandle user)
Robin Lee306fe082014-06-19 14:04:24 +0000521 throws InterruptedException {
Brian Carlstromd7524722011-05-17 16:20:36 -0700522 if (context == null) {
523 throw new NullPointerException("context == null");
524 }
525 ensureNotOnMainThread(context);
526 final BlockingQueue<IKeyChainService> q = new LinkedBlockingQueue<IKeyChainService>(1);
527 ServiceConnection keyChainServiceConnection = new ServiceConnection() {
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700528 volatile boolean mConnectedAtLeastOnce = false;
Brian Carlstromd7524722011-05-17 16:20:36 -0700529 @Override public void onServiceConnected(ComponentName name, IBinder service) {
Fred Quintanaab8b84a2011-07-13 14:55:39 -0700530 if (!mConnectedAtLeastOnce) {
531 mConnectedAtLeastOnce = true;
532 try {
533 q.put(IKeyChainService.Stub.asInterface(service));
534 } catch (InterruptedException e) {
535 // will never happen, since the queue starts with one available slot
536 }
Brian Carlstromd7524722011-05-17 16:20:36 -0700537 }
538 }
539 @Override public void onServiceDisconnected(ComponentName name) {}
540 };
Maggie Benthallda51e682013-08-08 22:35:44 -0400541 Intent intent = new Intent(IKeyChainService.class.getName());
542 ComponentName comp = intent.resolveSystemService(context.getPackageManager(), 0);
543 intent.setComponent(comp);
Robin Lee306fe082014-06-19 14:04:24 +0000544 boolean isBound = context.bindServiceAsUser(intent,
545 keyChainServiceConnection,
546 Context.BIND_AUTO_CREATE,
547 user);
Brian Carlstromd7524722011-05-17 16:20:36 -0700548 if (!isBound) {
549 throw new AssertionError("could not bind to KeyChainService");
550 }
551 return new KeyChainConnection(context, keyChainServiceConnection, q.take());
552 }
553
Alex Klyubin54bb1592015-05-11 12:30:03 -0700554 private static void ensureNotOnMainThread(@NonNull Context context) {
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700555 Looper looper = Looper.myLooper();
Brian Carlstrom8e9929c2011-05-17 00:40:28 -0700556 if (looper != null && looper == context.getMainLooper()) {
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700557 throw new IllegalStateException(
558 "calling this from your main thread can lead to deadlock");
559 }
560 }
Brian Carlstromb9a07c12011-04-11 09:03:51 -0700561}