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:
// 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, new KeyStore.PasswordProtection(password)); // 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.
@author Jan Luehe
@version 1.53, 07/28/06
@see java.security.PrivateKey
@see javax.crypto.SecretKey
@see java.security.cert.Certificate
@since 1.2