FileDocCategorySizeDatePackage
KeyChain.javaAPI DocAndroid 5.1 API20039Thu Mar 12 22:22:30 GMT 2015android.security

KeyChain

public final class KeyChain extends Object
The {@code KeyChain} class provides access to private keys and their corresponding certificate chains in credential storage.

Applications accessing the {@code KeyChain} normally go through these steps:

  1. Receive a callback from an {@link javax.net.ssl.X509KeyManager X509KeyManager} that a private key is requested.
  2. Call {@link #choosePrivateKeyAlias choosePrivateKeyAlias} to allow the user to select from a list of currently available private keys and corresponding certificate chains. The chosen alias will be returned by the callback {@link KeyChainAliasCallback#alias}, or null if no private key is available or the user cancels the request.
  3. Call {@link #getPrivateKey} and {@link #getCertificateChain} to retrieve the credentials to return to the corresponding {@link javax.net.ssl.X509KeyManager} callbacks.

An application may remember the value of a selected alias to avoid prompting the user with {@link #choosePrivateKeyAlias choosePrivateKeyAlias} on subsequent connections. If the alias is no longer valid, null will be returned on lookups using that value

An application can request the installation of private keys and certificates via the {@code Intent} provided by {@link #createInstallIntent}. Private keys installed via this {@code Intent} will be accessible via {@link #choosePrivateKeyAlias} while Certificate Authority (CA) certificates will be trusted by all applications through the default {@code X509TrustManager}.

Fields Summary
private static final String
TAG
public static final String
ACCOUNT_TYPE
private static final String
KEYCHAIN_PACKAGE
Package name for KeyChain chooser.
private static final String
ACTION_CHOOSER
Action to bring up the KeyChainActivity
private static final String
CERT_INSTALLER_PACKAGE
Package name for the Certificate Installer.
public static final String
EXTRA_RESPONSE
Extra for use with {@link #ACTION_CHOOSER}
public static final String
EXTRA_HOST
Extra for use with {@link #ACTION_CHOOSER}
public static final String
EXTRA_PORT
Extra for use with {@link #ACTION_CHOOSER}
public static final String
EXTRA_ALIAS
Extra for use with {@link #ACTION_CHOOSER}
public static final String
EXTRA_SENDER
Extra for use with {@link #ACTION_CHOOSER}
private static final String
ACTION_INSTALL
Action to bring up the CertInstaller.
public static final String
EXTRA_NAME
Optional extra to specify a {@code String} credential name on the {@code Intent} returned by {@link #createInstallIntent}.
public static final String
EXTRA_CERTIFICATE
Optional extra to specify an X.509 certificate to install on the {@code Intent} returned by {@link #createInstallIntent}. The extra value should be a PEM or ASN.1 DER encoded {@code byte[]}. An {@link X509Certificate} can be converted to DER encoded bytes with {@link X509Certificate#getEncoded}.

{@link #EXTRA_NAME} may be used to provide a default alias name for the installed certificate.

public static final String
EXTRA_PKCS12
Optional extra for use with the {@code Intent} returned by {@link #createInstallIntent} to specify a PKCS#12 key store to install. The extra value should be a {@code byte[]}. The bytes may come from an external source or be generated with {@link java.security.KeyStore#store} on a "PKCS12" instance.

The user will be prompted for the password to load the key store.

The key store will be scanned for {@link java.security.KeyStore.PrivateKeyEntry} entries and both the private key and associated certificate chain will be installed.

{@link #EXTRA_NAME} may be used to provide a default alias name for the installed credentials.

public static final String
ACTION_STORAGE_CHANGED
Broadcast Action: Indicates the trusted storage has changed. Sent when one of this happens:
  • a new CA is added,
  • an existing CA is removed or disabled,
  • a disabled CA is enabled,
  • trusted storage is reset (all user certs are cleared),
  • when permission to access a private key is changed.
Constructors Summary
Methods Summary
public static android.security.KeyChain$KeyChainConnectionbind(android.content.Context context)

hide
for reuse by CertInstaller and Settings. Caller should call unbindService on the result when finished.

        return bindAsUser(context, Process.myUserHandle());
    
public static android.security.KeyChain$KeyChainConnectionbindAsUser(android.content.Context context, android.os.UserHandle user)

hide

        if (context == null) {
            throw new NullPointerException("context == null");
        }
        ensureNotOnMainThread(context);
        final BlockingQueue<IKeyChainService> q = new LinkedBlockingQueue<IKeyChainService>(1);
        ServiceConnection keyChainServiceConnection = new ServiceConnection() {
            volatile boolean mConnectedAtLeastOnce = false;
            @Override public void onServiceConnected(ComponentName name, IBinder service) {
                if (!mConnectedAtLeastOnce) {
                    mConnectedAtLeastOnce = true;
                    try {
                        q.put(IKeyChainService.Stub.asInterface(service));
                    } catch (InterruptedException e) {
                        // will never happen, since the queue starts with one available slot
                    }
                }
            }
            @Override public void onServiceDisconnected(ComponentName name) {}
        };
        Intent intent = new Intent(IKeyChainService.class.getName());
        ComponentName comp = intent.resolveSystemService(context.getPackageManager(), 0);
        intent.setComponent(comp);
        boolean isBound = context.bindServiceAsUser(intent,
                                                    keyChainServiceConnection,
                                                    Context.BIND_AUTO_CREATE,
                                                    user);
        if (!isBound) {
            throw new AssertionError("could not bind to KeyChainService");
        }
        return new KeyChainConnection(context, keyChainServiceConnection, q.take());
    
public static voidchoosePrivateKeyAlias(android.app.Activity activity, KeyChainAliasCallback response, java.lang.String[] keyTypes, java.security.Principal[] issuers, java.lang.String host, int port, java.lang.String alias)
Launches an {@code Activity} for the user to select the alias for a private key and certificate pair for authentication. The selected alias or null will be returned via the KeyChainAliasCallback callback.

{@code keyTypes} and {@code issuers} may be used to highlight suggested choices to the user, although to cope with sometimes erroneous values provided by servers, the user may be able to override these suggestions.

{@code host} and {@code port} may be used to give the user more context about the server requesting the credentials.

{@code alias} allows the chooser to preselect an existing alias which will still be subject to user confirmation.

param
activity The {@link Activity} context to use for launching the new sub-Activity to prompt the user to select a private key; used only to call startActivity(); must not be null.
param
response Callback to invoke when the request completes; must not be null
param
keyTypes The acceptable types of asymmetric keys such as "RSA" or "DSA", or a null array.
param
issuers The acceptable certificate issuers for the certificate matching the private key, or null.
param
host The host name of the server requesting the certificate, or null if unavailable.
param
port The port number of the server requesting the certificate, or -1 if unavailable.
param
alias The alias to preselect if available, or null if unavailable.

        /*
         * TODO currently keyTypes, issuers are unused. They are meant
         * to follow the semantics and purpose of X509KeyManager
         * method arguments.
         *
         * keyTypes would allow the list to be filtered and typically
         * will be set correctly by the server. In practice today,
         * most all users will want only RSA, rarely DSA, and usually
         * only a small number of certs will be available.
         *
         * issuers is typically not useful. Some servers historically
         * will send the entire list of public CAs known to the
         * server. Others will send none. If this is used, if there
         * are no matches after applying the constraint, it should be
         * ignored.
         */
        if (activity == null) {
            throw new NullPointerException("activity == null");
        }
        if (response == null) {
            throw new NullPointerException("response == null");
        }
        Intent intent = new Intent(ACTION_CHOOSER);
        intent.setPackage(KEYCHAIN_PACKAGE);
        intent.putExtra(EXTRA_RESPONSE, new AliasResponse(response));
        intent.putExtra(EXTRA_HOST, host);
        intent.putExtra(EXTRA_PORT, port);
        intent.putExtra(EXTRA_ALIAS, alias);
        // the PendingIntent is used to get calling package name
        intent.putExtra(EXTRA_SENDER, PendingIntent.getActivity(activity, 0, new Intent(), 0));
        activity.startActivity(intent);
    
public static android.content.IntentcreateInstallIntent()
Returns an {@code Intent} that can be used for credential installation. The intent may be used without any extras, in which case the user will be able to install credentials from their own source.

Alternatively, {@link #EXTRA_CERTIFICATE} or {@link #EXTRA_PKCS12} maybe used to specify the bytes of an X.509 certificate or a PKCS#12 key store for installation. These extras may be combined with {@link #EXTRA_NAME} to provide a default alias name for credentials being installed.

When used with {@link Activity#startActivityForResult}, {@link Activity#RESULT_OK} will be returned if a credential was successfully installed, otherwise {@link Activity#RESULT_CANCELED} will be returned.


                                                                                                          
        
        Intent intent = new Intent(ACTION_INSTALL);
        intent.setClassName(CERT_INSTALLER_PACKAGE,
                            "com.android.certinstaller.CertInstallerMain");
        return intent;
    
private static voidensureNotOnMainThread(android.content.Context context)

        Looper looper = Looper.myLooper();
        if (looper != null && looper == context.getMainLooper()) {
            throw new IllegalStateException(
                    "calling this from your main thread can lead to deadlock");
        }
    
public static java.security.cert.X509Certificate[]getCertificateChain(android.content.Context context, java.lang.String alias)
Returns the {@code X509Certificate} chain for the requested alias, or null if no there is no result.

param
alias The alias of the desired certificate chain, typically returned via {@link KeyChainAliasCallback#alias}.
throws
KeyChainException if the alias was valid but there was some problem accessing it.

        if (alias == null) {
            throw new NullPointerException("alias == null");
        }
        KeyChainConnection keyChainConnection = bind(context);
        try {
            IKeyChainService keyChainService = keyChainConnection.getService();

            final byte[] certificateBytes = keyChainService.getCertificate(alias);
            if (certificateBytes == null) {
                return null;
            }

            TrustedCertificateStore store = new TrustedCertificateStore();
            List<X509Certificate> chain = store
                    .getCertificateChain(toCertificate(certificateBytes));
            return chain.toArray(new X509Certificate[chain.size()]);
        } catch (CertificateException e) {
            throw new KeyChainException(e);
        } catch (RemoteException e) {
            throw new KeyChainException(e);
        } catch (RuntimeException e) {
            // only certain RuntimeExceptions can be propagated across the IKeyChainService call
            throw new KeyChainException(e);
        } finally {
            keyChainConnection.close();
        }
    
public static java.security.PrivateKeygetPrivateKey(android.content.Context context, java.lang.String alias)
Returns the {@code PrivateKey} for the requested alias, or null if no there is no result.

param
alias The alias of the desired private key, typically returned via {@link KeyChainAliasCallback#alias}.
throws
KeyChainException if the alias was valid but there was some problem accessing it.

        if (alias == null) {
            throw new NullPointerException("alias == null");
        }
        KeyChainConnection keyChainConnection = bind(context);
        try {
            final IKeyChainService keyChainService = keyChainConnection.getService();
            final String keyId = keyChainService.requestPrivateKey(alias);
            if (keyId == null) {
                throw new KeyChainException("keystore had a problem");
            }

            final OpenSSLEngine engine = OpenSSLEngine.getInstance("keystore");
            return engine.getPrivateKeyById(keyId);
        } catch (RemoteException e) {
            throw new KeyChainException(e);
        } catch (RuntimeException e) {
            // only certain RuntimeExceptions can be propagated across the IKeyChainService call
            throw new KeyChainException(e);
        } catch (InvalidKeyException e) {
            throw new KeyChainException(e);
        } finally {
            keyChainConnection.close();
        }
    
public static booleanisBoundKeyAlgorithm(java.lang.String algorithm)
Returns {@code true} if the current device's {@code KeyChain} binds any {@code PrivateKey} of the given {@code algorithm} to the device once imported or generated. This can be used to tell if there is special hardware support that can be used to bind keys to the device in a way that makes it non-exportable.

        if (!isKeyAlgorithmSupported(algorithm)) {
            return false;
        }

        return KeyStore.getInstance().isHardwareBacked(algorithm);
    
public static booleanisKeyAlgorithmSupported(java.lang.String algorithm)
Returns {@code true} if the current device's {@code KeyChain} supports a specific {@code PrivateKey} type indicated by {@code algorithm} (e.g., "RSA").

        final String algUpper = algorithm.toUpperCase(Locale.US);
        return "DSA".equals(algUpper) || "EC".equals(algUpper) || "RSA".equals(algUpper);
    
public static java.security.cert.X509CertificatetoCertificate(byte[] bytes)

hide

        if (bytes == null) {
            throw new IllegalArgumentException("bytes == null");
        }
        try {
            CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
            Certificate cert = certFactory.generateCertificate(new ByteArrayInputStream(bytes));
            return (X509Certificate) cert;
        } catch (CertificateException e) {
            throw new AssertionError(e);
        }