A Java “keytool genkey” example

Java keytool genkey FAQ: Can you share some examples of the Java keytool genkey command, and the genkey process?

In my previous article on the Java keytool command, keystore files, and certificates, I demonstrated how to generate a private key with the keytool genkey option, but to simplify things a little, I thought I'd demonstrate the keytool/genkey command again here by itself.

keytool/genkey: How to create a private key and keystore

You create a private key and put it in a keystore with the Java keytool command. For instance, to create a keystore named "privateKey.store" that contains a private key with the alias "foo", I can use this keytool command option:

$ keytool -genkey -alias foo -keystore privateKey.store

This keytool/genkey command can be read as:

  • I want to generate a new private key (genkey)
  • I want to create an alias for this key named "foo"
  • I want to store this information in the file named privateKey.store

Of course a better name for a private key might be something like "AlsPrivateKey", but to show that you can name your alias anything, I'm using the string "foo".

Respond to the keytool genkey prompts

After issuing this keytool/genkey command, keytool prompts you with the following questions. I have provided my own example answers to these prompts so you can see exactly how this works:

$ keytool -genkey -alias foo -keystore privateKey.store

Enter keystore password:  ABC123
What is your first and last name?
  [Unknown]:  Alvin Alexander
What is the name of your organizational unit?
  [Unknown]:  Application Development
What is the name of your organization?
  [Unknown]:  devdaily.com
What is the name of your City or Locality?
  [Unknown]:  Louisville
What is the name of your State or Province?
  [Unknown]:  KY
What is the two-letter country code for this unit?
  [Unknown]:  US
Is CN=Alvin Alexander, OU=Application Development, O=devdaily.com, L=Louisville, ST=KY, C=US correct?
  [no]:  yes

Enter key password for <foo>
      (RETURN if same as keystore password):  123XYZ

There are at least a few important points to note here:

  • The password for accessing the keystore file is "ABC123".
  • The password for my alias is "123XYZ".

Both of these passwords are very important, and you'll see how they are used in the next few steps.

After creating your private key keystore with the "keytool genkey" command, you can query your keystore file with the "keytool list" command.

(To help keep these tutorials short I'm putting each in their own blog post. Again, you can also follow this link for one long "Java keytool keystore tutorial".)