Java KeyStore Basics
A Java KeyStore is a password-protected file that holds cryptographic keys and certificates. Instead of hard-coding an AES key in your source code or keeping a private key in a loose file, you put it in a keystore, and your program loads it with the java.security.KeyStore class.
This lesson shows what a keystore contains, how to create one with keytool and with Java code, how to read, list and delete entries, and how to load the JDK's own trusted certificates. It ends with a small secrets vault that encrypts app settings with a key kept in a keystore. The encryption parts build on Java Cryptography Basics.
What a Java KeyStore Contains
A keystore is a collection of entries. Every entry has a unique name called an alias, and the entry type decides what it holds.
| Entry type | Java class | Holds | Typical use |
|---|---|---|---|
| Private key entry | KeyStore.PrivateKeyEntry | Private key + its certificate chain | A server's TLS identity, code signing |
| Secret key entry | KeyStore.SecretKeyEntry | Symmetric key (AES, HMAC) | Encrypting data, signing tokens |
| Trusted certificate entry | KeyStore.TrustedCertificateEntry | A certificate you trust (no private key) | Trusting a CA or a partner's server |
Keystores come in several formats. Since Java 9 the default is PKCS12, an industry standard that other tools such as OpenSSL can read.
| Format | Status | Notes |
|---|---|---|
PKCS12 | Default since Java 9 | Standard format, file extension .p12 or .pfx |
JKS | Legacy | Old Java-only format; still readable |
JCEKS | Legacy | Old Java format that added secret keys |
Note: A file that holds only trusted certificates is often called a truststore. It is still a keystore; the name only describes its job.
Create a Java KeyStore With keytool
The JDK ships with keytool, a command-line tool for managing keystores. The command below creates a new PKCS12 keystore with an EC key pair and a self-signed certificate for localhost.
keytool -genkeypair \
-alias server \
-keyalg EC -groupname secp256r1 \
-dname "CN=localhost" \
-ext SAN=dns:localhost,ip:127.0.0.1 \
-validity 365 \
-keystore server.p12 -storetype PKCS12 \
-storepass changeit
Now list what the keystore contains:
keytool -list -keystore server.p12 -storepass changeit
Output:
Keystore type: PKCS12
Keystore provider: SUN
Your keystore contains 1 entry
server, Nov 17, 2026, PrivateKeyEntry,
Certificate fingerprint (SHA-256): 5D:FC:BA:13:...:9F:72:DB
How it works:
-genkeypaircreates a private key and wraps the public key in a certificate signed by that same private key (a self-signed certificate).-alias serveris the name you will use to find the entry later.-dnamesets the certificate subject, and-ext SAN=...lists the host names the certificate is valid for.-storepassis the keystore password. In PKCS12 files created bykeytool, the key password is the same as the store password.
Note: On Windows, write the command on one line or replace each