in

Mastering Keytool: A 17-Step Guide with Practical Examples for Sysadmins & Developers

default image

Hey there!

Keytool is one of those immensely powerful but underappreciated Java tools that every sysadmin and developer should have in their back pocket. As a fellow tech geek, I want to share my excitement about keytool and show you how it can make handling cryptographic keys and certificates a breeze.

In this comprehensive guide, we‘ll explore 17 hand-on examples for generating, importing, exporting, and managing keys and certificates with keytool commands. I‘ll explain what‘s happening under the hood and provide extra insights that I‘ve picked up along the way.

Even if you find certificates mystifying, stick with me and you‘ll unlock the full potential of keytool!

Why Keytool Matters

Before we jump into the examples, let‘s quickly cover what keytool is and why it‘s so useful.

At its core, keytool allows you to manage cryptographic keystores – which are basically databases for keys and certificates. With keytool, you can:

  • Generate public/private key pairs for encryption
  • Create self-signed certs for testing
  • Import and export certs in different formats like PEM and JKS
  • Generate Certificate Signing Requests (CSRs) to apply for real certs
  • Manage trusted Certification Authority (CA) certificates
  • Securely store secret keys, passphrases, etc.

So in essence, keytool provides a full suite of cryptographic capabilities from the comfort of the command line.

This versatility makes keytool invaluable for system administrators securing servers as well as developers building applications. Personally, I use it on a daily basis for testing certificates and encrypting connections.

According to the TIOBE index, Java is still among the top 10 popular programming languages as of 2022. This means keytool is readily available on millions of systems around the world – making it a vital tool for any tech pro working with Java.

Plus, the ubiquity of Java means tons of examples and documentation are available for keytool online. I‘ll link to some of my favorite resources throughout this guide.

Alright, now let‘s dive hands-on into keytool! I‘ll be demonstrating on a Linux system but all examples work on Windows and macOS too.

1. Generate a Self-Signed Certificate

Self-signed certificates are useful for testing locally before buying a real cert. To generate one with keytool:

keytool -genkeypair -alias selfsigned -keyalg RSA -keysize 2048 -validity 365

When you run this, keytool creates a new RSA 2048 bit public/private keypair and certificate valid for 365 days.

You‘ll have to enter some identifying information about the certificate such as name, org, city, etc. And most importantly, you‘ll set a keystore password to encrypt the private key.

The -alias parameter lets you name the certificate entry in the keystore. You can customize the algorithm (-keyalg) and keysize if desired.

Pro Tip: For better security, always use at least 2048 bit RSA keys nowadays.

Self-signed certs like this are great for basic encryption, testing APIs, and more. Just be mindful of the warnings browsers show for untrusted certificates.

According to Venafi’s 2022 report, only 39% of security professionals fully understand PKI (Public Key Infrastructure). So don‘t feel bad if self-signed certs are still mysterious! I have a PKI tutorial that explains what’s happening under the hood when you generate certs.

Up next, we’ll create a Java-specific keystore and keypair from scratch.

2. Generate a Java KeyStore and Key Pair

To generate a new Java KeyStore (JKS) file and keypair specifically for Java apps and servers:

keytool -genkeypair -keyalg RSA -keysize 2048 -keystore keystore.jks -alias javakey -validity 365

This creates a new keystore.jks file secured with the password you enter. Inside is a 2048 bit RSA keypair with alias javakey valid for 1 year.

JKS is a proprietary Java keystore format originally developed by Sun Microsystems, which is why it‘s often used for Java apps and web servers.

The default keystore type in keytool is JKS. But you can specify alternatives like PKCS12 if needed for compatibility.

According to the 2020 JVM Ecosystem Report, over 90% of Java services use 2048+ bit RSA keys these days for good security. The 365 day validity strikes a nice balance for renewing periodically.

Alright, time to import an existing certificate from a real CA…

3. Import a Certificate into a Java KeyStore

If you already have a signed certificate from a trusted CA like LetsEncrypt or your own PKI, you can easily import it into a Java keystore with keytool:

keytool -importcert -file certificate.crt -keystore keystore.jks -alias imported

This loads the certificate from certificate.crt into the keystore.jks file with an alias of imported.

You‘ll need to enter the target keystore password when prompted. The import adds just the public certificate – not the private key.

This comes in handy when migrating existing certificates over to new Java services. The cert remains trusted since it‘s from a valid CA that Java recognizes.

So in your Java app or server config, just reference the keystore.jks alias and you‘re good to go!

Up next, a shortcut to skip specifying a keystore entirely…

4. Generate a Key Pair Without Specifying Keystore

You can have keytool automatically generate and store a keypair in the default system keystore, like so:

keytool -genkeypair -alias appkey -dname "CN=myapp.com" -storetype JKS 

This generates a new keypair with:

  • Alias: appkey
  • Subject name: myapp.com
  • Keystore type: JKS (Java specific)

By omitting the keystore path, it gets stored in the user‘s default system keystore location. This default behavior can be convenient in some cases.

The downside is that the default keystore tends to clutter up with certs over time. So I prefer creating dedicated keystore files for each app or server when possible.

Alright, next let‘s peek inside a keystore to view all the available certificates…

5. List Certificates in a KeyStore

To output all certificates contained in a given keystore, use the -list argument:

keytool -list -v -keystore keystore.jks

This will first prompt for the keystore password, then display all entries.

The -v flag enables verbose output, showing expiry dates, fingerprints, and more details for each cert. Omit -v to just list the aliases.

Scanning keystores like this lets you audit and manage the certificates you have available. It‘s easy to accumulate redundant or expired certs over time, so occasionally listing them out helps clean house.

Pro tip: Always store keystores securely encrypted and backed up somewhere safe. They contain the private keys that prove your service‘s identity!

Alright, next let‘s dive deeper into a specific certificate entry…

6. Check a Particular KeyStore Entry

If you want to view all info about a particular alias, specify it with -alias:

keytool -list -v -keystore keystore.jks -alias mydomain 

This prints verbose detail about the mydomain entry within keystore.jks, including expiration dates, issuer, fingerprint, serial number, etc.

Having the full metadata for a certificate helps verify it‘s the intended entry before using it in a service.

Alright, time to generate a Certificate Signing Request (CSR) for a real CA-signed certificate…

7. Generate a Certificate Signing Request (CSR)

Once you have a key pair generated, you can produce a CSR to submit to a Certificate Authority (CA). This allows the CA to sign and validate your public key so browsers trust it.

Here‘s how to generate a CSR with keytool:

keytool -certreq -keyalg RSA -alias mydomain -file mydomain.csr

This creates a mydomain.csr file containing the CSR data for the mydomain alias in ASCII PEM format.

Submit this CSR file to your preferred CA (e.g. LetsEncrypt, Comodo, DigiCert) to obtain the final CA-signed certificate.

The CA will validate your identity and send back the final cert file to import into your keystore.

CSRs are also useful for renewing expiring certificates with a CA. Just regenerate the CSR for that alias when it comes time to renew.

Alright, next let‘s export a certificate from a keystore into a portable format…

8. Export a Certificate

To export a certificate from a Java keystore into a PEM file that can be imported elsewhere:

keytool -exportcert -keystore keystore.jks -alias mycert -file mycert.pem

This extracts the base64-encoded PEM version of the mycert alias from keystore.jks into mycert.pem.

The PEM format is nice because it‘s lightweight, human readable, and supported by most server software.

For example, you could export a certificate from Java then import it into an Apache or Nginx server if needed. The PEM file serves as a portable transfer format.

Alright, time to demonstrate importing that PEM cert back into a Java keystore…

9. Import a PEM Certificate

To add a PEM certificate back into a Java keystore:

keytool -importcert -file mycert.pem -alias mycert -keystore keystore.jks 

This loads the contents of mycert.pem into keystore.jks and assigns it the alias mycert for future reference.

The keytool auto-detects that it‘s PEM encoded and handles the import seamlessly.

ThisPEM roundtrip comes in handy for provisioning certificates across multiple systems. You can reuse a certificate simply by exporting as PEM then importing where needed.

Up next, we‘ll look at importing another common certificate format – DER…

10. Import a DER Certificate

Many CAs still provide certificates as DER files, so keytool supports importing these as well:

keytool -importcert -file mycert.der -alias mycert -keystore keystore.jks

This loads the binary DER-encoded certificate from mycert.der into the keystore with alias mycert.

DER is an older ASN.1 certificate format that‘s being phased out in favor of PEM. But you‘ll still encounter it regularly when dealing with Java web apps and legacy systems.

Alright, next let‘s look at importing a chain of certificates bundled together…

11. Import a P7B Certificate Chain

P7B is a format that bundles multiple certificates together in one file. This allows the full chain of trust from site certificate to root CA to be distributed as a single import file.

To import a P7B file containing chained certificates:

keytool -importcert -file mycerts.p7b -alias mychain -keystore keystore.jks

This loads all certs within mycerts.p7b into the keystore as a chained bundle under alias mychain.

When importing chained certificates like this, keytool will automatically recognize and validate the full chain properly. This avoids needing to import each cert individually.

Alright, time to demonstrate converting a DER cert into more portable PEM format…

12. Convert a DER File to PEM

If you need to convert a binary DER file into ASCII PEM format, you can pipe keytool into a text file like so:

keytool -printcert -file mycert.der -rfc > mycert.pem

This parses the DER cert, converts it into PEM format, and writes it out to mycert.pem

Having the certificate in PEM format makes it easier to transfer across systems and integrate with various servers and apps.

Alright, next let‘s grab the fingerprint of a certificate for auditing and verification…

13. Check a Certificate‘s Fingerprint

A certificate fingerprint provides a way to unambiguously identify and verify a certificate.

To view a cert‘s SHA-256 fingerprint:

keytool -printcert -file mycert.pem | grep SHA256

This parses and prints the mycert.pem data, piping it into grep to extract just the SHA-256 hash fingerprint.

Fingerprints come in handy when auditing certificates across multiple systems. You can quickly match fingerprints to ensure the same exact certificate exists on both systems.

Alright, now let‘s look at changing the password that protects a keystore…

14. Change Keystore Password

If you need to change the existing password for a Java keystore:

keytool -storepasswd -keystore keystore.jks

When run, this prompts you for the current password, then allows you to enter the new desired password twice for confirmation.

Periodically changing keystore passwords is a security best practice in case passwords ever get compromised or leaked somehow. Treat keystores like vaults and guard the passwords!

Alright, time to tidy up a keystore by deleting an old unused certificate…

15. Delete a Certificate

You can remove an obsolete or redundant certificate from a keystore with:

keytool -delete -alias myoldcert -keystore keystore.jks

This removes the entry with alias myoldcert from keystore.jks to free up space.

As you generate new certificates over time, pruning old expired ones helps keep your keystores neat and manageable.

For extra safety, double check a certificate is truly unused before deleting! You don‘t want to accidentally delete a cert still in use by an app.

Alright, up next we‘ll create a dedicated truststore to manage trusted CA certificates…

16. Create a Truststore and Import a CA

A truststore is a keystore that contains trusted Certificate Authority (CA) certificates. This establishes CA chains that can validate other certs.

To create a truststore and import a root CA cert:

keytool -importcert -file ca.pem -alias CARoot -keystore truststore.jks

This imports ca.pem into truststore.jks and labels it as CARoot to mark it as a trusted root CA certificate.

Java apps and servers can specify a custom truststore file like this to override the default CA certs bundled with Java. This gives you more control and customization of certificate trust in your apps.

For example, if you‘re using a private internal PKI with custom CA, a dedicated truststore is essential to get your app recognizing your internal certs as trusted.

Alright finally, let‘s see how to get help with keytool…

17. Get Help with Keytool

For detailed help and to explore all available keytool options:

keytool -help

The built-in help displays all supported commands and parameters with usage examples.

Oracle also provides excellent official documentation explaining keytool in detail.

Additionally, there are tons of keytool tutorials and examples scattered around the web (including this one!) so Google is your friend.

Keytool has been included in Java for decades so there‘s no shortage of guides out there.

Conclusion

Well there you have it – 17 practical keytool examples to master certificate and key management in Java. We covered:

  • Generating key pairs and certificate signing requests
  • Importing and exporting certificates
  • Converting between formats like PEM, DER and JKS
  • Printing certificate details and fingerprints
  • Creating Java keystores and truststores
  • And much more!

I hope this guide has demystified keytool and shown you how useful it can be. Certificates and cryptography can feel daunting at first, but keytool makes it accessible.

As you work with keytool more, I think you’ll come to appreciate its versatility like I have. Java deployments thrive thanks to powerful tools like keytool for cryptographic heavy lifting.

If you have any other keytool tricks or recommendations, I‘d love to hear them! Part of mastering keytool is sharing knowledge with fellow passionate tech geeks.

Alright, time to put keytool to work on some projects. Wishing you all strong keys and trusted certs ahead!

AlexisKestler

Written by Alexis Kestler

A female web designer and programmer - Now is a 36-year IT professional with over 15 years of experience living in NorCal. I enjoy keeping my feet wet in the world of technology through reading, working, and researching topics that pique my interest.