Most visited

Recently visited

Added in API level 1

KeyStore

public class KeyStore
extends Object

java.lang.Object
   ↳ java.security.KeyStore


This class represents a storage facility for cryptographic keys and certificates.

A KeyStore manages different types of entries. Each type of entry implements the KeyStore.Entry interface. Three basic KeyStore.Entry implementations are provided:

Each entry in a keystore is identified by an "alias" string. In the case of private keys and their associated certificate chains, these strings distinguish among the different ways in which the entity may authenticate itself. For example, the entity may authenticate itself using different certificate authorities, or using different public key algorithms.

Whether aliases are case sensitive is implementation dependent. In order to avoid problems, it is recommended not to use aliases in a KeyStore that only differ in case.

Whether keystores are persistent, and the mechanisms used by the keystore if it is persistent, are not specified here. This allows use of a variety of techniques for protecting sensitive (e.g., private or secret) keys. Smart cards or other integrated cryptographic engines (SafeKeyper) are one option, and simpler mechanisms such as files may also be used (in a variety of formats).

Typical ways to request a KeyStore object include relying on the default type and providing a specific keystore type.

Before a keystore can be accessed, it must be loaded.

    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());

    // get user password and file input stream
    char[] password = getPassword();

    java.io.FileInputStream fis = null;
    try {
        fis = new java.io.FileInputStream("keyStoreName");
        ks.load(fis, password);
    } finally {
        if (fis != null) {
            fis.close();
        }
    }
 
To create an empty keystore using the above load method, pass null as the InputStream argument.

Once the keystore has been loaded, it is possible to read existing entries from the keystore, or to write new entries into the keystore:

    KeyStore.ProtectionParameter protParam =
        new KeyStore.PasswordProtection(password);

    // get my private key
    KeyStore.PrivateKeyEntry pkEntry = (KeyStore.PrivateKeyEntry)
        ks.getEntry("privateKeyAlias", protParam);
    PrivateKey myPrivateKey = pkEntry.getPrivateKey();

    // save my secret key
    javax.crypto.SecretKey mySecretKey;
    KeyStore.SecretKeyEntry skEntry =
        new KeyStore.SecretKeyEntry(mySecretKey);
    ks.setEntry("secretKeyAlias", skEntry, protParam);

    // store away the keystore
    java.io.FileOutputStream fos = null;
    try {
        fos = new java.io.FileOutputStream("newKeyStoreName");
        ks.store(fos, password);
    } finally {
        if (fos != null) {
            fos.close();
        }
    }
 
Note that although the same password may be used to load the keystore, to protect the private key entry, to protect the secret key entry, and to store the keystore (as is shown in the sample code above), different passwords or other protection parameters may also be used.

Android provides the following KeyStore types:

Name Supported (API Levels)
AndroidCAStore 14+
AndroidKeyStore 18+
BCPKCS12 1–8
BKS 1+
BouncyCastle 1+
PKCS12 1+
PKCS12-DEF 1–8
These types are described in the KeyStore section of the Java Cryptography Architecture Standard Algorithm Name Documentation.

See also:

Summary

Nested classes

class KeyStore.Builder

A description of a to-be-instantiated KeyStore object. 

class KeyStore.CallbackHandlerProtection

A ProtectionParameter encapsulating a CallbackHandler. 

interface KeyStore.Entry

A marker interface for KeyStore entry types. 

interface KeyStore.LoadStoreParameter

A marker interface for KeyStore load and store parameters. 

class KeyStore.PasswordProtection

A password-based implementation of ProtectionParameter

class KeyStore.PrivateKeyEntry

A KeyStore entry that holds a PrivateKey and corresponding certificate chain. 

interface KeyStore.ProtectionParameter

A marker interface for keystore protection parameters. 

class KeyStore.SecretKeyEntry

A KeyStore entry that holds a SecretKey

class KeyStore.TrustedCertificateEntry

A KeyStore entry that holds a trusted Certificate

Protected constructors

KeyStore(KeyStoreSpi keyStoreSpi, Provider provider, String type)

Creates a KeyStore object of the given type, and encapsulates the given provider implementation (SPI object) in it.

Public methods

final Enumeration<String> aliases()

Lists all the alias names of this keystore.

final boolean containsAlias(String alias)

Checks if the given alias exists in this keystore.

final void deleteEntry(String alias)

Deletes the entry identified by the given alias from this keystore.

final boolean entryInstanceOf(String alias, Class<? extends KeyStore.Entry> entryClass)

Determines if the keystore Entry for the specified alias is an instance or subclass of the specified entryClass.

final Certificate getCertificate(String alias)

Returns the certificate associated with the given alias.

final String getCertificateAlias(Certificate cert)

Returns the (alias) name of the first keystore entry whose certificate matches the given certificate.

final Certificate[] getCertificateChain(String alias)

Returns the certificate chain associated with the given alias.

final Date getCreationDate(String alias)

Returns the creation date of the entry identified by the given alias.

static final String getDefaultType()

Returns the default keystore type as specified in the Java security properties file, or the string "jks" (acronym for "Java keystore") if no such property exists.

final KeyStore.Entry getEntry(String alias, KeyStore.ProtectionParameter protParam)

Gets a keystore Entry for the specified alias with the specified protection parameter.

static KeyStore getInstance(String type)

Returns a keystore object of the specified type.

static KeyStore getInstance(String type, String provider)

Returns a keystore object of the specified type.

static KeyStore getInstance(String type, Provider provider)

Returns a keystore object of the specified type.

final Key getKey(String alias, char[] password)

Returns the key associated with the given alias, using the given password to recover it.

final Provider getProvider()

Returns the provider of this keystore.

final String getType()

Returns the type of this keystore.

final boolean isCertificateEntry(String alias)

Returns true if the entry identified by the given alias was created by a call to setCertificateEntry, or created by a call to setEntry with a TrustedCertificateEntry.

final boolean isKeyEntry(String alias)

Returns true if the entry identified by the given alias was created by a call to setKeyEntry, or created by a call to setEntry with a PrivateKeyEntry or a SecretKeyEntry.

final void load(KeyStore.LoadStoreParameter param)

Loads this keystore using the given LoadStoreParameter.

final void load(InputStream stream, char[] password)

Loads this KeyStore from the given input stream.

final void setCertificateEntry(String alias, Certificate cert)

Assigns the given trusted certificate to the given alias.

final void setEntry(String alias, KeyStore.Entry entry, KeyStore.ProtectionParameter protParam)

Saves a keystore Entry under the specified alias.

final void setKeyEntry(String alias, Key key, char[] password, Certificate[] chain)

Assigns the given key to the given alias, protecting it with the given password.

final void setKeyEntry(String alias, byte[] key, Certificate[] chain)

Assigns the given key (that has already been protected) to the given alias.

final int size()

Retrieves the number of entries in this keystore.

final void store(OutputStream stream, char[] password)

Stores this keystore to the given output stream, and protects its integrity with the given password.

final void store(KeyStore.LoadStoreParameter param)

Stores this keystore using the given LoadStoreParameter.

Inherited methods

From class java.lang.Object

Protected constructors

KeyStore

Added in API level 1
KeyStore (KeyStoreSpi keyStoreSpi, 
                Provider provider, 
                String type)

Creates a KeyStore object of the given type, and encapsulates the given provider implementation (SPI object) in it.

Parameters
keyStoreSpi KeyStoreSpi: the provider implementation.
provider Provider: the provider.
type String: the keystore type.

Public methods

aliases

Added in API level 1
Enumeration<String> aliases ()

Lists all the alias names of this keystore.

Returns
Enumeration<String> enumeration of the alias names
Throws
KeyStoreException if the keystore has not been initialized (loaded).

containsAlias

Added in API level 1
boolean containsAlias (String alias)

Checks if the given alias exists in this keystore.

Parameters
alias String: the alias name
Returns
boolean true if the alias exists, false otherwise
Throws
KeyStoreException if the keystore has not been initialized (loaded).

deleteEntry

Added in API level 1
void deleteEntry (String alias)

Deletes the entry identified by the given alias from this keystore.

Parameters
alias String: the alias name
Throws
KeyStoreException if the keystore has not been initialized, or if the entry cannot be removed.

entryInstanceOf

Added in API level 1
boolean entryInstanceOf (String alias, 
                Class<? extends KeyStore.Entry> entryClass)

Determines if the keystore Entry for the specified alias is an instance or subclass of the specified entryClass.

Parameters
alias String: the alias name
entryClass Class: the entry class
Returns
boolean true if the keystore Entry for the specified alias is an instance or subclass of the specified entryClass, false otherwise
Throws
NullPointerException if alias or entryClass is null
KeyStoreException if the keystore has not been initialized (loaded)

getCertificate

Added in API level 1
Certificate getCertificate (String alias)

Returns the certificate associated with the given alias.

If the given alias name identifies an entry created by a call to setCertificateEntry, or created by a call to setEntry with a TrustedCertificateEntry, then the trusted certificate contained in that entry is returned.

If the given alias name identifies an entry created by a call to setKeyEntry, or created by a call to setEntry with a PrivateKeyEntry, then the first element of the certificate chain in that entry is returned.

Parameters
alias String: the alias name
Returns
Certificate the certificate, or null if the given alias does not exist or does not contain a certificate.
Throws
KeyStoreException if the keystore has not been initialized (loaded).

getCertificateAlias

Added in API level 1
String getCertificateAlias (Certificate cert)

Returns the (alias) name of the first keystore entry whose certificate matches the given certificate.

This method attempts to match the given certificate with each keystore entry. If the entry being considered was created by a call to setCertificateEntry, or created by a call to setEntry with a TrustedCertificateEntry, then the given certificate is compared to that entry's certificate.

If the entry being considered was created by a call to setKeyEntry, or created by a call to setEntry with a PrivateKeyEntry, then the given certificate is compared to the first element of that entry's certificate chain.

Parameters
cert Certificate: the certificate to match with.
Returns
String the alias name of the first entry with a matching certificate, or null if no such entry exists in this keystore.
Throws
KeyStoreException if the keystore has not been initialized (loaded).

getCertificateChain

Added in API level 1
Certificate[] getCertificateChain (String alias)

Returns the certificate chain associated with the given alias. The certificate chain must have been associated with the alias by a call to setKeyEntry, or by a call to setEntry with a PrivateKeyEntry.

Parameters
alias String: the alias name
Returns
Certificate[] the certificate chain (ordered with the user's certificate first followed by zero or more certificate authorities), or null if the given alias does not exist or does not contain a certificate chain
Throws
KeyStoreException if the keystore has not been initialized (loaded).

getCreationDate

Added in API level 1
Date getCreationDate (String alias)

Returns the creation date of the entry identified by the given alias.

Parameters
alias String: the alias name
Returns
Date the creation date of this entry, or null if the given alias does not exist
Throws
KeyStoreException if the keystore has not been initialized (loaded).

getDefaultType

Added in API level 1
String getDefaultType ()

Returns the default keystore type as specified in the Java security properties file, or the string "jks" (acronym for "Java keystore") if no such property exists. The Java security properties file is located in the file named <JAVA_HOME>/lib/security/java.security. <JAVA_HOME> refers to the value of the java.home system property, and specifies the directory where the JRE is installed.

The default keystore type can be used by applications that do not want to use a hard-coded keystore type when calling one of the getInstance methods, and want to provide a default keystore type in case a user does not specify its own.

The default keystore type can be changed by setting the value of the "keystore.type" security property (in the Java security properties file) to the desired keystore type.

Returns
String the default keystore type as specified in the Java security properties file, or the string "jks" if no such property exists.

getEntry

Added in API level 1
KeyStore.Entry getEntry (String alias, 
                KeyStore.ProtectionParameter protParam)

Gets a keystore Entry for the specified alias with the specified protection parameter.

Parameters
alias String: get the keystore Entry for this alias
protParam KeyStore.ProtectionParameter: the ProtectionParameter used to protect the Entry, which may be null
Returns
KeyStore.Entry the keystore Entry for the specified alias, or null if there is no such entry
Throws
NullPointerException if alias is null
NoSuchAlgorithmException if the algorithm for recovering the entry cannot be found
UnrecoverableEntryException if the specified protParam were insufficient or invalid
UnrecoverableKeyException if the entry is a PrivateKeyEntry or SecretKeyEntry and the specified protParam does not contain the information needed to recover the key (e.g. wrong password)
KeyStoreException if the keystore has not been initialized (loaded).

See also:

getInstance

Added in API level 1
KeyStore getInstance (String type)

Returns a keystore object of the specified type.

This method traverses the list of registered security Providers, starting with the most preferred Provider. A new KeyStore object encapsulating the KeyStoreSpi implementation from the first Provider that supports the specified type is returned.

Note that the list of registered providers may be retrieved via the Security.getProviders() method.

Parameters
type String: the type of keystore. See the KeyStore section in the Java Cryptography Architecture Standard Algorithm Name Documentation for information about standard keystore types.
Returns
KeyStore a keystore object of the specified type.
Throws
KeyStoreException if no Provider supports a KeyStoreSpi implementation for the specified type.

See also:

getInstance

Added in API level 1
KeyStore getInstance (String type, 
                String provider)

Returns a keystore object of the specified type.

A new KeyStore object encapsulating the KeyStoreSpi implementation from the specified provider is returned. The specified provider must be registered in the security provider list.

Note that the list of registered providers may be retrieved via the Security.getProviders() method.

Parameters
type String: the type of keystore. See the KeyStore section in the Java Cryptography Architecture Standard Algorithm Name Documentation for information about standard keystore types.
provider String: the name of the provider.
Returns
KeyStore a keystore object of the specified type.
Throws
KeyStoreException if a KeyStoreSpi implementation for the specified type is not available from the specified provider.
NoSuchProviderException if the specified provider is not registered in the security provider list.
IllegalArgumentException if the provider name is null or empty.

See also:

getInstance

Added in API level 1
KeyStore getInstance (String type, 
                Provider provider)

Returns a keystore object of the specified type.

A new KeyStore object encapsulating the KeyStoreSpi implementation from the specified Provider object is returned. Note that the specified Provider object does not have to be registered in the provider list.

Parameters
type String: the type of keystore. See the KeyStore section in the Java Cryptography Architecture Standard Algorithm Name Documentation for information about standard keystore types.
provider Provider: the provider.
Returns
KeyStore a keystore object of the specified type.
Throws
KeyStoreException if KeyStoreSpi implementation for the specified type is not available from the specified Provider object.
IllegalArgumentException if the specified provider is null.

See also:

getKey

Added in API level 1
Key getKey (String alias, 
                char[] password)

Returns the key associated with the given alias, using the given password to recover it. The key must have been associated with the alias by a call to setKeyEntry, or by a call to setEntry with a PrivateKeyEntry or SecretKeyEntry.

Parameters
alias String: the alias name
password char: the password for recovering the key
Returns
Key the requested key, or null if the given alias does not exist or does not identify a key-related entry.
Throws
KeyStoreException if the keystore has not been initialized (loaded).
NoSuchAlgorithmException if the algorithm for recovering the key cannot be found
UnrecoverableKeyException if the key cannot be recovered (e.g., the given password is wrong).

getProvider

Added in API level 1
Provider getProvider ()

Returns the provider of this keystore.

Returns
Provider the provider of this keystore.

getType

Added in API level 1
String getType ()

Returns the type of this keystore.

Returns
String the type of this keystore.

isCertificateEntry

Added in API level 1
boolean isCertificateEntry (String alias)

Returns true if the entry identified by the given alias was created by a call to setCertificateEntry, or created by a call to setEntry with a TrustedCertificateEntry.

Parameters
alias String: the alias for the keystore entry to be checked
Returns
boolean true if the entry identified by the given alias contains a trusted certificate, false otherwise.
Throws
KeyStoreException if the keystore has not been initialized (loaded).

isKeyEntry

Added in API level 1
boolean isKeyEntry (String alias)

Returns true if the entry identified by the given alias was created by a call to setKeyEntry, or created by a call to setEntry with a PrivateKeyEntry or a SecretKeyEntry.

Parameters
alias String: the alias for the keystore entry to be checked
Returns
boolean true if the entry identified by the given alias is a key-related entry, false otherwise.
Throws
KeyStoreException if the keystore has not been initialized (loaded).

load

Added in API level 1
void load (KeyStore.LoadStoreParameter param)

Loads this keystore using the given LoadStoreParameter.

Note that if this KeyStore has already been loaded, it is reinitialized and loaded again from the given parameter.

Parameters
param KeyStore.LoadStoreParameter: the LoadStoreParameter that specifies how to load the keystore, which may be null
Throws
IllegalArgumentException if the given LoadStoreParameter input is not recognized
IOException if there is an I/O or format problem with the keystore data. If the error is due to an incorrect ProtectionParameter (e.g. wrong password) the cause of the IOException should be an UnrecoverableKeyException
NoSuchAlgorithmException if the algorithm used to check the integrity of the keystore cannot be found
CertificateException if any of the certificates in the keystore could not be loaded

load

Added in API level 1
void load (InputStream stream, 
                char[] password)

Loads this KeyStore from the given input stream.

A password may be given to unlock the keystore (e.g. the keystore resides on a hardware token device), or to check the integrity of the keystore data. If a password is not given for integrity checking, then integrity checking is not performed.

In order to create an empty keystore, or if the keystore cannot be initialized from a stream, pass null as the stream argument.

Note that if this keystore has already been loaded, it is reinitialized and loaded again from the given input stream.

Parameters
stream InputStream: the input stream from which the keystore is loaded, or null
password char: the password used to check the integrity of the keystore, the password used to unlock the keystore, or null
Throws
IOException if there is an I/O or format problem with the keystore data, if a password is required but not given, or if the given password was incorrect. If the error is due to a wrong password, the cause of the IOException should be an UnrecoverableKeyException
NoSuchAlgorithmException if the algorithm used to check the integrity of the keystore cannot be found
CertificateException if any of the certificates in the keystore could not be loaded

setCertificateEntry

Added in API level 1
void setCertificateEntry (String alias, 
                Certificate cert)

Assigns the given trusted certificate to the given alias.

If the given alias identifies an existing entry created by a call to setCertificateEntry, or created by a call to setEntry with a TrustedCertificateEntry, the trusted certificate in the existing entry is overridden by the given certificate.

Parameters
alias String: the alias name
cert Certificate: the certificate
Throws
KeyStoreException if the keystore has not been initialized, or the given alias already exists and does not identify an entry containing a trusted certificate, or this operation fails for some other reason.

setEntry

Added in API level 1
void setEntry (String alias, 
                KeyStore.Entry entry, 
                KeyStore.ProtectionParameter protParam)

Saves a keystore Entry under the specified alias. The protection parameter is used to protect the Entry.

If an entry already exists for the specified alias, it is overridden.

Parameters
alias String: save the keystore Entry under this alias
entry KeyStore.Entry: the Entry to save
protParam KeyStore.ProtectionParameter: the ProtectionParameter used to protect the Entry, which may be null
Throws
NullPointerException if alias or entry is null
KeyStoreException if the keystore has not been initialized (loaded), or if this operation fails for some other reason

See also:

setKeyEntry

Added in API level 1
void setKeyEntry (String alias, 
                Key key, 
                char[] password, 
                Certificate[] chain)

Assigns the given key to the given alias, protecting it with the given password.

If the given key is of type java.security.PrivateKey, it must be accompanied by a certificate chain certifying the corresponding public key.

If the given alias already exists, the keystore information associated with it is overridden by the given key (and possibly certificate chain).

Parameters
alias String: the alias name
key Key: the key to be associated with the alias
password char: the password to protect the key
chain Certificate: the certificate chain for the corresponding public key (only required if the given key is of type java.security.PrivateKey).
Throws
KeyStoreException if the keystore has not been initialized (loaded), the given key cannot be protected, or this operation fails for some other reason

setKeyEntry

Added in API level 1
void setKeyEntry (String alias, 
                byte[] key, 
                Certificate[] chain)

Assigns the given key (that has already been protected) to the given alias.

If the protected key is of type java.security.PrivateKey, it must be accompanied by a certificate chain certifying the corresponding public key. If the underlying keystore implementation is of type jks, key must be encoded as an EncryptedPrivateKeyInfo as defined in the PKCS #8 standard.

If the given alias already exists, the keystore information associated with it is overridden by the given key (and possibly certificate chain).

Parameters
alias String: the alias name
key byte: the key (in protected format) to be associated with the alias
chain Certificate: the certificate chain for the corresponding public key (only useful if the protected key is of type java.security.PrivateKey).
Throws
KeyStoreException if the keystore has not been initialized (loaded), or if this operation fails for some other reason.

size

Added in API level 1
int size ()

Retrieves the number of entries in this keystore.

Returns
int the number of entries in this keystore
Throws
KeyStoreException if the keystore has not been initialized (loaded).

store

Added in API level 1
void store (OutputStream stream, 
                char[] password)

Stores this keystore to the given output stream, and protects its integrity with the given password.

Parameters
stream OutputStream: the output stream to which this keystore is written.
password char: the password to generate the keystore integrity check
Throws
KeyStoreException if the keystore has not been initialized (loaded).
IOException if there was an I/O problem with data
NoSuchAlgorithmException if the appropriate data integrity algorithm could not be found
CertificateException if any of the certificates included in the keystore data could not be stored

store

Added in API level 1
void store (KeyStore.LoadStoreParameter param)

Stores this keystore using the given LoadStoreParameter.

Parameters
param KeyStore.LoadStoreParameter: the LoadStoreParameter that specifies how to store the keystore, which may be null
Throws
IllegalArgumentException if the given LoadStoreParameter input is not recognized
KeyStoreException if the keystore has not been initialized (loaded)
IOException if there was an I/O problem with data
NoSuchAlgorithmException if the appropriate data integrity algorithm could not be found
CertificateException if any of the certificates included in the keystore data could not be stored

Hooray!