Home > Articles > Programming > Java

This chapter is from the book

Java Security Management Tools

As part of the J2SE bundle, the Java 2 platform provides a set of tools that helps Java developers and security administrators to administer security policies, create keys (for testing purposes only), manage keys and certificates, sign JAR files, verify signatures, and support other functions related to key management.

The following tools and utilities are provided as part of the J2SE bundle.

Java Keystore

The keystore is a protected database that stores keys and trusted certificate entries for those keys. A keystore stores all the certificate information related to verifying and proving an identity of a person or an application. It contains a private key and a chain of certificates that allows establishing authentication with corresponding public keys. Each entry in the keystore is identified by a unique alias. All stored key entries can also be protected using a password. The Java keystore follows the RSA cryptographic standard known as PKCS#12, which provides a way to securely store multiple keys and certificates in a password-protected file. Unless specified by default, the key entries are stored in a .keystore file and the trusted CA certificate entries are stored in a cacerts file, which resides in the JRE security directory.

Keytool

Keytool is a key and certificate management tool that allows users and administrators to administer their own private/public key pairs and associated certificates. This tool is intended for use with authentication services and verifying data integrity using digital signatures. The keytool is provided with the J2SE bundle as a command-line utility, which can be used to create JKS (Java keystore) and JCEKS (Java Cryptographic Extensions Keystore) keystores, generate and store keys and their associated X.509v1 certificates, generate Certificate Signing Requests (CSR), import and store trusted certificates, and perform maintenance on keystore entries.

The keytool utility uses the X.509 certificate standard, which is encoded using the Abstract Syntax Notation 1 (ASN.1) standard to describe data and the Definite Encoding Rules (DER) standard to identify how the information is to be stored and transmitted. The X.509 certificate takes the values of subject and issuer fields from the X.500 Distinguished Name (DN) standard.

Let's take a look at the most common operations performed using the keytool utility:

Creating a keystore database. A keystore is created whenever you use keytool with options to add entries to a non-existent keystore. The following options automatically create a keystore when the specified keystore does not exist in the user's directory:

  • -genkey option is used to generate private/public key pairs.
  • -import option is used to import a trusted certificate.
  • -identitydb is used to import data from a legacy JDK 1.1.

By default, the keytool creates a keystore as a file named .keystore in the user's home directory, but a name can be specified using the –keystore option.

Generating private/public key pairs. When a keytool is used to generate a private/public key pair, each entry contains a private key and an associated certificate "chain." The first certificate in the chain contains the public key corresponding to the private key.

A pair of public and private keys can be generated and added to the keystore using the keytool -genkey command. The -genkey option creates a public/private key pair and then wraps the public key in a self-signed certificate. The following example will generate a key pair wrapped in a X.509 self-signed certificate and stored in a single-element certificate chain. In this command, we also need to specify passwords for the keys and the keystore, the algorithm to use (RSA), and the alias (see Example 3-20).

Example 3-20. Generating key pairs using keytool

   keytool -genkey -alias myalias -keyalg RSA
         -keypass mykeypass -keystore mykeystore
                              -storepass mystorepass

In the command shown in Example 3-20, the -genkey option is used to generate the key pair, and all other options are used in support of this command. The key pair is identified with an alias myalias with a password of mykeypass. Both the alias and the keypass are required for all the subsequent commands and operations when we access the particular key pair in the keystore. The other options that can be used are as follows:

  • -keyalg -- specifies the encryption algorithm used for the key (example: RSA). An additional "–keysize" option would allow us to specify the bit size for the key; if not specified, the keytool uses the default value of 1024 bits.
  • -keypass -- specifies the password for the key generated.
  • -keystore -- specifies the name of the keystore to store the keys, which is a binary file. If it is not specified, a new file will be created and saved as a .keystore file.
  • -storepass -- specifies the password used to control access to the keystore. After keystore creation, all modifications to the keystore will require you to use the password whenever accessing the keystore.

When you execute these command and options, you will also be prompted with questions to supply the following names for creating subcomponents of the X.500 Distinguished Name standard:

CN - First and Last name
OU - Organizational unit
O - Organization
L - City or Locality
ST - State or Province
C - Country code

Example 3-21 is a sample output generated using these command and options.

Example 3-21. Generating keypairs using Keytool

$ keytool -genkey -alias myalias -keyalg RSA
        -keystore mykeystore  -keypass mykeypass
                     -storepass mystorepass
What is your first and last name?
  [Unknown]:  Roger R
What is the name of your organizational unit?
  [Unknown]:  Java developer
What is the name of your organization?
  [Unknown]:  Java Day care
What is the name of your City or Locality?
  [Unknown]:  Boston
What is the name of your State or Province?
  [Unknown]:  Massachusetts
What is the two-letter country code for this unit?
  [Unknown]:  US
Is CN=Roger R, OU=Java developer,
O=Java Day care, L=Boston, ST=Massachusetts, C=US correct?
  [no]: yes

With all the questions answered, the keytool generates the keys and the certificate and stores them in the specified keystore file.

Listing the entries of a keystore. The keytool with the -list option is used to list all the entries of a keystore, and also to look at the contents of an entry associated with an alias. Example 3-22 is a command that lists all the entries of a keystore named mykeystore. This command also requires us to enter the keystore password.

Example 3-22. Using keytool to list entries of a Java keystore

$ keytool -list -keystore mykeystore
Enter keystore password:  mystorepass

Keystore type: jks
Keystore provider: SUN

Your keystore contains 1 entry
myalias, Sep  5, 2003,  keyEntry,
Certificate fingerprint   (MD5):
68:A2:CA:0C:D5:C6:D2:96:D5:DC:EA:8D:E3:A1:AB:9B

To display the contents of a keystore entry when identified with an alias, the list command prints the MD5 fingerprint of a certificate. If the -v option is specified, the certificate is printed in a human-readable format. If the -rfc option is specified, the certificate is output in the Base 64 encoding format. The following command (see Example 3-23) lists the contents of a keystore entry in a human-readable format for alias "myalias."

Example 3-23. Using keytool to list contents of a Java keystore

$ keytool -list -alias myalias -keystore mykeystore -v
Enter keystore password:  mystorepass
Alias name: myalias
Creation date: Sep 5, 2003
Entry type: keyEntry
Certificate chain length: 1
Certificate[1]:
Owner: CN=Roger R, OU=Java developer,
O=Java Day care, L=Boston, ST=MA, C=US
Issuer: CN=Roger R, OU=Java developer,
O=Java Day care, L=Boston, ST=MA, C=US
Serial number: 3f58edda
Valid from: Fri Sep 05 16:11:06 EDT 2003
until: Thu Dec 04 15:11:06 EST 2003
Certificate fingerprints:
MD5:  68:A2:CA:0C:D5:C6:D2:96:D5:DC:EA:8D:E3:A1:AB:9B
SHA1: 2E:E1:36:ED:D0:E8:EF:85:E5:6B:92:AD:9D:AE:28:82:25:8C:CC:9F

Exporting a certificate entry from a keystore. To have trusted interactions, the communicating client peer needs to have a copy of the public keys from the original signer in the keystore. This is done by exporting the certificate (containing the public key and signer information) to a binary certificate file and then importing them as a trusted certificate into the client peer's keystore.

To export the certificate to a binary certificate file (see Example 3-24), the keytool -export and -file options are used. The following command exports a certificate entry identified with alias myalias in keystore mykeystore to a file mycertificate.cer. This command requires entering the keystore password.

Example 3-24. Exporting a certificate from a Java keystore

$ keytool -export -alias myalias -file mycertificate.cer -keystore
mykeystore
Enter keystore password:  mystorepass
Certificate stored in file <mycertificate.cer>

Importing a trusted certificate. The keytool -import option is used to import a trusted certificate into a keystore database and to associate it with a unique alias. This is executed in the environment of a client who wishes to trust this certificate and to have trusted client interactions with that communicating peer.

When a new certificate is imported into the keystore, the keytool utility verifies that the certificate has integrity and authenticity. The keytool utility attempts this verification by building a chain of trust from that certificate to the self-signed certificate that belongs to the issuer. The lists of trusted certificates are stored in the cacerts file.

To execute the import in a keystore (see Example 3-25), you need to provide the certificate entry with a unique alias and key password. For example, the following command imports a certificate entry from a file mycertificate.cer and identifies the entry with myclientalias and key password clientkeypass in keystore clientkeystore with keystore password clientpass. As a last step, the command displays the owner and issuer information of the certificate and prompts the user to trust the certificate:

Example 3-25. Importing a trusted certificate to a Java keystore

$ keytool -import -alias myclientalias -file
             mycertificate.cer -keypass clientkeypass
            -keystore clientstore -storepass clientpass
Owner: CN=Roger R, OU=Java developer,
O=Java Day care, L=Boston, ST=MA, C=US
Issuer: CN=Roger R, OU=Java developer,
O=Java Day care, L=Boston, ST=MA, C=US
Serial number: 3f58edda
Valid from: Fri Sep 05 16:11:06 EDT 2003
until: Thu Dec 04 15:11:06 EST 2003
Certificate fingerprints:
MD5:  68:A2:CA:0C:D5:C6:D2:96:D5:DC:EA:8D:E3:A1:AB:9B
SHA1: 2E:E1:36:ED:D0:E8:EF:85:E5:6B:92:AD:9D:AE:28:82:25:8C:CC:9F
Trust this certificate? [no]:  yes
Certificate was added to keystore

Printing certificate information. The keytool –printcert option is used to display the contents of a certificate that has been exported from a keystore and made available as a file. To execute this command, no associated keystore database or password is required, because the certificate contains the information as a certificate file (.cer), which is not imported into the keystore.

You would use Example 3-26 to display the contents of a binary certificate file.

Example 3-26. Displaying contents of a certificate

$ keytool -printcert -file mycertificate.cer
Owner: CN=Roger R, OU=Java developer,
O=Java Day care, L=Boston, ST=MA, C=US
Issuer: CN=Roger R, OU=Java developer,
O=Java Day care, L=Boston, ST=MA, C=US
Serial number: 3f58edda
Valid from: Fri Sep 05 16:11:06 EDT 2003 until: Thu Dec
 04 15:11:06 EST 2003
Certificate fingerprints:
MD5:  68:A2:CA:0C:D5:C6:D2:96:D5:DC:EA:8D:E3:A1:AB:9B
SHA1: 2E:E1:36:ED:D0:E8:EF:85:E5:6B:92:AD:9D:AE:28:82:25:8C:CC:9F

Creating a Certificate Signing Request (CSR). The Keytool -certreq option allows you to generate a certificate authentication request for a certificate from a Certificate Authority (CA). The -certreq option (see Example 3-27) creates a CSR for the certificate and places the CSR in a file named certreq_file.csr, where certreq_file.csr is the name of the file that is to be sent to the CA for authentication. If a CA considers the certificate to be valid, it issues a certificate reply and places the reply in a file named cert_reply.cer, where cert_reply.cer is the file returned by the CA that holds the results of the CSR authorizations that were submitted in the certreq_file.csr file.

Example 3-27. Creating a CSR

keytool -certReq -keystore mykeystore
             -file myCSR.csr -alias mycsralias

Deleting a keystore. To delete a keystore, use an operating system delete command to delete the keystore files.

Changing password in the keystore. To change the keystore password, use keytool -storepassword -new options to set a new password (see Example 3-28).

Example 3-28. Changing keystore password

keytool -storepasswd -new newstorepass
     -keystore mykeystore -storepass mystorepass

Example 3-28 shows how the password for the keystore mykeystore is changed from mystorepass to newstorepass.

Smart Cards and Cryptographic Devices Based Keystores

With the release of J2SE 5.0 [J2SE5], Java provides support for using smart cards and cryptographic devices as keystores. J2SE 5.0 introduced the support for RSA Cryptographic Token Interface Standard (referred to as PKCS#11) which defines native programming interfaces to cryptographic tokens, such as hardware cryptographic accelerators and smart cards. Integrating smart card based keystores is accomplished by configuring the smart card PKCS#11 module as a security provider. To facilitate the integration using PKCS#11 interfaces, J2SE 5.0 provides a new cryptographic provider (SunPKCS11). The SunPKCS11 provider enables existing applications written to the JCA and JCE APIs to access native PKCS#11-based smart cards and cryptographic devices. To enable this, the JRE must be configured with the PKCS#11 provider in the java.security file located at $JAVA_HOME/jre/lib/security/java.security.

For a detailed example about how to configure the smart card as Java keystore, refer to the section "Using Smart Cards as Keystores" in Chapter 4, "Java Extensible Security Architecture and APIs."

Policytool

The policytool is a utility that provides a menu-driven user-friendly interface for creating and viewing Java security policy configuration files. The policytool menu options enable you to read and edit policy files by adding policy and permission entries, assigning a keystore, and creating a new policy configuration file.

To start the Policy Tool utility, simply type the following at the command line:

  policytool

For more information about using policytool menu options, refer to the policytool documentation provided with the J2SE bundle.

Jarsigner

The jarsigner tool is used to digitally sign the Java archives (JAR files) and to verify the signature and its integrity. The jarsigner can sign and verify only the JAR file created by the JAR utility provided with the J2SE bundle.

Signing a JAR file

The jarsigner uses the private key information from the signer's keystore to generate digital signatures for signing the JAR files. After signing, the signed JAR file includes a copy of the public key from the keystore that corresponds to the private key used to sign the file. The jarsigner can also verify the signer's information in the signed JAR file.

Example 3-29 shows what you would use to sign a JAR file named myJar.jar and then name the signed JAR file as mySignedJar.jar.

Example 3-29. Using jarsigner to sign a jar file

  jarsigner
       -keystore /home/nr/mykeystore
       -storepass mykeystorepass
        -keypass mykeypass
       -signedjar mySignedJar.jar
          myJar.jar myPrivateKeyalias

Verifying a Signed JAR

To verify a signed JAR file, and to verify that the signature is valid and the JAR file has not been tampered with, you would use the command shown in Example 3-30.

Example 3-30. Using jarsigner to verify signature a signed jar

    jarsigner –keystore /home/nr/mykeystore
                -verify –certs mySignedJar.jar

The J2SE environment also provides support for cryptographic services, secure communication services using SSL and TLS protocols, and certificate management services. The J2SE 5.0 is the newest release of the Java platform. It includes numerous feature and security updates to the Java language and the JVM. J2SE 5.0 also offers significant security enhancements compared to the previous release of J2SE 1.4.x. These will be discussed in Chapter 4, "Java Extensible Security Architecture and APIs."

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020