JavaTM Cryptography Extension 1.2.1

API Specification & Reference


Introduction

Cryptographic Concepts
Encryption and Decryption
Password-Based Encryption
Cipher
Key Agreement
Message Authentication Code

Core Classes
The Cipher Class
The Cipher Stream Classes
The CipherInputStream Class
The CipherOutputStream Class
The KeyGenerator Class
The SecretKeyFactory Class
The SealedObject Class
The KeyAgreement Class
The Mac Class

Application Exportability

How to Make Applications "Exempt" from Cryptographic Restrictions

Install Providers for JCE 1.2.1

JCE Keystore

Code Examples
Using Encryption
Using Password-Based Encryption
Using Key Agreement


Appendix A: Standard Names

Appendix B: JCE 1.2.1 Jurisdiction Policy Files

Appendix C: SunJCE Default Keysizes

Appendix D: SunJCE Keysize Restrictions

Appendix E: Sample Programs
Diffie-Hellman Key Exchange between 2 Parties
Diffie-Hellman Key Exchange between 3 Parties
Blowfish Example
HMAC-MD5 Example

Introduction

This document is intended as a companion to the JavaTM Cryptography Architecture (JCA) API Specification & Reference. References to chapters not present in this document are to chapters in the JCA Specification.

The JavaTM Cryptography Extension (JCE) 1.2.1 provides a framework and implementations for encryption, key generation and key agreement, and Message Authentication Code (MAC) algorithms. Support for encryption includes symmetric, asymmetric, block, and stream ciphers. The software also supports secure streams and sealed objects.

JCE 1.2.1 has a provider-based architecture. Providers signed by a trusted entity can be plugged into the JCE 1.2.1 framework, and new algorithms can be added seamlessly.

JCE 1.2.1 supplements the JavaTM 2 SDK, Standard Edition, v 1.2 (J2SDK), formerly known as JDKTM version 1.2, which already includes interfaces and implementations of message digests and digital signatures. JCE 1.2.1 is provided as an optional package (formerly known as an "extension") to the JavaTM 2 platform.

JCE 1.2.1 is based on the same design principles found elsewhere in the JCA: implementation independence and, whenever possible, algorithm independence. It uses the same "provider" architecture.

The JCE 1.2.1 API covers:

The JCE 1.2.1 release comes standard with a provider named "SunJCE", which must be installed and which supplies the following cryptographic services:

A Note on Terminology

The JCE 1.2.1 release includes two software components:

Throughout this document, the term "JCE 1.2.1" refers to the JCE 1.2.1 framework. If the full release is mentioned, it will be referred to as "the JCE 1.2.1 release."

Cryptographic Concepts

This section provides a high-level description of the concepts implemented by the API, and the exact meaning of the technical terms used in the API specification.

Encryption and Decryption

Encryption is the process of taking data (called cleartext) and a short string (a key), and producing data (ciphertext) meaningless to a third-party who does not know the key. Decryption is the inverse process: that of taking ciphertext and a short key string, and producing cleartext.

Password-Based Encryption

Password-Based Encryption (PBE) derives an encryption key from a password. In order to make the task of getting from password to key very time-consuming for an attacker, most PBE implementations will mix in a random number, known as a salt, to create the key.

Cipher

Encryption and decryption are done using a cipher. A cipher is an object capable of carrying out encryption and decryption according to an encryption scheme (algorithm).

Key Agreement

Key agreement is a protocol by which 2 or more parties can establish the same cryptographic keys, without having to exchange any secret information.

Message Authentication Code

A Message Authentication Code (MAC) provides a way to check the integrity of information transmitted over or stored in an unreliable medium, based on a secret key. Typically, message authentication codes are used between two parties that share a secret key in order to validate information transmitted between these parties.

A MAC mechanism that is based on cryptographic hash functions is referred to as HMAC. HMAC can be used with any cryptographic hash function, e.g., MD5 or SHA-1, in combination with a secret shared key. HMAC is specified in RFC 2104.


Core Classes


Application Exportability

[Note 1: You can ignore this section if (1) you will not export your application outside the U.S. or Canada, or (2) your application may be exported, but it doesn't require any cryptography stronger than that which the U.S. government allows throughout the world.]

[Note 2: Throughout this section, the term "application" is meant to encompass both applications and applets.]

Overview

Prior to JCE 1.2.1, the JCE framework for encryption services was not exportable. Only people in the U.S. and Canada were allowed to use it. Export control restrictions by the U.S. Commerce Department prohibit such a framework from being exported outside the U.S. or Canada, unless appropriate mechanisms have been implemented to ensure that only qualified providers can be plugged into the framework. (Qualified providers include those approved for export and those certified for domestic use only. Qualified providers are signed by a trusted entity.)

The JCE 1.2.1 framework contains such mechanisms and is thus now exportable. It is transparent to application developers how providers are authenticated, and only qualified providers can be plugged into JCE 1.2.1.

The JCE 1.2.1 framework also enforces restrictions regarding the cryptographic algorithms and maximum cryptographic strength available to applets/applications in different jurisdiction contexts (locations). This makes the JCE 1.2.1 framework worldwide exportable and worldwide importable.

Implications for Applications

Applications that do not require any cryptography stronger than the default strength (as defined by the applicable jurisdiction policy files described in the next section) will not require any modifications by their vendors. Existing unmodified applications will run unrestricted, exactly as before in the domestic market (the United States and Canada). Such applications can now also be exported. When such an application is run outside the domestic market, the maximum cryptographic strength that can be utilized by any Cipher it creates is determined by the default policy.

New applications that are unsigned or that are signed but not by an entity trusted by JCE 1.2.1 will also have the maximum cryptographic strength determined by the default policy.

Applications that need stronger cryptography will need to be signed by a "trusted signer" and have an associated permission policy file also signed and bundled with the application in a JAR file, as described in How to Make Applications "Exempt" from Cryptographic Restrictions.

Permission Model and Policy Files

JCE 1.2.1 takes advantage of the security model introduced in J2SE. In particular, privileges related to the use of strong(er) cryptography are expressed as permission classes whose definitions are bundled with the JCE 1.2.1 framework.

When users download the JAR file containing the JCE 1.2.1 software, they also download two other JAR files:

These JAR files are signed by the same entity that signed the JCE 1.2.1 JAR file, and they contain "jurisdiction policy files" that specify the allowable cryptography algorithms, key strengths, and algorithm parameter values for default and exempt applications (see below).

JCE 1.2.1 represents its jurisdiction policy files as J2SE-style policy files with corresponding permission statements. As described in Default Policy Implementation and Policy File Syntax, a J2SE policy file specifies what permissions are allowed for code from specified code sources. A permission represents access to a system resource. In the case of JCE 1.2.1, the "resources" are cryptography algorithms, and code sources do not need to be specified, because the cryptographic restrictions apply to all code.

Downloaded Jurisdiction Policy Files

The exact contents of the downloaded JAR files depends on the jurisdiction (location) of the person downloading them. Domestic (U.S. and Canada) users receive one set of these JAR files, while everyone from other countries receives a different set.

Jurisdiction Policy Files for Domestic Market

Domestic (U.S. and Canadian) people receive JAR files that each contain a single policy file:

US_export_policy.jar:
    default_domestic_US_export.policy 
local_policy.jar:
    default_domestic_local.policy 
These files for domestic users currently specify that all applications are unrestricted, that is, the applications can utilize any available cryptographic strengths they wish.

Jurisdiction Policy Files for Global Market

People outside the U.S. and Canada receive JAR files that each contain up to two policy files:

US_export_policy.jar:
    default_global_US_export.policy 
local_policy.jar:
    default_global_local.policy
    exempt_global_local.policy

As you can see, there are both "default" and "exempt" jurisdiction policy files.

The default files represent the default cryptographic strengths allowed for applications that are unsigned or that are signed but not by parties trusted by JCE 1.2.1. When JCE 1.2.1 is running such applications, for each cryptography algorithm utilized JCE 1.2.1 determines and enforces the weaker of the cryptographic strengths specified in the two default files downloaded by the user.

If a default file for a given domain (US_export or local) specifies that applications are unrestricted, no corresponding exempt file is needed or supplied for that domain. (This is why the JAR files for domestic users do not currently contain any exempt policy files, and why there is no exempt_global_US_export.policy.)

Otherwise, an exempt file is required. The exempt file specifies the conditions under which "exempt applications" can have reduced cryptographic restrictions. Exempt policy files are consulted when an application is determined at runtime to be potentially exempt from some or all cryptographic restrictions.

In order for an application to be recognized as "exempt" at runtime, it must have a policy file bundled with it in a JAR file. The policy file specifies what cryptography-related permissions the application has, and under what conditions (if any). See How to Make Applications "Exempt" from Cryptographic Restrictions for further information.

Jurisdiction Policy File Format

A jurisdiction policy file consists of a very basic "grant entry" containing one or more "permission entries."

grant {
    <permission entries>;
};

The format of a permission entry in a jurisdiction policy file is:

permission <crypto permission class name>[ <alg_name>
    [[, <exemption mechanism name>][, <maxKeySize>
    [, <AlgorithmParameterSpec class name>,
    <parameters for constructing an 
        AlgorithmParameterSpec object>]]]];

A sample jurisdiction policy file that includes restricting the "DES" algorithm to maximum key sizes of 64 bits is:

grant {
    permission javax.crypto.CryptoPermission "DES", 64;
    . . .;
};

A permission entry must begin with the word permission. The <crypto permission class name> in the template above would actually be a specific permission class name, such as javax.crypto.CryptoPermission. A crypto permission class reflects the ability of an application/applet to use certain algorithms with certain key sizes in certain environments. There are two crypto permission classes: CryptoPermission and CryptoAllPermission. The special CryptoAllPermission class implies all cryptography-related permissions, that is, it specifies that there are no cryptography-related restrictions.

The <alg_name>, when utilized, is a quoted string specifying the standard name of a cryptography algorithm, such as "DES" or "RSA".

The <exemption mechanism name>, when specified, is a quoted string indicating an exemption mechanism which, if enforced, enables a reduction in cryptographic restrictions. The exemption mechanism names that can be used are "KeyRecovery" "KeyEscrow", and "KeyWeakening".

<maxKeySize> is an integer specifying the maximum key size (in bits) allowed for the specified algorithm.

For some algorithms it may not be sufficient to specify the algorithm strength in terms of just a key size. For example, in the case of the "RC5" algorithm, the number of rounds must also be considered. For algorithms whose strength needs to be expressed as more than a key size, the permission entry should also specify an AlgorithmParameterSpec class name (such as javax.crypto.spec.RC5ParameterSpec) and a list of parameters for constructing the specified AlgorithmParameterSpec object.

Items that appear in a permission entry must appear in the specified order. An entry is terminated with a semicolon.

Case is unimportant for the identifiers (grant, permission) but is significant for the <crypto permission class name> or for any string that is passed in as a value.

Note: An "*" can be used as a wildcard for any permission entry option. For example, an "*" (without the quotes) for an <alg_name> option means "all algorithms."


How to Make Applications "Exempt" from Cryptographic Restrictions

[Note 1: This section should be ignored by most application developers. It is only for people whose applications may be exported to countries other than the U.S. and Canada, and whose applications need to have fewer cryptographic restrictions than the default policies allow for.]

[Note 2: Throughout this section, the term "application" is meant to encompass both applications and applets.]

An application may become exempt from some or all cryptographic restrictions, after receiving U.S. government approval, under two circumstances:

  1. It is a special type of application (such as a financial or health care application) whose algorithms are deemed to be exempt from all cryptographic restrictions.

  2. It is an application that utilizes an "exemption mechanism," such as key recovery.

In order for an application to be recognized as "exempt" at runtime, it must meet the following conditions:

The steps required in order to make an application exempt from some or all cryptographic restrictions are the following:


Step 1: Write and Compile Your Application Code

The first step is to write and compile your application code basically the same as you normally would. However, if your application is going to become exempt by use of an exemption mechanism, there are some additional requirements.

Special Code Requirements for Applications that Use Exemption Mechanisms

When an application has a permission policy file associated with it (in the same JAR file) and that permission policy file specifies an exemption mechanism, then when the Cipher getInstance method is called to instantiate a Cipher, the JCE 1.2.1 code searches the installed providers for one that implements the specified exemption mechanism. If it finds such a provider, JCE 1.2.1 instantiates an ExemptionMechanism API object associated with the provider's implementation, and then associates the ExemptionMechanism object with the Cipher returned by getInstance.

After instantiating a Cipher, and prior to initializing it (via a call to the Cipher init method), your code must call the following Cipher method:

    public ExemptionMechanism getExemptionMechanism()

This call returns the ExemptionMechanism object associated with the Cipher. You must then initialize the exemption mechanism implementation by calling the following method on the returned ExemptionMechanism:

     public final void init(Key key)

The arguments you supply should be the same as the arguments of the same types that you will subsequently supply to a Cipher init method.

Once you have initialized the ExemptionMechanism, you can proceed as usual to initialize and use the Cipher.

Step 2: Create a Permission Policy File Granting Appropriate Cryptographic Permissions

In order for an application to be recognized at runtime as being "exempt" from some or all cryptographic restrictions, it must have a permission policy file bundled with it in a JAR file. The permission policy file specifies what cryptography-related permissions the application has, and under what conditions (if any).

Note: The permission policy file bundled with an application must be named cryptoPerms.

The format of a permission entry in a permission policy file that accompanies an exempt application is the same as the format for a jurisdiction policy file downloaded with JCE 1.2.1, which is:

permission <crypto permission class name>[ <alg_name>
    [[, <exemption mechanism name>][, <maxKeySize>
    [, <AlgorithmParameterSpec class name>,
    <parameters for constructing an AlgorithmParameterSpec object>]]]];

Permission Policy Files for Exempt Applications

Some applications (e.g., financial and health care applications) can be completely unrestricted, just like applications that are run in the domestic market. Thus, the permission policy file that accompanies such an application usually just needs to contain the following:

grant {
    // There are no restrictions to any algorithms.
    permission javax.crypto.CryptoAllPermission;
};

If an application just uses a single algorithm (or several specific algorithms), then the permission policy file could simply mention that algorithm (or algorithms) explicitly, rather than granting CryptoAllPermission. For example, if an application just uses the Blowfish algorithm, the permission policy file doesn't have to grant CryptoAllPermission to all algorithms. It could just specify that there is no cryptographic restriction if the Blowfish algorithm is used. In order to do this, the permission policy file would look like the following:

grant {
    permission javax.crypto.CryptoPermission "Blowfish";
};

Permission Policy Files for Applications Exempt Due to Exemption Mechanisms

If an application is considered "exempt" if an exemption mechanism is enforced, then the permission policy file that accompanies the application must specify one or more exemption mechanisms. At runtime, the application will be considered exempt if any of those exemption mechanisms is enforced. Each exemption mechanism must be specified in a permission entry that looks like the following:

    // No algorithm restrictions if specified
    // exemption mechanism is enforced.
    permission javax.crypto.CryptoPermission *, 
        "<ExemptionMechanismName>";

where <ExemptionMechanismName> specifies the name of an exemption mechanism. The list of exemption mechanism names that can be used is:

  • KeyRecovery

  • KeyEscrow

  • KeyWeakening
As an example, suppose your application is exempt if either key recovery or key escrow is enforced. Then your permission policy file should contain the following:
grant {
    // No algorithm restrictions if KeyRecovery is enforced.
    permission javax.crypto.CryptoPermission *, 
        "KeyRecovery";
    // No algorithm restrictions if KeyEscrow is enforced.
    permission javax.crypto.CryptoPermission *, 
        "KeyEscrow";
};

Note: Permission entries that specify exemption mechanisms should not also specify maximum key sizes. The allowed key sizes are actually determined from the exempt jurisdiction policy files downloaded with JCE 1.2.1, as described in the next section.

How Bundled Permission Policy Files Affect Cryptographic Permissions

At runtime, when an application being run outside the U.S. and Canada instantiates a Cipher (via a call to its getInstance method) and that application has an associated permission policy file, JCE 1.2.1 checks to see whether the permission policy file has an entry that applies to the algorithm specified in the getInstance call. If it does, and the entry grants CryptoAllPermission or does not specify that an exemption mechanism must be enforced, it means there is no cryptographic restriction for this particular algorithm.

If the permission policy file has an entry that applies to the algorithm specified in the getInstance call and the entry does specify that an exemption mechanism must be enforced, then the exempt jurisdiction policy file(s) are examined. If the exempt permissions include an entry for the relevant algorithm and exemption mechanism, and that entry is implied by the permissions in the permission policy file bundled with the application, and if there is an implementation of the specified exemption mechanism available from one of the registered providers, then the maximum key size and algorithm parameter values for the Cipher are determined from the exempt permission entry.

If there is no exempt permission entry implied by the relevant entry in the permission policy file bundled with the application, or if there is no implementation of the specified exemption mechanism available from any of the registered providers, then the application is only allowed the standard default cryptographic permissions.

Step 3: Prepare for Testing

Step 3a: Get a Code-Signing Certificate for Testing

Request a code-signing certificate for testing only. This certificate has a limited validity period (30 days). It is provided for testing only. You should not use it to sign your product in the production environment.

Below are the steps use to get a code-signing certificate for testing. For more information on the keytool tool, see keytool (for Solaris) (for Microsoft Windows).

  1. Use keytool to generate a DSA keypair.
      keytool -genkey -alias <alias> -keyalg DSA -keysize 1024
        -dname "cn=<Company Name>,ou=Java Software Code Signing, 
        o=Sun Microsystems Inc" 
        -keystore <keystore file name>
        -storepass <keystore password>
    

    (Please note: This must be typed as a single line. Multiple lines and indentation are used in the examples just for legibility purposes.)

    This will generate a DSA keypair (a public key and an associated private key) and store it in an entry in the specified keystore. The public key is stored in a self-signed certificate. The keystore entry can subsequently be accessed using the specified alias.

    The option values in angle brackets ("<" & ">") represent the actual values that must be supplied. For example, <alias> must be replaced with whatever alias name you wish to be used to refer to the newly-generated keystore entry in the future, and <keystore file name> must be replaced with the name of the keystore to be used. Note: Do not surround actual values with angle brackets. For example, if you want your alias to be myTestAlias, specify the -alias option as follows:

        -alias myTestAlias
    

    If you specify a keystore that doesn't yet exist, it will be created.

    Note: If command lines you type are not allowed to be as long as the keytool -genkey command you want to execute (for example, if you are typing to a Microsoft Windows DOS prompt), you can create and execute a plain-text batch file containing the command. That is, create a new text file that contains nothing but the full keytool -genkey command. (Remember to type it all on one line.) Save the file with a .bat extension. Then in your DOS window, type the file name (with its path, if necessary). This will cause the command in the batch file to be executed.

  2. Use keytool to generate a certificate signing request.
    keytool -certreq -alias <alias> -sigalg DSA 
            -file <csr file name> 
            -keystore <keystore file name> 
            -storepass <keystore password>
    
    Here, <alias> is the alias for the DSA keypair entry created in the previous step. This command generates a Certificate Signing Request (CSR), using the PKCS#10 format. It stores the CSR in the file whose name is specified in <csr file name>.

  3. Send the CSR and contact information to the JCE Code Signing Certification Authority.

    Send, via email, the CSR and contact information to javasoft-cert-request@sun.com. Put the following in the Subject line of your email message:

      Request a Certificate for Signing a JCE Application (Testing)
    

    Put the contact information in the body of the message and send the CSR file as a plain text attachment to the message. If your mail tool has an option for specifying the encoding format to be used for attachments, select the "MIME" option. Note: The CSR file is just a plain text file, in Base 64 encoding. Only the first and last lines are human-readable.

    Include the following contact information in the body of your message:

    Company Name
    Street Address (Not a post office box)
    City
    State/Province
    Country
    Company Telephone Number
    Company Fax Number
    Company Home Page URL 
    Requester Name
    Requester Telephone Number
    Requester Email Address
    Brief description of your company (size, 
        line of business, etc.)
    

    All of the above information is required, except for the home page URL.

    The JCE Code Signing Certification Authority will authenticate you, the requester. Then it will create and sign a code-signing certificate for testing, valid for 30 days. It will send you an email message containing two plain-text file attachments: one file containing this code-signing certificate for testing and another file containing its own CA certificate, which authenticates its public key.

  4. Use keytool to import the certificates received from the CA.

    Once you have received the two certificates from the JCE Code Signing Certification Authority, you can use keytool to import them into your keystore.

    First import the CA's certificate as a "trusted certificate":

    keytool -import -alias <alias for the CA cert> 
            -file <CA cert file name> 
            -keystore <keystore file name> 
            -storepass <keystore password>
    
    Then import the code-signing certificate:
    keytool -import -alias <alias> 
            -file <code-signing cert file name>
            -keystore <keystore file name> 
            -storepass <keystore password>
    
    Here, <alias> is the same alias as that which you created in step 1 where you generated a DSA keypair. This command replaces the self-signed certificate in the keystore entry specified by <alias> with the one signed by the JCE Code Signing Certification Authority.

Now that you have in your keystore a certificate from an entity trusted by JCE 1.2.1 (the JCE Code Signing Certification Authority), you can place your application code and permission policy file in a JAR file (Step 3b) and then use that certificate to sign the JAR file (Step 3c)

Step 3b: Bundle the Application and Permission Policy File into a JAR File

In order to prepare for testing, your application and permission policy file (created in Step 2) must be bundled together into a JAR file, which will be signed in the next step.

For example, to create a JAR file named myApp.jar containing the myApp.class and cryptoPerms files, you could type the following in your command window:

jar cvf myApp.jar myApp.class cryptoPerms
For more information on the jar tool, see jar (for Solaris) (for Microsoft Windows).

Step 3c: Sign the JAR File for Testing

Sign the JAR file created in the previous step with the code-signing certificate obtained in Step 3a. For more information on the jarsigner tool, see jarsigner (for Solaris) (for Microsoft Windows).

jarsigner -keystore <keystore file name> 
          -storepass <keystore password>
          <JAR file name> <alias>

Here, <alias> is the alias into the keystore for the entry containing the code-signing certificate received from the JCE Code Signing Certification Authority (the same alias as that specified in the commands in Step 3a).

You can test verification of the signature via the following:

jarsigner -verify <JAR file name> 

The text "jar verified" will be displayed if the verification was successful.

Step 3d: Set Up Your Environment Like That of a Global User

In order to ensure that your application can be run with the reduced cryptographic restrictions that your exemption allows, you will need to set up your environment to be like that of users running your application in markets other than the U.S. and Canada (since programs run in the U.S. and Canada have no cryptographic restrictions).

Anyone in the world (including those in the U.S. and Canada) can download and install the global JCE 1.2.1 distribution. So download and install this distribution and use it for your testing in Step 4.

Step 3e: (only for apps using exemption mechanisms) Install a Provider Implementing the Exemption Mechanism Specified in the Permission Policy File

In order for an application to be exempt from cryptographic restrictions due to enforcement of an exemption mechanism, a provider implementing the exemption mechanism must be installed. Thus, you need to install such a provider in order to test your application, and the client of your application will also need to install such a provider. The method of installing providers is described in Install Providers for JCE 1.2.1.

Note: The "SunJCE" provider supplied with every JCE 1.2.1 installation does not implement any exemption mechanisms, so you will need to obtain code from a provider that has an appropriate implementation.

Step 4: Test Your Application

Now that your JCE 1.2.1 environment is set up the same as it would be for global users, you can test your application as though you were running it from a country other than the U.S. or Canada.

You could start off directly testing your application itself. Or you could initially write and run a shorter test program that creates a Cipher that attempts to do encryption using the algorithm(s) and cryptographic strengths your application should be allowed to use if your request for exempt status is accepted. Of course, any test program you utilize must be bundled with a copy of the permission policy file and signed using the certificate for testing, as described in Step 3b and Step 3c.

One way to test whether or not you are able to utilize keys of a particular size is to generate a key of that size and then instantiate and attempt to initialize a Cipher using that key and one of the algorithms your application will utilize. (You can generate a key of a particular size by, for example, using a javax.crypto.KeyGenerator and calling its init method with a keysize parameter, or by using a java.security.KeyPairGenerator and calling its initialize method with a keysize parameter.) If the keysize is greater than the maximum allowable keysize given the environment in which the program is run -- determined by the jurisdiction policy files and the permission policy file bundled with the application, if any -- then the Cipher init method throws a SecurityException. This should not happen if you are utilizing a keysize that should be accepted for your exempt application. If a SecurityException is thrown, review the previous steps carefully and ensure you have followed them all.

Once you have a short test program working, test your complete application.

Step 5: Prepare for Production

Step 5a: Apply for Government Approval

Apply to the Bureau of Export Administration in the U.S. Department of Commerce for exemption from cryptographic restrictions. Specify why your application qualifies for exemption. Is it a special type of application, such as a health care or financial application, whose algorithms the government considers exempt from cryptographic restrictions? Is it an application that utilizes an "exemption mechanism" such as key recovery? Consult your export attorney for more information.

Include a copy of the permission policy file which you created in Step 2 and which you intend to bundle with your application code in the JAR file for your application.

Here are a couple URLs that may be of use to you:

Step 5b: Get a Code-Signing Certificate for Production

Below are the steps use to get a code-signing certificate for production. Note that they are basically the same as the steps used to get a code-signing certificate for testing (Step 3a), except that the certificate you receive for production will last a lot longer than the temporary certificate you received for testing, and you will need to show proof of exemption from cryptographic restrictions before you will be issued a code-signing certificate for production.

  1. Use keytool to generate a DSA keypair.
      keytool -genkey -alias <prAlias> -keyalg DSA -keysize 1024
        -dname "cn=<Company Name>,ou=Java Software Code Signing, 
        o=Sun Microsystems Inc" 
        -keystore <keystore file name>
        -storepass <keystore password>
    

    (Please note: This must be typed as a single line. Multiple lines and indentation are used in the examples just for legibility purposes.)

    This will generate a DSA keypair (a public key and an associated private key) and store it in an entry in the specified keystore. The public key is stored in a self-signed certificate. The keystore entry can subsequently be accessed using the alias specified in <prAlias>.

    As mentioned in the corresponding step for obtaining a code-signing certificate for testing (Step 3a), the option values in angle brackets ("<" & ">") represent the actual values that must be supplied. (Do not surround actual values with angle brackets.) Also, if command lines you type are not allowed to be as long as the keytool -genkey command you want to execute, you can create and execute a plain-text batch file containing the command.

  2. Use keytool to generate a certificate signing request.
    keytool -certreq -alias <prAlias> -sigalg DSA 
            -file <csr file name> 
            -keystore <keystore file name> 
            -storepass <keystore password>
    
    Here, <prAlias> is the alias for the DSA keypair entry created in the previous step. This command generates a Certificate Signing Request (CSR), using the PKCS#10 format. It stores the CSR in the file whose name is specified in <csr file name>.

  3. Send the CSR, contact information, and proof of exemption to the JCE Code Signing Certification Authority.

    Send, via email, the CSR and contact information to javasoft-cert-request@sun.com.

    Put the following in the Subject line of your email message:

    Request a Certificate for Signing a JCE Application (Production)
    

    Put the contact information in the body of the message and send the CSR file as a plain text attachment to the message. If your mail tool has an option for specifying the encoding format to be used for attachments, select the "MIME" option. Note: The CSR file is just a plain text file, in Base 64 encoding. Only the first and last lines are human-readable.

    Include the following contact information in the body of your message:

    Company Name
    Street Address (Not a post office box)
    City
    State/Province
    Country
    Company Telephone Number
    Company Fax Number
    Company Home Page URL 
    Requester Name
    Requester Telephone Number
    Requester Email Address
    Brief description of your company (size, 
        line of business, etc.)
    

    After the JCE Code Signing Certification Authority has received your email message, it will send you a request number, also via email. After receiving this request number, mail a copy of your proof of exemption from cryptographic restrictions received from the U.S. government in Step 5a. Include in your mailing a note indicating the request number so that your hardcopy mailing can be matched to your email message containing the CSR and contact information. The exemption proof and request number should be mailed to

    Corporate Export
    Attn: Encryption export
    901 San Antonio Road, UPAL01-541
    Palo Alto, CA 94303
    

    After the JCE Code Signing Certification Authority has received your email message and the proof of exemption from cryptographic restrictions, it will authenticate you, the requester. Then it will create and sign a code-signing certificate for production, valid for 5 years. It will send you an email message containing two plain-text file attachments: one file containing this code-signing certificate for testing and another file containing its own CA certificate, which authenticates its public key.

  4. Use keytool to import the certificates received from the CA.

    Once you have received the two certificates from the JCE Code Signing Certification Authority, you can use keytool to import them into your keystore.

    If you are using the same keystore as that used for testing, you will already have imported the CA's certificate as a "trusted certificate" in the fourth substep of Step 3a: Get a Code-Signing Certificate for Testing, so you don't need to do that again.

    If you are using a different keystore, you need to import the CA's certificate into your keystore as a "trusted certificate":

    keytool -import -alias <alias for the CA cert> 
            -file <CA cert file name> 
            -keystore <keystore file name> 
            -storepass <keystore password>
    
    In any case, then import the code-signing certificate:
    keytool -import -alias <prAlias> 
            -file <code-signing cert file name>
            -keystore <keystore file name> 
            -storepass <keystore password>
    
    Here, <prAlias> is the same alias as that which you created in step 1 where you generated a DSA keypair. This command replaces the self-signed certificate in the keystore entry specified by <prAlias> with the one signed by the JCE Code Signing Certification Authority.

Now that you have in your keystore a code-signing certificate for production from an entity trusted by JCE 1.2.1 (the JCE Code Signing Certification Authority), you can place your application code and permission policy file in a JAR file (Step 5c) and then use that certificate to sign the JAR file (Step 5d)

Step 5c: Bundle the Application and Permission Policy File into a New JAR File

Create a new JAR file containing the application and permission policy file, to be signed in the next step using the official code-signing certificate.

jar cvf <JAR file name> <space-separated list of classes> cryptoPerms

This command creates a JAR file with the specified name containing the specified classes and the permission policy file (which must always be named cryptoPerms).

For performance reasons, it is best to create this new JAR file rather than simply adding the official production signature to the JAR file created in Step 3b that was signed using the testing certificate obtained in Step 3a. If the JAR file used in production still contains signatures generated by the test certificate, the JCE 1.2.1 framework may waste time trying to verify those signatures.

Step 5d: Sign the JAR File for Production

Sign the JAR file created in the previous step with the code-signing certificate obtained in Step 5b.

jarsigner -keystore <keystore file name> 
          -storepass <keystore password>
          <JAR file name> <prAlias>

Here, <prAlias> is the alias into the keystore for the entry containing the code-signing certificate for production received from the JCE Code Signing Certification Authority (the same alias as that specified in the commands in Step 5b).

You can test verification of the signature via the following:

jarsigner -verify <JAR file name> 

The text "jar verified" will be displayed if the verification was successful.

Step 6: Run Your Test Programs Again

Your application should have been thoroughly tested in Step 4. However, we suggest you run your test programs again to make sure that everything still works fine since what you tested in Step 4 is signed by a different certificate.

Step 7: Deploy Your Application

Now that your application has been officially made exempt and has been tested, the final step is to make your application available to your customers. If your application is only exempt if an exemption mechanism is enforced, also either supply your customers with one or more providers implementing appropriate exemption mechanisms or suggest where they can obtain such providers.


Install Providers for JCE 1.2.1

Cryptographic providers for JCE 1.2.1 are installed and configured in much the same way as cryptographic providers for the JavaTM 2 platform. The only difference is that when you install a JCE 1.2.1 provider, you also need to make sure that JCE 1.2.1 is installed. More information about installing and configuring providers can be found in the Install Providers section of the JavaTM Cryptography Architecture API Specification & Reference document.

There are two parts to installing a provider: installing the provider package classes, and configuring the provider.

Install the Provider Classes

The first thing do is make the provider classes available so that they can be found when requested. Provider classes are shipped as a JAR (Java ARchive) file.

Note that in order for a provider to work, also have JCE 1.2.1 (more specifically: the jce1_2_1.jar file) installed as an optional package (also known as an "extension") to the Java 2 platform. In order to access the "SunJCE" provider included with the JCE 1.2.1 release, also install the sunjce_provider.jar file as an optional package. Installation of these two JAR files is described in Java Cryptography Extension 1.2.1 Installation Instructions.

There are a couple possible ways of installing other provider classes:

For more information on "installed" extensions, see Installed Extensions.

For more information on "bundled" extensions, see Bundled Extensions.

Configuring the Provider

The next step is to add the provider to your list of approved providers. This is done statically by editing the security properties file

<java-home>\lib\security\java.security         [Win32]
<java-home>/lib/security/java.security         [Solaris]
Here <java-home> refers to the directory where the JRE was installed. For example, if you have J2SDK v 1.2.2 installed on Solaris in a directory named jdk1.2.2, you need to edit the following file:
jdk1.2.2/jre/lib/security/java.security
Similarly, if you have JavaTM 2 Runtime Environment, Standard Edition, v 1.2 (J2RE, formerly known as JRE 1.2) installed on Solaris in a directory named jre1.2, you need to edit this file:
jre1.2/lib/security/java.security

For each provider, this file should have a statement of the following form:

    security.provider.n=masterClassName

This declares a provider, and specifies its preference order n. The preference order is the order in which providers are searched for requested algorithms when no specific provider is requested. The order is 1-based; 1 is the most preferred, followed by 2, and so on.

masterClassName must specify the fully qualified name of the provider's "master class". The provider vendor should supply you this name.

J2SE comes standard with a provider named "SUN", which is automatically configured as a static provider in the java.security properties file, as follows:

    security.provider.1=sun.security.provider.Sun
(The "SUN" provider's master class is the Sun class in the sun.security.provider package.)

Note that when you install JCE 1.2.1 (the jce1_2_1.jar extension), the "SunJCE" provider that is also included with the JCE 1.2.1 release is not automatically installed. That is, if you want to use the "SunJCE" provider, you need to install the sunjce_provider.jar file as an optional package (extension) and explicitly register the "SunJCE" provider - either statically or dynamically, as described in this section.

In order to statically add "SunJCE" to your list of providers, you need to edit the security properties file to contain a line of the format shown above. For example, to make "SunJCE" the second preferred provider, add the following line to the java.security file below the line for the "SUN" provider:

    security.provider.2=com.sun.crypto.provider.SunJCE
Add similar lines to statically register other providers. For example, suppose that a provider's master class is the CryptoX class in the com.cryptox.provider package, and that you would like to make this provider the third preferred provider, after the "Sun" and "SunJCE" providers. To do so, add the following line to the java.security file below the line for the "SunJCE" provider:
    security.provider.3=com.cryptox.provider.CryptoX

Providers may also be registered dynamically. To do so, a program can call either the addProvider or insertProviderAt method in the Security class. This type of registration is not persistent and can only be done by "trusted" programs. See the Security class section of the Java Cryptography Architecture API Specification and Reference.

An example of dynamic registration of the "SunJCE" provider is the following:

    Provider sunJce = new com.sun.crypto.provider.SunJCE();
    Security.addProvider(sunJce);

JCE Keystore

The "SunJCE" provider supplies its own implementation of the java.security.KeyStore class in J2SDK. Its implementation employs a much stronger protection of private keys (using password-based encryption with Triple DES) than the keystore implementation supplied by the "SUN" provider in J2SDK. (Note that because J2SDK is distributed world-wide in binary and source format, it cannot employ any strong encryption mechanisms.)

In order to take advantage of the keystore implementation of the "SunJCE" provider, you specify "JCEKS" as the keystore type.

You may upgrade your keystore of type "JKS" - this is the name of the keystore type implemented by the "SUN" provider in J2SDK - to a JCE 1.2.1 keystore of type "JCEKS" by changing the password of a private-key entry in your keystore. Note that once you have upgraded your keystore, your keystore can no longer be accessed without JCE 1.2.1 installed.

To apply the cryptographically strong(er) key protection supplied by "SunJCE" to a private key named "signkey" in your default keystore, use the following command, which will prompt you for the old and new key passwords:

    keytool -keypasswd -alias signkey -storetype jceks

You may want to change the password back to its old value, using the same command.

See the keytool user guide for more information about keystores and how they are managed.


Code Examples

This section is a short tutorial on how to use some of the major features of the JCE 1.2.1 APIs. Complete sample programs that exercise the APIs can be found in Appendix D of this document.

Using Encryption

This section takes the user through the process of generating a key, creating and initializing a cipher object, encrypting a file, and then decrypting it. Throughout this example, we use the Data Encryption Standard (DES).

Generating a Key

To create a DES key, we have to instantiate a KeyGenerator for DES. We do not specify a provider, because we do not care about a particular DES key generation implementation. Since we do not initialize the KeyGenerator, a system-provided source of randomness will be used to create the DES key:

    KeyGenerator keygen = KeyGenerator.getInstance("DES");
    SecretKey desKey = keygen.generateKey();

After the key has been generated, the same KeyGenerator object can be re-used to create further keys.

Creating a Cipher

The next step is to create a Cipher instance. To do this, we use one of the getInstance factory methods of the Cipher class. We must specify the name of the requested transformation, which includes the following components, separated by slashes (/):

  • the algorithm name
  • the mode (optional)
  • the padding scheme (optional)

In this example, we create a DES (Data Encryption Standard) cipher in Electronic Codebook mode, with PKCS#5-style padding. We do not specify a provider, because we do not care about a particular implementation of the requested transformation.

The standard algorithm name for DES is "DES", the standard name for the Electronic Codebook mode is "ECB", and the standard name for PKCS#5-style padding is "PKCS5Padding":

    Cipher desCipher;

    // Create the cipher 
    desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");

We use the generated desKey from above to initialize the Cipher object for encryption:

    // Initialize the cipher for encryption
    desCipher.init(Cipher.ENCRYPT_MODE, desKey);

    // Our cleartext
    byte[] cleartext = "This is just an example".getBytes();

    // Encrypt the cleartext
    byte[] ciphertext = desCipher.doFinal(cleartext);

    // Initialize the same cipher for decryption
    desCipher.init(Cipher.DECRYPT_MODE, desKey);

    // Decrypt the ciphertext
    byte[] cleartext1 = desCipher.doFinal(ciphertext);

cleartext and cleartext1 are identical.

Using Password-Based Encryption

In this example, we prompt the user for a password from which we derive an encryption key.

It would seem logical to collect and store the password in an object of type java.lang.String. However, here's the caveat: Objects of type String are immutable, i.e., there are no methods defined that allow you to change (overwrite) or zero out the contents of a String after usage. This feature makes String objects unsuitable for storing security sensitive information such as user passwords. You should always collect and store security sensitive information in a char array instead.

For that reason, the javax.crypto.spec.PBEKeySpec class takes (and returns) a password as a char array.

The following method is an example of how to collect a user password as a char array:

    /**
     * Reads user password from given input stream.
     */
    public char[] readPasswd(InputStream in) throws IOException {
	char[] lineBuffer;
	char[] buf;
	int i;

	buf = lineBuffer = new char[128];

	int room = buf.length;
	int offset = 0;
	int c;

loop:	while (true) {
	    switch (c = in.read()) {
	      case -1: 
	      case '\n':
		break loop;

	      case '\r':
		int c2 = in.read();
		if ((c2 != '\n') && (c2 != -1)) {
		    if (!(in instanceof PushbackInputStream)) {
			in = new PushbackInputStream(in);
		    }
		    ((PushbackInputStream)in).unread(c2);
		} else 
		    break loop;

	      default:
		if (--room < 0) {
		    buf = new char[offset + 128];
		    room = buf.length - offset - 1;
		    System.arraycopy(lineBuffer, 0, buf, 0, offset);
		    Arrays.fill(lineBuffer, ' ');
		    lineBuffer = buf;
		}
		buf[offset++] = (char) c;
		break;
	    }
	}

	if (offset == 0) {
	    return null;
	}

	char[] ret = new char[offset];
	System.arraycopy(buf, 0, ret, 0, offset);
	Arrays.fill(buf, ' ');

	return ret;
    }

In order to use Password-Based Encryption (PBE) as defined in PKCS#5, we have to specify a salt and an iteration count. The same salt and iteration count that are used for encryption must be used for decryption:

    PBEKeySpec pbeKeySpec;
    PBEParameterSpec pbeParamSpec;
    SecretKeyFactory keyFac;

    // Salt
    byte[] salt = {
        (byte)0xc7, (byte)0x73, (byte)0x21, (byte)0x8c,
        (byte)0x7e, (byte)0xc8, (byte)0xee, (byte)0x99
    };

    // Iteration count
    int count = 20;

    // Create PBE parameter set
    pbeParamSpec = new PBEParameterSpec(salt, count);

    // Prompt user for encryption password.
    // Collect user password as char array (using the
    // "readPasswd" method from above), and convert
    // it into a SecretKey object, using a PBE key
    // factory.
    System.out.print("Enter encryption password:  ");
    System.out.flush();
    pbeKeySpec = new PBEKeySpec(readPasswd(System.in));
    keyFac = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
    SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);

    // Create PBE Cipher
    Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");

    // Initialize PBE Cipher with key and parameters
    pbeCipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec);

    // Our cleartext
    byte[] cleartext = "This is another example".getBytes();

    // Encrypt the cleartext
    byte[] ciphertext = pbeCipher.doFinal(cleartext);

Using Key Agreement

Please refer to Appendix D for sample programs exercising the Diffie-Hellman key exchange between 2 and 3 parties, respectively.


Appendix A: Standard Names

The JCE 1.2.1 API requires and utilizes a set of standard names for algorithms, algorithm modes, and padding schemes. This specification establishes the following names as standard names. It supplements the list of standard names defined in Appendix A in the JavaTM Cryptography Architecture API Specification & Reference. Note that algorithm names are treated case-insensitive.

Cipher

Algorithm

The following names can be specified as the algorithm component in a transformation when requesting an instance of Cipher:

  • DES: The Digital Encryption Standard as described in FIPS PUB 46-2.

  • DESede: Triple DES Encryption (DES-EDE).

  • PBEWithMD5AndDES: The password-based encryption algorithm as defined in: RSA Laboratories, "PKCS #5: Password-Based Encryption Standard," version 1.5, Nov 1993. Note that this algorithm implies CBC as the cipher mode and PKCS5Padding as the padding scheme and cannot be used with any other cipher modes or padding schemes.

  • Blowfish: The block cipher designed by Bruce Schneier.

Mode

The following names can be specified as the mode component in a transformation when requesting an instance of Cipher:

  • ECB: Electronic Codebook Mode, as defined in: The National Institute of Standards and Technology (NIST) Federal Information Processing Standard (FIPS) PUB 81, "DES Modes of Operation," U.S. Department of Commerce, Dec 1980.

  • CBC: Cipher Block Chaining Mode, as defined in FIPS PUB 81.

  • CFB: Cipher Feedback Mode, as defined in FIPS PUB 81.

  • OFB: Output Feedback Mode, as defined in FIPS PUB 81.

  • PCBC: Plaintext Cipher Block Chaining, as defined by Kerberos.

Padding

The following names can be specified as the padding component in a transformation when requesting an instance of Cipher:

  • NoPadding: No padding.

  • PKCS5Padding: The padding scheme described in: RSA Laboratories, "PKCS #5: Password-Based Encryption Standard," version 1.5, November 1993.

  • SSL3Padding: The padding scheme defined in the SSL Protocol Version 3.0, November 18, 1996, section 5.2.3.2 (CBC block cipher):
        block-ciphered struct {
            opaque content[SSLCompressed.length];
            opaque MAC[CipherSpec.hash_size];
            uint8 padding[GenericBlockCipher.padding_length];
            uint8 padding_length;
        } GenericBlockCipher;
    

    The size of an instance of a GenericBlockCipher must be a multiple of the block cipher's block length.

    The padding length, which is always present, contributes to the padding, which implies that if:

        sizeof(content) + sizeof(MAC) % block_length = 0, 
    padding has to be (block_length - 1) bytes long, because of the existence of padding_length.

    This make the padding scheme similar (but not quite) to PKCS5Padding, where the padding length is encoded in the padding (and ranges from 1 to block_length). With the SSL scheme, the sizeof(padding) is encoded in the always present padding_length and therefore ranges from 0 to block_length-1.

    Note that this padding mechanism is not supported by the "SunJCE" provider.

KeyAgreement

The following algorithm names can be specified when requesting an instance of KeyAgreement:

KeyGenerator

The following algorithm names can be specified when requesting an instance of KeyGenerator:

KeyPairGenerator

The following algorithm names can be specified when requesting an instance of KeyPairGenerator:

SecretKeyFactory

The following algorithm names can be specified when requesting an instance of SecretKeyFactory:

KeyFactory

The following algorithm names can be specified when requesting an instance of KeyFactory:

AlgorithmParameterGenerator

The following algorithm names can be specified when requesting an instance of AlgorithmParameterGenerator:

AlgorithmParameters

The following algorithm names can be specified when requesting an instance of AlgorithmParameters:

MAC

The following algorithm names can be specified when requesting an instance of Mac:

Keystore Types

The following types can be specified when requesting an instance of KeyStore:


Appendix B: JCE 1.2.1 Jurisdiction Policy Files

The JCE 1.2.1 jurisdiction policy files contain maximum allowable cryptography strength defined by laws (e.g., the U.S. export regulations).

One gets the jurisdiction policy files for the U.S. and Canada when downloading the JCE 1.2.1 software bundle for users within the U.S. and Canada. There is no restriction to the maximum allowable cryptography strength in the jurisdiction policy files for users within the U.S. and Canada.

One gets the jurisdiction policy files for global users when downloading the JCE 1.2.1 software bundle for global users. There are restrictions to the maximum allowable cryptography strength in the jurisdiction policy files for global users. Currently, 512 bits is the maximum allowable keysize for RSA encryption; 64 bits is the maximum allowable keysize for all other encryption algorithms.

The jurisdiction policies are enforced by the JCE 1.2.1 framework. For example, one cannot usually use a Blowfish key of 448 bits with the JCE 1.2.1 software for global users even if there is a provider that supports this keysize for Blowfish, since the global jurisdiction policy files say that the maximum allowable keysize for Blowfish is 64. One can use a Blowfish key of 448 bits with the JCE 1.2.1 software for users within the U.S. and Canada if there is a provider that supports this keysize for Blowfish, since there is no restriction in the jurisdiction policy files for users within the U.S. and Canada.

The only condition under which an application run in a country outside the U.S. and Canada can utilize cryptographic strengths greater than those defined in the global jurisdiction policy files is if the application is "exempt," as described in How to Make Applications "Exempt" from Cryptographic Restrictions.

For more information about application exportability and jurisdiction policy files, see Application Exportability.


Appendix C: SunJCE Default Keysizes

The SunJCE provider uses the following default keysizes:


Appendix D: SunJCE Keysize Restrictions

The SunJCE provider enforces the following restrictions on the keysize passed to the initialization methods of the following classes:


Appendix E: Sample Programs


Copyright © 1996-2000 Sun Microsystems, Inc. All Rights Reserved.

Please send comments to: java-security@java.sun.com.
Sun
Java Software
Last modified: Wed Apr 12 2000