FileDocCategorySizeDatePackage
KeyStore.javaAPI DocJava SE 5 API54379Fri Aug 26 14:57:14 BST 2005java.security

KeyStore

public class KeyStore extends Object
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:

  • KeyStore.PrivateKeyEntry

    This type of entry holds a cryptographic PrivateKey, which is optionally stored in a protected format to prevent unauthorized access. It is also accompanied by a certificate chain for the corresponding public key.

    Private keys and certificate chains are used by a given entity for self-authentication. Applications for this authentication include software distribution organizations which sign JAR files as part of releasing and/or licensing software.

  • KeyStore.SecretKeyEntry

    This type of entry holds a cryptographic SecretKey, which is optionally stored in a protected format to prevent unauthorized access.

  • KeyStore.TrustedCertificateEntry

    This type of entry contains a single public key Certificate belonging to another party. It is called a trusted certificate because the keystore owner trusts that the public key in the certificate indeed belongs to the identity identified by the subject (owner) of the certificate.

    This type of entry can be used to authenticate other parties.

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 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.

  • To rely on the default type:
    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    
    The system will return a keystore implementation for the default type.

  • To provide a specific keystore type:
    KeyStore ks = KeyStore.getInstance("JKS");
    
    The system will return the most preferred implementation of the specified keystore type available in the environment.

Before a keystore can be accessed, it must be {@link #load(java.io.InputStream, char[]) loaded}.

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

// get user password and file input stream
char[] password = getPassword();
java.io.FileInputStream fis =
new java.io.FileInputStream("keyStoreName");
ks.load(fis, password);
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:

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

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

// store away the keystore
java.io.FileOutputStream fos =
new java.io.FileOutputStream("newKeyStoreName");
ks.store(fos, password);
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.
author
Jan Luehe
version
1.42, 06/28/04
see
java.security.PrivateKey
see
javax.crypto.SecretKey
see
java.security.cert.Certificate
since
1.2

Fields Summary
private static final String
KEYSTORE_TYPE
private String
type
private Provider
provider
private KeyStoreSpi
keyStoreSpi
private boolean
initialized
Constructors Summary
protected 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.

param
keyStoreSpi the provider implementation.
param
provider the provider.
param
type the keystore type.

	this.keyStoreSpi = keyStoreSpi;
	this.provider = provider;
	this.type = type;
    
Methods Summary
public final java.util.Enumerationaliases()
Lists all the alias names of this keystore.

return
enumeration of the alias names
exception
KeyStoreException if the keystore has not been initialized (loaded).

	if (!initialized) {
	    throw new KeyStoreException("Uninitialized keystore");
	}
	return keyStoreSpi.engineAliases();
    
public final booleancontainsAlias(java.lang.String alias)
Checks if the given alias exists in this keystore.

param
alias the alias name
return
true if the alias exists, false otherwise
exception
KeyStoreException if the keystore has not been initialized (loaded).

	if (!initialized) {
	    throw new KeyStoreException("Uninitialized keystore");
	}
	return keyStoreSpi.engineContainsAlias(alias);
    
public final voiddeleteEntry(java.lang.String alias)
Deletes the entry identified by the given alias from this keystore.

param
alias the alias name
exception
KeyStoreException if the keystore has not been initialized, or if the entry cannot be removed.

	if (!initialized) {
	    throw new KeyStoreException("Uninitialized keystore");
	}
	keyStoreSpi.engineDeleteEntry(alias);
    
public final booleanentryInstanceOf(java.lang.String alias, java.lang.Class entryClass)
Determines if the keystore Entry for the specified alias is an instance or subclass of the specified entryClass.

param
alias the alias name
param
entryClass the entry class
return
true if the keystore Entry for the specified alias is an instance or subclass of the specified entryClass, false otherwise
exception
NullPointerException if alias or entryClass is null
exception
KeyStoreException if the keystore has not been initialized (loaded)
since
1.5


	if (alias == null || entryClass == null) {
	    throw new NullPointerException("invalid null input");
	}
	if (!initialized) {
	    throw new KeyStoreException("Uninitialized keystore");
	}
	return keyStoreSpi.engineEntryInstanceOf(alias, entryClass);
    
public final java.security.cert.CertificategetCertificate(java.lang.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.

param
alias the alias name
return
the certificate, or null if the given alias does not exist or does not contain a certificate.
exception
KeyStoreException if the keystore has not been initialized (loaded).

	if (!initialized) {
	    throw new KeyStoreException("Uninitialized keystore");
	}
	return keyStoreSpi.engineGetCertificate(alias);
    
public final java.lang.StringgetCertificateAlias(java.security.cert.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.

param
cert the certificate to match with.
return
the alias name of the first entry with a matching certificate, or null if no such entry exists in this keystore.
exception
KeyStoreException if the keystore has not been initialized (loaded).

	if (!initialized) {
	    throw new KeyStoreException("Uninitialized keystore");
	}
	return keyStoreSpi.engineGetCertificateAlias(cert);
    
public final java.security.cert.Certificate[]getCertificateChain(java.lang.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.

param
alias the alias name
return
the certificate chain (ordered with the user's certificate first and the root certificate authority last), or null if the given alias does not exist or does not contain a certificate chain
exception
KeyStoreException if the keystore has not been initialized (loaded).

	if (!initialized) {
	    throw new KeyStoreException("Uninitialized keystore");
	}
	return keyStoreSpi.engineGetCertificateChain(alias);
    
public final java.util.DategetCreationDate(java.lang.String alias)
Returns the creation date of the entry identified by the given alias.

param
alias the alias name
return
the creation date of this entry, or null if the given alias does not exist
exception
KeyStoreException if the keystore has not been initialized (loaded).

	if (!initialized) {
	    throw new KeyStoreException("Uninitialized keystore");
	}
	return keyStoreSpi.engineGetCreationDate(alias);
    
public static final java.lang.StringgetDefaultType()
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, where <JAVA_HOME> refers to the directory where the JDK was 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.

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

	String kstype;
	kstype = (String)AccessController.doPrivileged(new PrivilegedAction() {
	    public Object run() {
		return Security.getProperty(KEYSTORE_TYPE);
	    }
	});
	if (kstype == null) {
	    kstype = "jks";
	}
	return kstype;
    
public final java.security.KeyStore$EntrygetEntry(java.lang.String alias, java.security.KeyStore$ProtectionParameter protParam)
Gets a keystore Entry for the specified alias with the specified protection parameter.

param
alias get the keystore Entry for this alias
param
protParam the ProtectionParameter used to protect the Entry, which may be null
return
the keystore Entry for the specified alias, or null if there is no such entry
exception
NullPointerException if alias is null
exception
NoSuchAlgorithmException if the algorithm for recovering the entry cannot be found
exception
UnrecoverableEntryException if the specified protParam were insufficient or invalid
exception
KeyStoreException if the keystore has not been initialized (loaded).
see
#setEntry(String, KeyStore.Entry, KeyStore.ProtectionParameter)
since
1.5


	if (alias == null) {
	    throw new NullPointerException("invalid null input");
	}
	if (!initialized) {
	    throw new KeyStoreException("Uninitialized keystore");
	}
	return keyStoreSpi.engineGetEntry(alias, protParam);
    
public static java.security.KeyStoregetInstance(java.lang.String type)
Generates a keystore object of the given type.

If the default provider package provides a keystore implementation of the given type, an instance of KeyStore containing that implementation is returned. If the requested keystore type is not available in the default package, other packages are searched.

param
type the type of keystore. See Appendix A in the Java Cryptography Architecture API Specification & Reference for information about standard keystore types.
return
a keystore object of the specified type.
exception
KeyStoreException if the requested keystore type is not available in the default provider package or any of the other provider packages that were searched.

	try {
	    Object[] objs = Security.getImpl(type, "KeyStore", (String)null);
	    return new KeyStore((KeyStoreSpi)objs[0], (Provider)objs[1], type);
	} catch (NoSuchAlgorithmException nsae) {
	    throw new KeyStoreException(type + " not found");
	} catch (NoSuchProviderException nspe) {
	    throw new KeyStoreException(type + " not found");
	}
    
public static java.security.KeyStoregetInstance(java.lang.String type, java.lang.String provider)
Generates a keystore object for the specified keystore type from the specified provider.

param
type the type of keystore. See Appendix A in the Java Cryptography Architecture API Specification & Reference for information about standard keystore types.
param
provider the name of the provider.
return
a keystore object of the specified type, as supplied by the specified provider.
exception
KeyStoreException if the requested keystore type is not available from the provider.
exception
NoSuchProviderException if the provider has not been configured.
exception
IllegalArgumentException if the provider name is null or empty.
see
Provider

	if (provider == null || provider.length() == 0)
	    throw new IllegalArgumentException("missing provider");
	try {
	    Object[] objs = Security.getImpl(type, "KeyStore", provider);
	    return new KeyStore((KeyStoreSpi)objs[0], (Provider)objs[1], type);
	} catch (NoSuchAlgorithmException nsae) {
	    throw new KeyStoreException(type + " not found");
	}
    
public static java.security.KeyStoregetInstance(java.lang.String type, java.security.Provider provider)
Generates a keystore object for the specified keystore type from the specified provider. Note: the provider doesn't have to be registered.

param
type the type of keystore. See Appendix A in the Java Cryptography Architecture API Specification & Reference for information about standard keystore types.
param
provider the provider.
return
a keystore object of the specified type, as supplied by the specified provider.
exception
KeyStoreException if the requested keystore type is not available from the provider.
exception
IllegalArgumentException if the provider is null.
see
Provider
since
1.4

	if (provider == null)
	    throw new IllegalArgumentException("missing provider");
	try {
	    Object[] objs = Security.getImpl(type, "KeyStore", provider);
	    return new KeyStore((KeyStoreSpi)objs[0], (Provider)objs[1], type);
	} catch (NoSuchAlgorithmException nsae) {
	    throw new KeyStoreException(type + " not found");
	}
    
public final java.security.KeygetKey(java.lang.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.

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

	if (!initialized) {
	    throw new KeyStoreException("Uninitialized keystore");
	}
	return keyStoreSpi.engineGetKey(alias, password);
    
public final java.security.ProvidergetProvider()
Returns the provider of this keystore.

return
the provider of this keystore.

	return this.provider;
    
public final java.lang.StringgetType()
Returns the type of this keystore.

return
the type of this keystore.

	return this.type;
    
public final booleanisCertificateEntry(java.lang.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.

param
alias the alias for the keystore entry to be checked
return
true if the entry identified by the given alias contains a trusted certificate, false otherwise.
exception
KeyStoreException if the keystore has not been initialized (loaded).

	if (!initialized) {
	    throw new KeyStoreException("Uninitialized keystore");
	}
	return keyStoreSpi.engineIsCertificateEntry(alias);
    
public final booleanisKeyEntry(java.lang.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.

param
alias the alias for the keystore entry to be checked
return
true if the entry identified by the given alias is a key-related entry, false otherwise.
exception
KeyStoreException if the keystore has not been initialized (loaded).

	if (!initialized) {
	    throw new KeyStoreException("Uninitialized keystore");
	}
	return keyStoreSpi.engineIsKeyEntry(alias);
    
public final voidload(java.io.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.

param
stream the input stream from which the keystore is loaded, or null
param
password the password used to check the integrity of the keystore, the password used to unlock the keystore, or null
exception
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
exception
NoSuchAlgorithmException if the algorithm used to check the integrity of the keystore cannot be found
exception
CertificateException if any of the certificates in the keystore could not be loaded

	keyStoreSpi.engineLoad(stream, password);
	initialized = true;
    
public final voidload(java.security.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.

param
param the LoadStoreParameter that specifies how to load the keystore, which may be null
exception
IllegalArgumentException if the given LoadStoreParameter input is not recognized
exception
IOException if there is an I/O or format problem with the keystore data
exception
NoSuchAlgorithmException if the algorithm used to check the integrity of the keystore cannot be found
exception
CertificateException if any of the certificates in the keystore could not be loaded
since
1.5


	keyStoreSpi.engineLoad(param);
	initialized = true;
    
public final voidsetCertificateEntry(java.lang.String alias, java.security.cert.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.

param
alias the alias name
param
cert the certificate
exception
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.

	if (!initialized) {
	    throw new KeyStoreException("Uninitialized keystore");
	}
	keyStoreSpi.engineSetCertificateEntry(alias, cert);
    
public final voidsetEntry(java.lang.String alias, java.security.KeyStore$Entry entry, java.security.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.

param
alias save the keystore Entry under this alias
param
entry the Entry to save
param
protParam the ProtectionParameter used to protect the Entry, which may be null
exception
NullPointerException if alias or entry is null
exception
KeyStoreException if the keystore has not been initialized (loaded), or if this operation fails for some other reason
see
#getEntry(String, KeyStore.ProtectionParameter)
since
1.5

	if (alias == null || entry == null) {
	    throw new NullPointerException("invalid null input");
	}
	if (!initialized) {
	    throw new KeyStoreException("Uninitialized keystore");
	}
	keyStoreSpi.engineSetEntry(alias, entry, protParam);
    
public final voidsetKeyEntry(java.lang.String alias, java.security.Key key, char[] password, java.security.cert.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).

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

	if (!initialized) {
	    throw new KeyStoreException("Uninitialized keystore");
	}
	if ((key instanceof PrivateKey) && 
	    (chain == null || chain.length == 0)) {
	    throw new IllegalArgumentException("Private key must be "
					       + "accompanied by certificate "
					       + "chain");
	}
	keyStoreSpi.engineSetKeyEntry(alias, key, password, chain);
    
public final voidsetKeyEntry(java.lang.String alias, byte[] key, java.security.cert.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).

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

	if (!initialized) {
	    throw new KeyStoreException("Uninitialized keystore");
	}
	keyStoreSpi.engineSetKeyEntry(alias, key, chain);
    
public final intsize()
Retrieves the number of entries in this keystore.

return
the number of entries in this keystore
exception
KeyStoreException if the keystore has not been initialized (loaded).

	if (!initialized) {
	    throw new KeyStoreException("Uninitialized keystore");
	}
	return keyStoreSpi.engineSize();
    
public final voidstore(java.io.OutputStream stream, char[] password)
Stores this keystore to the given output stream, and protects its integrity with the given password.

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

	if (!initialized) {
	    throw new KeyStoreException("Uninitialized keystore");
	}
	keyStoreSpi.engineStore(stream, password);
    
public final voidstore(java.security.KeyStore$LoadStoreParameter param)
Stores this keystore using the given LoadStoreParameter.

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

	if (!initialized) {
	    throw new KeyStoreException("Uninitialized keystore");
	}
	keyStoreSpi.engineStore(param);