Keyboard Shortcuts N Next post
P Previous post
S Save / unsave
R Read aloud
T Toggle theme
/ Focus search
Esc Close panels
🔥
Ready to read...
Cryptography Cryptography Tutorial Java Java and Cryptography Mastery Series — Extended Module 15 - Digital Signatures and PKI

Java Program Using keytool Command for Key Management

Reviewed & accurate
AI Summary

Introduction

The keytool command has shipped with every Oracle JDK and OpenJDK distribution since JDK 1.2 in December 1998. It is the command-line front end to the java.security.KeyStore API and was originally designed so system administrators could create and manage X.509 certificate keystores without writing a single line of Java. The keytool command for Key Management matters today because the same binary still creates the PKCS12 keystores that back TLS endpoints in Tomcat, Jetty, Spring Boot, and the Android APK signing process. A Java learner should care because keytool is the easiest way to materialise a real RSA, DSA, or EC keypair onto disk that you can then load with KeyStore.getInstance("PKCS12") in your own code.

This tutorial shows two parallel approaches. The first half invokes the actual keytool binary from a Java program using ProcessBuilder, captures stdout and stderr, and parses the -list output to enumerate keystore entries. The second half uses only the standard java.security.KeyStore and java.security.KeyPairGenerator APIs to do exactly what keytool does at the source level, so the same lesson applies even on a JVM where the binary is missing.

What is the keytool Command?

keytool is a JDK-supplied command-line utility for managing cryptographic keystores. A keystore is a password-protected database that maps an alias string to either a private key entry (private key plus its certificate chain) or a trusted certificate entry (just a public-key certificate). keytool subcommands include -genkeypair to create a fresh RSA or EC keypair, -certreq to emit a PKCS10 certificate signing request, -exportcert to write a DER or PEM certificate, -importcert to install a trusted certificate, -list to enumerate entries, and -storepasswd to change the keystore password.

keytool is not a separate cryptographic provider: it delegates all maths to the same java.security and javax.crypto providers that your application code uses. That means a keypair you create with keytool -genkeypair -keyalg RSA -keysize 2048 is byte-for-byte equivalent to a keypair you create with KeyPairGenerator.getInstance("RSA").initialize(2048) in Java. The command is convenience, not a different algorithm.

Since JDK 9 the default keystore type changed from the proprietary JKS to the standard PKCS12, so cross-tool compatibility with OpenSSL and Windows Certificate Manager is now the default. keytool still understands JKS files for backward compatibility, but new files are PKCS12 unless you pass -storetype JKS.

How keytool Works - Step by Step

Step 1: Pick a keystore location. keytool reads and writes one file at a time, identified by the -keystore path. If the file does not exist on a -genkeypair call, keytool creates it. The keystore password, passed with -storepass, encrypts the entire file; an additional -keypass per entry protects each private key, although in PKCS12 the two are usually the same.

Step 2: Generate a keypair. The command keytool -genkeypair -alias server -keyalg RSA -keysize 2048 -sigalg SHA256withRSA -validity 365 -keystore server.p12 -storepass changeit asks the JDK provider for an RSA 2048-bit keypair, hashes the X.500 distinguished name you supply, builds a self-signed X.509 v3 certificate valid for 365 days, signs it with the new private key, and stores both the private key and the self-signed certificate under the alias "server" in server.p12.

Step 3: Build a CSR. keytool -certreq -alias server -file server.csr -keystore server.p12 -storepass changeit reads the private key under the alias, encodes the subject DN, the public key, and an extensionRequest attribute into a PKCS10 CertificationRequest, signs it with the private key, and writes the PEM-armoured CSR to server.csr. You send that file to a certificate authority such as Let's Encrypt or DigiCert.

Step 4: Import the CA reply. keytool -importcert -alias server -file server-chain.pem -keystore server.p12 -storepass changeit replaces the self-signed certificate under the alias with the full chain leaf, intermediate, root that the CA sent back. keytool validates that the chain terminates at a trusted certificate already in the keystore (or in the JVM cacerts file).

Step 5: List and inspect. keytool -list -v -keystore server.p12 -storepass changeit walks every alias, prints the creation date, the entry type (PrivateKeyEntry or TrustedCertEntry), and a verbose dump of each certificate including the X.500 subject, X.500 issuer, serial number, validity window, and signature algorithm.

Java Program for keytool

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.util.Enumeration;

public class KeytoolBasicsDemo {

    // Location of the JDK keytool binary, derived from java.home.
    static final String KEYTOOL = System.getProperty("java.home")
            + File.separator + "bin" + File.separator + "keytool";

    public static void main(String[] args) throws Exception {
        String ksPath = "demo.p12";
        String storePass = "changeit";
        String alias = "server";
        String dn = "CN=imcseian.com, OU=Engineering, O=IMCSEIAN, L=Bengaluru, ST=Karnataka, C=IN";

        // Step 1: invoke keytool -genkeypair to create a real keystore.
        String[] genkeypair = {
            KEYTOOL,
            "-genkeypair",
            "-alias", alias,
            "-keyalg", "RSA",
            "-keysize", "2048",
            "-sigalg", "SHA256withRSA",
            "-validity", "365",
            "-dname", dn,
            "-keystore", ksPath,
            "-storetype", "PKCS12",
            "-storepass", storePass
        };
        System.out.println("==> keytool -genkeypair");
        System.out.println(run(genkeypair));

        // Step 2: invoke keytool -list to print the entries.
        String[] listCmd = {
            KEYTOOL,
            "-list",
            "-v",
            "-keystore", ksPath,
            "-storepass", storePass
        };
        System.out.println("==> keytool -list -v");
        System.out.println(run(listCmd));

        // Step 3: load the keystore through the Java KeyStore API
        //         and confirm that keytool and the API see the same data.
        KeyStore ks = KeyStore.getInstance("PKCS12");
        try (var in = java.io.FileInputStream.class.getConstructor(String.class).newInstance(ksPath)) {
            ks.load(in, storePass.toCharArray());
        }
        System.out.println("==> Java KeyStore API view");
        System.out.println("Provider:    " + ks.getProvider());
        System.out.println("Type:        " + ks.getType());
        System.out.println("Size:        " + ks.size());
        Enumeration<String> aliases = ks.aliases();
        while (aliases.hasMoreElements()) {
            String a = aliases.nextElement();
            System.out.println("Alias:       " + a);
            System.out.println("  Created:    " + ks.getCreationDate(a));
            if (ks.isKeyEntry(a)) {
                Certificate[] chain = ks.getCertificateChain(a);
                X509Certificate leaf = (X509Certificate) chain[0];
                System.out.println("  Subject:    " + leaf.getSubjectX500Principal());
                System.out.println("  Issuer:     " + leaf.getIssuerX500Principal());
                System.out.println("  Not before: " + leaf.getNotBefore());
                System.out.println("  Not after:  " + leaf.getNotAfter());
                System.out.println("  Sig alg:    " + leaf.getSigAlgName());
            }
        }

        // Step 4: equivalent pure-Java keypair generation that produces
        //         the same kind of RSA 2048-bit keypair, without keytool.
        KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
        kpg.initialize(2048);
        KeyPair kp = kpg.generateKeyPair();
        System.out.println("==> Pure Java KeyPairGenerator");
        System.out.println("Public key algorithm:  " + kp.getPublic().getAlgorithm());
        System.out.println("Public key format:     " + kp.getPublic().getFormat());
        System.out.println("Public key length:     " + (kp.getPublic().getEncoded().length * 8) + " bits");

        // Cleanup.
        new File(ksPath).delete();
    }

    static String run(String[] cmd) throws Exception {
        ProcessBuilder pb = new ProcessBuilder(cmd);
        pb.redirectErrorStream(true);
        Process p = pb.start();
        StringBuilder out = new StringBuilder();
        try (BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()))) {
            String line;
            while ((line = r.readLine()) != null) {
                out.append(line).append('\n');
            }
        }
        int code = p.waitFor();
        if (code != 0) {
            out.append("Exit code: ").append(code).append('\n');
        }
        return out.toString();
    }
}

Code Explanation - Line by Line

The KEYTOOL constant uses the java.home system property to find the JDK installation directory, then appends bin/keytool (or bin/keytool.exe on Windows automatically because File.separator is platform-aware). This trick lets the same program locate the binary on Linux, macOS, and Windows without any environment probing.

The run() helper wraps ProcessBuilder with redirectErrorStream(true) so that the merged stdout and stderr streams are read line by line. We deliberately do not throw on a non-zero exit code because keytool prints a human-readable diagnostic to stderr that we want to surface to the caller.

In step 3 we load the same demo.p12 keystore through the standard KeyStore.getInstance("PKCS12") API. The try-with-resources around FileInputStream uses reflection to construct the stream so we do not add an extra import line, but in production code you would simply write try (var in = new java.io.FileInputStream(ksPath)). The aliases() enumeration is the API equivalent of keytool -list.

In step 4 we generate the same RSA 2048-bit keypair through KeyPairGenerator. The getEncoded() call returns the SubjectPublicKeyInfo in DER format, which is 294 bytes for a 2048-bit RSA public key (the extra 22 bytes are the ASN.1 wrapper around the 2704-bit modulus and exponent).

Sample Input and Output

==> keytool -genkeypair
Generated 2048-bit RSA key pair and self-signed certificate (SHA256withRSA)
with a validity of 365 days for: CN=imcseian.com, OU=Engineering, O=IMCSEIAN,
L=Bengaluru, ST=Karnataka, C=IN

==> keytool -list -v
Keystore type: PKCS12
Keystore provider: SUN

Your keystore contains 1 entry

Alias name: server
Creation date: ...
Entry type: PrivateKeyEntry
...

The output proves that keytool and the KeyStore API see the same data: both report one PrivateKeyEntry under alias "server", both expose the X.500 subject and issuer strings, and the validity window starts from the moment of keypair generation. The pure-Java step confirms that the public key is 2048-bit RSA in SubjectPublicKeyInfo format.

Common Mistakes to Avoid

First, never type the keystore password on the command line in production. The command line is visible to every other process through /proc/PID/cmdline on Linux and through Task Manager on Windows. Use the -storepass:env FOO form to read the password from an environment variable, or -storepass:file /etc/secrets/storepass to read it from a protected file. Second, do not forget to pass -storetype PKCS12 on Java 8 and earlier; on those versions the default is still JKS, which is incompatible with OpenSSL unless you convert. Third, do not confuse -storepasswd with -keypasswd: the first re-encrypts the entire keystore file, the second only re-wraps a single private key entry. Finally, do not expect -validity 36500 (100 years) to work in every CA's policy: public CAs cap at 397 days for publicly trusted server certificates, so 100-year certificates are only useful for internal trust anchors.

Real-World Applications

Every Spring Boot application that exposes HTTPS uses a keystore that was created with keytool or OpenSSL. Tomcat's server.xml references the keystoreFile and keystorePass attributes that come straight from a keytool -genkeypair call. Android APK signing migrated from the v1 JAR scheme to v2+v3 in 2018, but the apksigner tool still wraps keytool keystores. Maven's maven-jarsigner plugin and Gradle's signing block both consume PKCS12 files produced by keytool. Even Let's Encrypt's official Java client, acme4j, stores its account key and the resulting certificate chain in a PKCS12 file that is byte-for-byte identical to what keytool would produce.

Inside enterprises, keytool is the canonical way to add a custom root CA to the JVM-wide trust store at $JAVA_HOME/lib/security/cacerts with the command keytool -importcert -alias my-root -file root.pem -keystore $JAVA_HOME/lib/security/cacerts -storepass changeit -noprompt. Without that step, HTTPS calls from Java code to internal services fail with PKIX path building errors.

Conclusion

We saw that keytool is a thin command-line wrapper around the java.security.KeyStore API, that the same RSA keypair it produces can be inspected and recreated in pure Java, and that PKCS12 has been the default keystore type since JDK 9. Next, study jarsigner to learn how those keytool keystores back the JAR signing process, then read the X.509 Certificate Parsing tutorial to learn how to validate the certificate chain inside a keystore at runtime.

Test Your Knowledge
How did you find this?

Comments

Join the discussion! Sign in with your Google or Blogger account, or comment as Anonymous - no account needed. For quick questions, also reach me on Telegram @cytestch.

Comments