KeyStore (Java SE 9 & JDK 9 ) (original) (raw)

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:

The system will return a keystore implementation for the default type.  
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 beloaded (unless it was already loaded during instantiation).
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 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
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 KeyStore type: