Class KeyStore
- java.lang.Object
-
- java.security.KeyStore
-
public class KeyStore extends java.lang.ObjectThis class represents a storage facility for cryptographic keys and certificates.A
KeyStoremanages different types of entries. Each type of entry implements theKeyStore.Entryinterface. Three basicKeyStore.Entryimplementations 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
Certificatebelonging 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 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.
- 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
loaded.KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); // get user password and file input stream char[] password = getPassword(); try (FileInputStream fis = new FileInputStream("keyStoreName")) { ks.load(fis, password); }To create an empty keystore using the aboveloadmethod, passnullas theInputStreamargument.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 try (FileOutputStream fos = new FileOutputStream("newKeyStoreName")) { ks.store(fos, password); }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.Every implementation of the Java platform is required to support the following standard
KeyStoretype:PKCS12
- Since:
- 1.2
- See Also:
Certificate
- KeyStore.PrivateKeyEntry
-
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description java.util.Enumeration<java.lang.String>aliases()Lists all the alias names of this keystore.booleancontainsAlias(java.lang.String alias)Checks if the given alias exists in this keystore.voiddeleteEntry(java.lang.String alias)Deletes the entry identified by the given alias from this keystore.CertificategetCertificate(java.lang.String alias)Returns the certificate associated with the given alias.Certificate[]getCertificateChain(java.lang.String alias)Returns the certificate chain associated with the given alias.static java.lang.StringgetDefaultType()Returns the default keystore type as specified by thekeystore.typesecurity property, or the string "jks" (acronym for "Java keystore") if no such property exists.static KeyStoregetInstance(java.lang.String type)Returns a keystore object of the specified type.KeygetKey(java.lang.String alias, char[] password)Returns the key associated with the given alias, using the given password to recover it.java.lang.StringgetType()Returns the type of this keystore.booleanisCertificateEntry(java.lang.String alias)Returns true if the entry identified by the given alias was created by a call tosetCertificateEntry, or created by a call tosetEntrywith aTrustedCertificateEntry.booleanisKeyEntry(java.lang.String alias)Returns true if the entry identified by the given alias was created by a call tosetKeyEntry, or created by a call tosetEntrywith aPrivateKeyEntryor aSecretKeyEntry.voidload(java.io.InputStream stream, char[] password)Loads this KeyStore from the given input stream.voidsetCertificateEntry(java.lang.String alias, Certificate cert)Assigns the given trusted certificate to the given alias.voidsetKeyEntry(java.lang.String alias, byte[] key, Certificate[] chain)Assigns the given key (that has already been protected) to the given alias.voidsetKeyEntry(java.lang.String alias, Key key, char[] password, Certificate[] chain)Assigns the given key to the given alias, protecting it with the given password.intsize()Retrieves the number of entries in this keystore.
-
-
-
Method Detail
-
getInstance
public static KeyStore getInstance(java.lang.String type) throws KeyStoreException
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.
- Parameters:
type- the type of keystore. See the KeyStore section in the Java Security Standard Algorithm Names Specification for information about standard keystore types. Consult the release documentation for your implementation to see which types are supported.- Returns:
- a keystore object of the specified type.
- Throws:
KeyStoreException- if no Provider supports a KeyStoreSpi implementation for the specified type.
-
getDefaultType
public static final java.lang.String getDefaultType()
Returns the default keystore type as specified by thekeystore.typesecurity property, or the string "jks" (acronym for "Java keystore") if no such property exists.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
getInstancemethods, 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.typesecurity property to the desired keystore type.- Returns:
- the default keystore type as specified by the
keystore.typesecurity property, or the string "jks" if no such property exists.
-
getType
public final java.lang.String getType()
Returns the type of this keystore.- Returns:
- the type of this keystore.
-
getKey
@Nullable public final Key getKey(java.lang.String alias, char[] password) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException
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 tosetKeyEntry, or by a call tosetEntrywith aPrivateKeyEntryorSecretKeyEntry.- Parameters:
alias- the alias namepassword- the password for recovering the key- Returns:
- 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 foundUnrecoverableKeyException- if the key cannot be recovered (e.g., the given password is wrong).
-
getCertificateChain
@Nullable public final Certificate[] getCertificateChain(java.lang.String alias) throws KeyStoreException
Returns the certificate chain associated with the given alias. The certificate chain must have been associated with the alias by a call tosetKeyEntry, or by a call tosetEntrywith aPrivateKeyEntry.- Parameters:
alias- the alias name- Returns:
- 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).
-
getCertificate
@Nullable public final Certificate getCertificate(java.lang.String alias) throws KeyStoreException
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 tosetEntrywith aTrustedCertificateEntry, 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 tosetEntrywith aPrivateKeyEntry, then the first element of the certificate chain in that entry is returned.- Parameters:
alias- the alias name- Returns:
- 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).
-
setKeyEntry
public final void setKeyEntry(java.lang.String alias, byte[] key, Certificate[] chain) throws KeyStoreExceptionAssigns 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 typejks,keymust be encoded as anEncryptedPrivateKeyInfoas 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- the alias namekey- the key (in protected format) to be associated with the aliaschain- the certificate chain for the corresponding public key (only useful if the protected key is of typejava.security.PrivateKey).- Throws:
KeyStoreException- if the keystore has not been initialized (loaded), or if this operation fails for some other reason.
-
setKeyEntry
public final void setKeyEntry(java.lang.String alias, Key key, char[] password, Certificate[] chain) throws KeyStoreExceptionAssigns 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- the alias namekey- the key to be associated with the aliaspassword- the password to protect the keychain- the certificate chain for the corresponding public key (only required if the given key is of typejava.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
-
setCertificateEntry
public final void setCertificateEntry(java.lang.String alias, Certificate cert) throws KeyStoreExceptionAssigns 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 tosetEntrywith aTrustedCertificateEntry, the trusted certificate in the existing entry is overridden by the given certificate.- Parameters:
alias- the alias namecert- 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.
-
deleteEntry
public final void deleteEntry(java.lang.String alias) throws KeyStoreExceptionDeletes the entry identified by the given alias from this keystore.- Parameters:
alias- the alias name- Throws:
KeyStoreException- if the keystore has not been initialized, or if the entry cannot be removed.
-
aliases
public final java.util.Enumeration<java.lang.String> aliases() throws KeyStoreExceptionLists all the alias names of this keystore.- Returns:
- enumeration of the alias names
- Throws:
KeyStoreException- if the keystore has not been initialized (loaded).
-
containsAlias
public final boolean containsAlias(java.lang.String alias) throws KeyStoreExceptionChecks if the given alias exists in this keystore.- Parameters:
alias- the alias name- Returns:
- true if the alias exists, false otherwise
- Throws:
KeyStoreException- if the keystore has not been initialized (loaded).
-
size
public final int size() throws KeyStoreExceptionRetrieves the number of entries in this keystore.- Returns:
- the number of entries in this keystore
- Throws:
KeyStoreException- if the keystore has not been initialized (loaded).
-
isKeyEntry
public final boolean isKeyEntry(java.lang.String alias) throws KeyStoreExceptionReturns true if the entry identified by the given alias was created by a call tosetKeyEntry, or created by a call tosetEntrywith aPrivateKeyEntryor aSecretKeyEntry.- Parameters:
alias- the alias for the keystore entry to be checked- Returns:
- 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).
-
isCertificateEntry
public final boolean isCertificateEntry(java.lang.String alias) throws KeyStoreExceptionReturns true if the entry identified by the given alias was created by a call tosetCertificateEntry, or created by a call tosetEntrywith aTrustedCertificateEntry.- Parameters:
alias- the alias for the keystore entry to be checked- Returns:
- 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).
-
load
public final void load(@Nullable java.io.InputStream stream, @Nullable char[] password) throws java.io.IOException, NoSuchAlgorithmException, CertificateExceptionLoads 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
nullas thestreamargument.Note that if this keystore has already been loaded, it is reinitialized and loaded again from the given input stream.
- Parameters:
stream- the input stream from which the keystore is loaded, ornullpassword- the password used to check the integrity of the keystore, the password used to unlock the keystore, ornull- Throws:
java.io.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, thecauseof theIOExceptionshould be anUnrecoverableKeyExceptionNoSuchAlgorithmException- if the algorithm used to check the integrity of the keystore cannot be foundCertificateException- if any of the certificates in the keystore could not be loaded
-
-