Skip to main content


developerWorks  >   Java™ technology  >   IBM developer kits  >   Security information  >   6  >  

Security information

The following pages contain documentation, example code, and ancillary files relating to IBM's SDKs. The documentation covers IBM-specific features of IBM's offerings. A platform-specific Security User Guide is included in each download. For information about the SDK for z/OS product and security components specific to that platform, see this Web site.

Before you can download code, you will need an IBM Registration ID. You can read about IBM Registration here.

developerWorks

Java Cryptography Extension

JavaTM Cryptography Extension (JCE)

API Specification & Reference

for IBM's Java 2 SDK, v 6.0

Last Modified: 20th November 2007


Copyright information

Note: Before using this information and the product it supports, be sure to read the general information under Notices.

(c) Copyright Sun Microsystems, Inc. 1998, 2005, 901 San Antonio Rd., Palo Alto, CA 94303 USA. All rights reserved.

(c) Copyright International Business Machines Corporation, 1998, 2007. All rights reserved.

U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP Schedule Contract with IBM Corp.


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

Installing Providers for JCE

JCE Keystore

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


Appendix A: Standard Names

Appendix B: JCE Jurisdiction Policy Files

Appendix C: Maximum Key Sizes Allowed by "Strong" Jurisdiction Policy Files

Appendix D: IBMJCE 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
Other Examples
Appendix F: Warnings

Notices


Introduction

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

The Java Cryptography Extension (JCE) 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 has a provider-based architecture. Providers signed by a trusted entity can be plugged into the JCE framework, and new algorithms can be added seamlessly.

JCE supplemented the Java 2 SDK, Standard Edition, v 1.2 (J2SDK), formerly known as JDKTM version 1.2, which already included interfaces and implementations of message digests and digital signatures. As of the 1.4.2 SDK, JCE is now included as part of the SDK.

JCE 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 API covers:

  • Symmetric bulk encryption, such as DES, RC2, and IDEA

  • Symmetric stream encryption, such as RC4

  • Asymmetric encryption, such as RSA

  • Password-based encryption (PBE)

  • Key Agreement

  • Message Authentication Codes (MAC)

The JCE IBM provider, named "IBMJCE", supplies the following cryptographic services:

  • An implementation of the AES, DES (FIPS PUB 46-1), Triple DES, and Blowfish encryption algorithms in the Electronic Code Book (ECB), Cipher Block Chaining (CBC), Cipher Feedback (CFB), Counter (CTR), Output Feedback (OFB), and Propagating Cipher Block Chaining (PCBC) modes. (Note: Throughout this document, the terms "Triple DES" and "DES-EDE" will be used interchangeably.)

  • Key generators for generating keys suitable for the DES, Triple DES, Blowfish, HMAC-MD5, and HMAC-SHA1 algorithms.

  • An implementation of the MD5 with DES-CBC password-based encryption (PBE) algorithm defined in PKCS #5.

  • "Secret-key factories" providing bi-directional conversions between opaque DES, Triple DES and PBE key objects and transparent representations of their underlying key material.

  • An implementation of the Diffie-Hellman key agreement algorithm between two or more parties.

  • A Diffie-Hellman key pair generator for generating a pair of public and private values suitable for the Diffie-Hellman algorithm.

  • A Diffie-Hellman algorithm parameter generator.

  • A Diffie-Hellman "key factory" providing bi-directional conversions between opaque Diffie-Hellman key objects and transparent representations of their underlying key material.

  • Algorithm parameter managers for Diffie-Hellman, DES, Triple DES, Blowfish, and PBE parameters.

  • An implementation of the HMAC-MD5 and HMAC-SHA1 keyed-hashing algorithms defined in RFC 2104.

  • An implementation of the padding scheme described in PKCS#5.

  • A keystore implementation for the proprietary keystore type named "JCEKS", "PKCS12", "JKS".

  • Later versions of JCE have extended these offerings. See the Crypto Spec for what's new.

A Note on Terminology

The JCE release includes two software components:

  • the framework that defines and supports cryptographic services that providers can supply implementations for. This framework includes everything in the javax.crypto package.

  • a provider named "IBMJCE"
Throughout this document, the term "JCE" refers to the JCE framework. If the full release is mentioned, it will be referred to as "the JCE 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, such as MD5 or SHA-1, in combination with a secret shared key. HMAC is specified in RFC 2104.


Core Classes

  • The Cipher Class

    The Cipher class provides the functionality of a cryptographic cipher used for encryption and decryption. It forms the core of the JCE framework.

    Creating a Cipher Object

    Like other engine classes in the API, Cipher objects are created using the getInstance factory methods of the Cipher class. A factory method is a static method that returns an instance of a class, in this case, an instance of Cipher, which implements a requested transformation.

    To create a Cipher object, you must specify the transformation name. You can also specify which provider you want to supply the implementation of the requested transformation:

     public static Cipher getInstance(String transformation);

    public static Cipher getInstance(String transformation,
    String provider);

    If just a transformation name is specified, the system will determine if there is an implementation of the requested transformation available in the environment, and if there is more than one, whether there is a preferred one.

    If both a transformation name and a package provider are specified, the system will determine if there is an implementation of the requested transformation in the package requested, and throw an exception if there is not.

    A transformation is a string that describes the operation (or set of operations) to be performed on the given input, to produce some output. A transformation always includes the name of a cryptographic algorithm (such as DES), and can be followed by a mode and padding scheme.

    A transformation is of the form:

    For example, the following are valid transformations:

     "DES/CBC/PKCS5Padding"

    "DES"

    If no mode or padding have been specified, provider-specific default values for the mode and padding scheme are used. For example, the IBMJCE provider uses ECB as the default mode, and PKCS5Padding as the default padding scheme for DES, DES-EDE and Blowfish ciphers. This means that in the case of the IBMJCE provider,

     Cipher c1 = Cipher.getInstance("DES/ECB/PKCS5Padding");

    and

     Cipher c1 = Cipher.getInstance("DES");

    are equivalent statements.

    When requesting a block cipher in stream cipher mode (such as DES in CFB or OFB mode), you can optionally specify the number of bits to be processed at a time, by appending this number to the mode name as shown in the "DES/CFB8/NoPadding" and "DES/OFB32/PKCS5Padding" transformations. If no such number is specified, a provider-specific default is used. (For example, the IBMJCE provider uses a default of 64 bits.)

    Appendix A of this document contains a list of standard names that can be used to specify the algorithm name, mode, and padding scheme components of a transformation.

    The objects returned by factory methods are uninitialized, and must be initialized before they become usable.

    Initializing a Cipher Object

    A Cipher object obtained using getInstance must be initialized for one of four modes, which are defined as final integer constants in the Cipher class. The modes can be referenced by their symbolic names, which are shown below along with a description of the purpose of each mode:

    • ENCRYPT_MODE

      Encryption of data.
    • DECRYPT_MODE

      Decryption of data.
    • WRAP_MODE

      Wrapping a Key into bytes so that the key can be securely transported.
    • UNWRAP_MODE

      Unwrapping of a previously wrapped key into a java.security.Key object.

    Each of the Cipher initialization methods takes a mode parameter (opmode), and initializes the Cipher object for that mode. Other parameters include the key (key) or certificate containing the key (certificate), algorithm parameters (params), and a source of randomness (random).

    To initialize a Cipher object, call one of the following init methods:

     public void init(int opmode, Key key);

    public void init(int opmode, Certificate certificate)

    public void init(int opmode, Key key,
    SecureRandom random);

    public void init(int opmode, Certificate certificate,
    SecureRandom random)

    public void init(int opmode, Key key,
    AlgorithmParameterSpec params);

    public void init(int opmode, Key key,
    AlgorithmParameterSpec params,
    SecureRandom random);

    public void init(int opmode, Key key,
    AlgorithmParameters params)

    public void init(int opmode, Key key,
    AlgorithmParameters params,
    SecureRandom random)

    If a Cipher object that requires parameters (such as an initialization vector) is initialized for encryption, and no parameters are supplied to the init method, the underlying cipher implementation is supposed to supply the required parameters itself, either by generating random parameters or by using a default, provider-specific set of parameters.

    However, if a Cipher object that requires parameters is initialized for decryption, and no parameters are supplied to the init method, an InvalidKeyException or InvalidAlgorithmParameterException exception will be raised, depending on the init method that was used.

    See the section about Managing Algorithm Parameters for more details.

    The same parameters that were used for encryption must be used for decryption.

    Note that when a Cipher object is initialized, it loses all of its previously acquired state. In other words, initializing a Cipher is equivalent to creating a new instance of that Cipher, and initializing it. For example, if a Cipher is first initialized for decryption with a given key, and then initialized for encryption, it will lose any state it acquired while in decryption mode.

    Encrypting and Decrypting Data

    Data can be encrypted or decrypted in one step (single-part operation) or in multiple steps (multiple-part operation). A multiple-part operation is useful if you do not know in advance how long the data is going to be, or if the data is too long to be stored in memory all at once.

    To encrypt or decrypt data in a single step, call one of the doFinal methods:

     public byte[] doFinal(byte[] input);

    public byte[] doFinal(byte[] input, int inputOffset,
    int inputLen);

    public int doFinal(byte[] input, int inputOffset,
    int inputLen, byte[] output);

    public int doFinal(byte[] input, int inputOffset,
    int inputLen, byte[] output, int outputOffset)

    To encrypt or decrypt data in multiple steps, call one of the update methods:

     public byte[] update(byte[] input);

    public byte[] update(byte[] input, int inputOffset, int inputLen);

    public int update(byte[] input, int inputOffset, int inputLen,
    byte[] output);

    public int update(byte[] input, int inputOffset, int inputLen,
    byte[] output, int outputOffset)

    A multiple-part operation must be terminated by one of the above doFinal methods (if there is still some input data left for the last step), or by one of the following doFinal methods (if there is no input data left for the last step):

     public byte[] doFinal();

    public int doFinal(byte[] output, int outputOffset);

    All the doFinal methods take care of any necessary padding (or unpadding), if padding (or unpadding) was requested as part of the specified transformation.

    A call to doFinal resets the Cipher object to the state it was in when initialized via a call to init. That is, the Cipher object is reset and available to encrypt or decrypt (depending on the operation mode that was specified in the call to init) more data.

    Wrapping and Unwrapping Keys

    Wrapping a key enables secure transfer of the key from one place to another.

    The wrap/unwrap API makes it more convenient to write code because it works with key objects directly. These methods also enable the possibility of a secure transfer of hardware-based keys.

    To wrap a Key, first initialize the Cipher object for WRAP_MODE, and then call the following:

     public final byte[] wrap(Key key);

    If you are supplying the wrapped key bytes (the result of calling wrap) to someone else who will unwrap them, be sure to also send additional information that the recipient will need in order to do the unwrap:

    • the name of the key algorithm, and

    • the type of the wrapped key (one of SECRET_KEY, PRIVATE_KEY, or PUBLIC_KEY).

    The key algorithm name can be determined by calling the getAlgorithm method from the Key interface:

     public String getAlgorithm();

    To unwrap the bytes returned by a previous call to wrap, first initialize a Cipher object for UNWRAP_MODE, then call the following:

     public final Key unwrap(byte[] wrappedKey,
    String wrappedKeyAlgorithm,
    int wrappedKeyType));

    Here, wrappedKey is the bytes returned from the previous call to wrap, wrappedKeyAlgorithm is the algorithm associated with the wrapped key, and wrappedKeyType is the type of the wrapped key. This value must be one of SECRET_KEY, PRIVATE_KEY, or PUBLIC_KEY.

    Managing Algorithm Parameters

    The parameters being used by the underlying Cipher implementation, which were either explicitly passed to the init method by the application or generated by the underlying implementation itself, can be retrieved from the Cipher object by calling its getParameters method, which returns the parameters as a java.security.AlgorithmParameters object (or null if no parameters are being used). If the parameter is an initialization vector (IV), it can also be retrieved by calling the getIV method.

    In the following example, a Cipher object implementing password-based encryption is initialized with just a key and no parameters. However, the selected algorithm for password-based encryption requires two parameters - a salt and an iteration count. Those parameters will be generated by the underlying algorithm implementation itself. The application can retrieve the generated parameters from the Cipher object as follows:

     import javax.crypto.*;
    import java.security.AlgorithmParameters;

    // get cipher object for password-based encryption
    Cipher c = Cipher.getInstance("PBEWithMD5AndDES");

    // initialize cipher for encryption, without supplying
    // any parameters. Here, "myKey" is assumed to refer
    // to an already-generated key.
    c.init(Cipher.ENCRYPT_MODE, myKey);

    // encrypt some data and store away ciphertext
    // for later decryption
    byte[] cipherText = c.doFinal("This is just an example".getBytes());

    // retrieve parameters generated by underlying cipher
    // implementation
    AlgorithmParameters algParams = c.getParameters();

    // get parameter encoding and store it away
    byte[] encodedAlgParams = algParams.getEncoded();

    The same parameters that were used for encryption must be used for decryption. They can be instantiated from their encoding and used to initialize the corresponding Cipher object for decryption, as follows:

     import javax.crypto.*;
    import java.security.AlgorithmParameters;

    // get parameter object for password-based encryption
    AlgorithmParameters algParams;
    algParams =
    AlgorithmParameters.getInstance("PBEWithMD5AndDES");

    // initialize with parameter encoding from above
    algParams.init(encodedAlgParams);

    // get cipher object for password-based encryption
    Cipher c = Cipher.getInstance("PBEWithMD5AndDES");

    // initialize cipher for decryption, using one of the
    // init() methods that takes an AlgorithmParameters
    // object, and pass it the algParams object from above
    c.init(Cipher.DECRYPT_MODE, myKey, algParams);

    If you did not specify any parameters when you initialized a Cipher object, and you are not sure whether the underlying implementation uses any parameters, you can find out by simply calling the getParameters method of your Cipher object and checking the value returned. A return value of null indicates that no parameters were used.

    The following cipher algorithms implemented by the IBMJCE provider use parameters:

    • DES, DES-EDE, and Blowfish, when used in feedback (such as CBC, CFB, CTR, OFB, or PCBC) mode, use an initialization vector (IV). The javax.crypto.spec.IvParameterSpec class can be used to initialize a Cipher object with a given IV.

    • PBEWithMD5AndDES uses a set of parameters, comprising a salt and an iteration count. The javax.crypto.spec.PBEParameterSpec class can be used to initialize a Cipher object implementing PBEWithMD5AndDES with a given salt and iteration count.

    Note that you do not have to worry about storing or transferring any algorithm parameters for use by the decryption operation if you use the SealedObject class. This class attaches the parameters used for sealing (encryption) to the encrypted object contents, and uses the same parameters for unsealing (decryption).

    Cipher Output Considerations

    Some of the update and doFinal methods of Cipher allow the caller to specify the output buffer into which to encrypt or decrypt the data. In these cases, it is important to pass a buffer that is large enough to hold the result of the encryption or decryption operation.

    The following method in Cipher can be used to determine how big the output buffer should be:

     public int outOutputSize(int inputLen)
  • The Cipher Stream Classes

    JCE introduces the concept of secure streams, which combine an InputStream or OutputStream with a Cipher object. Secure streams are provided by the CipherInputStream and CipherOutputStream classes.

    • The CipherInputStream Class

      This class is a FilterInputStream that encrypts or decrypts the data passing through it. It is composed of an InputStream, or one of its subclasses, and a Cipher. CipherInputStream represents a secure input stream into which a Cipher object has been interposed. The read methods of CipherInputStream return data that are read from the underlying InputStream but have additionally been processed by the embedded Cipher object. The Cipher object must be fully initialized before being used by a CipherInputStream.

      For example, if the embedded Cipher has been initialized for decryption, the CipherInputStream will attempt to decrypt the data it reads from the underlying InputStream before returning it to the application.

      This class adheres strictly to the semantics, especially the failure semantics, of its ancestor classes java.io.FilterInputStream and java.io.InputStream. This class has exactly those methods specified in its ancestor classes, and overrides them all, so that the data is additonally processed by the embedded cipher. Moreover, this class catches all exceptions that are not thrown by its ancestor classes. In particular, the skip(long) method skips only data that has been processed by the Cipher.

      If you use this class, do not use methods that are not defined or that are overridden in this class (such as a new method or constructor that is later added to one of the super classes), because the design and implementation of those methods are unlikely to have considered security impact with regard to CipherInputStream.

      As an example of its usage, suppose cipher1 has been initialized for encryption. The code below demonstrates how to use a CipherInputStream containing that cipher and a FileInputStream in order to encrypt input stream data:

       FileInputStream fis;
      FileOutputStream fos;
      CipherInputStream cis;

      fis = new FileInputStream("/tmp/a.txt");
      cis = new CipherInputStream(fis, cipher1);
      fos = new FileOutputStream("/tmp/b.txt");
      byte[] b = new byte[8];
      int i = cis.read(b);
      while (i != -1) {
      fos.write(b, 0, i);
      i = cis.read(b);
      }

      The above program reads and encrypts the content from the file /tmp/a.txt and then stores the result (the encrypted bytes) in /tmp/b.txt.

      The following example demonstrates how to easily connect several instances of CipherInputStream and FileInputStream. In this example, assume that cipher1 and cipher2 have been initialized for encryption and decryption (with corresponding keys), respectively.

       FileInputStream fis;
      FileOutputStream fos;
      CipherInputStream cis1, cis2;

      fis = new FileInputStream("/tmp/a.txt");
      cis1 = new CipherInputStream(fis, cipher1);
      cis2 = new CipherInputStream(cis1, cipher2);
      fos = new FileOutputStream("/tmp/b.txt");
      byte[] b = new byte[8];
      int i = cis2.read(b);
      while (i != -1) {
      fos.write(b, 0, i);
      i = cis2.read(b);
      }

      The above program copies the content from file /tmp/a.txt to /tmp/b.txt, except that the content is first encrypted and then decrypted back when it is read from /tmp/a.txt. Of course because this program simply encrypts text and decrypts it back right away, it is actually not very useful except as a simple way of illustrating chaining of CipherInputStreams.

    • The CipherOutputStream Class

      This class is a FilterOutputStream that encrypts or decrypts the data passing through it. It is composed of an OutputStream, or one of its subclasses, and a Cipher. CipherOutputStream represents a secure output stream into which a Cipher object has been interposed. The write methods of CipherOutputStream first process the data with the embedded Cipher object before writing it out to the underlying OutputStream. The Cipher object must be fully initialized before being used by a CipherOutputStream.

      For example, if the embedded Cipher has been initialized for encryption, the CipherOutputStream will encrypt its data, before writing them out to the underlying output stream.

      This class adheres strictly to the semantics, especially the failure semantics, of its ancestor classes java.io.OutputStream and java.io.FilterOutputStream. This class has exactly those methods specified in its ancestor classes, and overrides them all, so that all data is additionally processed by the embedded cipher. Moreover, this class catches all exceptions that are not thrown by its ancestor classes.

      If you use this class, do not to use methods that are not defined or that are overridden in this class (such as a new method or constructor that is later added to one of the super classes), because the design and implementation of those methods are unlikely to have considered security impact with regard to CipherOutputStream.

      As an example of its usage, suppose cipher1 has been initialized for encryption. The code below demonstrates how to use a CipherOutputStream containing that cipher and a FileOutputStream in order to encrypt data to be written to an output stream:

       FileInputStream fis;
      FileOutputStream fos;
      CipherOutputStream cos;

      fis = new FileInputStream("/tmp/a.txt");
      fos = new FileOutputStream("/tmp/b.txt");
      cos = new CipherOutputStream(fos, cipher1);
      byte[] b = new byte[8];
      int i = fis.read(b);
      while (i != -1) {
      cos.write(b, 0, i);
      i = fis.read(b);
      }
      cos.flush();

      The above program reads the content from the file /tmp/a.txt, then encrypts and stores the result (the encrypted bytes) in /tmp/b.txt.

      The following example demonstrates how to easily connect several instances of CipherOutputStream and FileOutputStream. In this example, assume that cipher1 and cipher2 have been initialized for decryption and encryption (with corresponding keys), respectively:

       FileInputStream fis;
      FileOutputStream fos;
      CipherOutputStream cos1, cos2;

      fis = new FileInputStream("/tmp/a.txt");
      fos = new FileOutputStream("/tmp/b.txt");
      cos1 = new CipherOutputStream(fos, cipher1);
      cos2 = new CipherOutputStream(cos1, cipher2);
      byte[] b = new byte[8];
      int i = fis.read(b);
      while (i != -1) {
      cos2.write(b, 0, i);
      i = fis.read(b);
      }
      cos2.flush();

      The above program copies the content from file /tmp/a.txt to /tmp/b.txt, except that the content is first encrypted and then decrypted back before it is written to /tmp/b.txt.

      There is one important difference between the flush and close methods of this class, which becomes even more relevant if the encapsulated Cipher object implements a block cipher algorithm with padding turned on:

      • flush flushes the underlying OutputStream by forcing any buffered output bytes that have already been processed by the encapsulated Cipher object to be written out. Any bytes buffered by the encapsulated Cipher object and waiting to be processed by it will not be written out.

      • close closes the underlying OutputStream and releases any system resources associated with it. It invokes the doFinal method of the encapsulated Cipher object, causing any bytes buffered by it to be processed and written out to the underlying stream by calling its flush method.

  • The KeyGenerator Class

    A key generator is used to generate secret keys for symmetric algorithms.

    Creating a Key Generator

    Like other engine classes in the API, KeyGenerator objects are created using the getInstance factory methods of the KeyGenerator class. A factory method is a static method that returns an instance of a class, in this case, an instance of KeyGenerator which provides an implementation of the requested key generator.

    getInstance takes as its argument the name of a symmetric algorithm for which a secret key is to be generated. Optionally, a package provider name may be specified:

     public static KeyGenerator getInstance(String algorithm);

    public static KeyGenerator getInstance(String algorithm,
    String provider);

    If only an algorithm name is specified, the system will determine if there is an implementation of the requested key generator available in the environment, and if there is more than one, whether there is a preferred one.

    If both an algorithm name and a package provider are specified, the system will determine if there is an implementation of the requested key generator in the package requested, and will throw an exception if there is not.

    Initializing a KeyGenerator Object

    A key generator for a particular symmetric-key algorithm creates a symmetric key that can be used with that algorithm. It also associates algorithm-specific parameters (if any) with the generated key.

    There are two ways to generate a key: in an algorithm-independent manner and in an algorithm-specific manner. The only difference between the two is the initialization of the object:

    • Algorithm-Independent Initialization

      All key generators share the concepts of a keysize and a source of randomness. There is an init method that takes these two universally shared types of arguments. There is also one that takes just a keysize argument, and uses a system-provided source of randomness, and one that takes just a source of randomness:

       public void init(SecureRandom random);

      public void init(int keysize);

      public void init(int keysize, SecureRandom random);

      Because no other parameters are specified when you call the above algorithm-independent init methods, it is up to the provider what to do about the algorithm-specific parameters (if any) to be associated with the generated key.

    • Algorithm-Specific Initialization

      For situations where a set of algorithm-specific parameters already exists, there are two init methods that have an AlgorithmParameterSpec argument. One also has a SecureRandom argument, while the source of randomness is system-provided for the other:

       public void init(AlgorithmParameterSpec params);

      public void init(AlgorithmParameterSpec params,
      SecureRandom random);

    In case the client does not explicitly initialize the KeyGenerator (through a call to an init method), each provider must supply (and document) a default initialization.

    Creating a Key

    The following method generates a secret key:
     public SecretKey generateKey();
  • The SecretKeyFactory Class

    This class represents a factory for secret keys.

    Key factories are used to convert keys (opaque cryptographic keys of type java.security.Key) into key specifications (transparent representations of the underlying key material in a suitable format), and vice versa.

    A javax.crypto.SecretKeyFactory object operates only on secret (symmetric) keys, whereas a java.security.KeyFactory object processes the public and private key components of a key pair.

    Objects of type java.security.Key, of which java.security.PublicKey, java.security.PrivateKey, and javax.crypto.SecretKey are subclasses, are opaque key objects, because you cannot tell how they are implemented. The underlying implementation is provider-dependent, and can be software or hardware based. Key factories allow providers to supply their own implementations of cryptographic keys.

    For example, if you have a key specification for a Diffie Hellman public key, consisting of the public value y, the prime modulus p, and the base g, and you feed the same specification to Diffie-Hellman key factories from different providers, the resulting PublicKey objects will most likely have different underlying implementations.

    A provider should document the key specifications supported by its secret key factory. For example, the SecretKeyFactory for DES keys supplied by the "IBMJCE" provider supports DESKeySpec as a transparent representation of DES keys, the SecretKeyFactory for DES-EDE keys supports DESedeKeySpec as a transparent representation of DES-EDE keys, and the SecretKeyFactory for PBE supports PBEKeySpec as a transparent representation of the underlying password.

    The following is an example of how to use a SecretKeyFactory to convert secret key data into a SecretKey object, which can be used for a subsequent Cipher operation:

     // Note the following bytes are not realistic secret key data 
    // bytes but are simply supplied as an illustration of using data
    // bytes (key material) you already have to build a DESKeySpec.
    byte[] desKeyData = { (byte)0x01, (byte)0x02, (byte)0x03,
    (byte)0x04, (byte)0x05, (byte)0x06, (byte)0x07, (byte)0x08 };
    DESKeySpec desKeySpec = new DESKeySpec(desKeyData);
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
    SecretKey secretKey = keyFactory.generateSecret(desKeySpec);

    In this case, the underlying implementation of secretKey is based on the provider of keyFactory.

    An alternative, provider-independent way of creating a functionally equivalent SecretKey object from the same key material is to use the javax.crypto.spec.SecretKeySpec class, which implements the javax.crypto.SecretKey interface:

     byte[] desKeyData = { (byte)0x01, (byte)0x02, ...};
    SecretKeySpec secretKey = new SecretKeySpec(desKeyData, "DES");
  • The SealedObject Class

    This class enables you to create an object and protect its confidentiality with a cryptographic algorithm.

    Given any object that implements the java.io.Serializable interface, you can create a SealedObject that encapsulates the original object, in serialized format (that is, a "deep copy"), and seals (encrypts) its serialized contents, using a cryptographic algorithm such as DES, to protect its confidentiality. The encrypted content can later be decrypted (with the corresponding algorithm using the correct decryption key) and de-serialized, yielding the original object.

    A typical usage is illustrated in the following code segment: In order to seal an object, you create a SealedObject from the object to be sealed and a fully initialized Cipher object that will encrypt the serialized object contents. In this example, the String "This is a secret" is sealed using the DES algorithm. Note that any algorithm parameters that can be used in the sealing operation are stored inside of SealedObject:

     // create Cipher object
    // Note: sKey is assumed to refer to an already-generated
    // secret DES key.
    Cipher c = Cipher.getInstance("DES");
    c.init(Cipher.ENCRYPT_MODE, sKey);

    // do the sealing
    SealedObject so = new SealedObject("This is a secret", c);

    The original object that was sealed can be recovered in two different ways:

    • using a Cipher object that has been initialized with the exact same algorithm, key, padding scheme, and so on, that were used to seal the object:

       c.init(Cipher.DECRYPT_MODE, sKey);
      try {
      String s = (String)so.getObject(c);
      } catch (Exception e) {
      // do something
      };

      This approach has the advantage that the party who unseals the sealed object does not require knowledge of the decryption key. For example, after one party has initialized the cipher object with the required decryption key, it could hand over the cipher object to another party who then unseals the sealed object.

    • using the appropriate decryption key (because DES is a symmetric encryption algorithm, we use the same key for sealing and unsealing):

       try {
      String s = (String)so.getObject(sKey);
      } catch (Exception e) {
      // do something
      };

      In this approach, the getObject method creates a cipher object for the appropriate decryption algorithm and initializes it with the given decryption key and the algorithm parameters (if any) that were stored in the sealed object. This approach has the advantage that the party who unseals the object does not need to keep track of the parameters (for example, the IV) that were used to seal the object.

  • The KeyAgreement Class

    The KeyAgreement class provides the functionality of a key agreement protocol. The keys involved in establishing a shared secret are created by one of the key generators (KeyPairGenerator or KeyGenerator), a KeyFactory, or as a result from an intermediate phase of the key agreement protocol.

    Creating a KeyAgreement Object

    Each party involved in the key agreement has to create a KeyAgreement object. Like other engine classes in the API, KeyAgreement objects are created using the getInstance factory methods of the KeyAgreement class. A factory method is a static method that returns an instance of a class, in this case, an instance of KeyAgreement, which provides the requested key agreement algorithm.

    getInstance takes as its argument the name of a key agreement algorithm. Optionally, a package provider name can be specified:

     public static KeyAgreement getInstance(String algorithm);

    public static KeyAgreement getInstance(String algorithm,
    String provider);

    If just an algorithm name is specified, the system will determine if there is an implementation of the requested key agreement available in the environment, and if there is more than one, whether there is a preferred one.

    If both an algorithm name and a package provider are specified, the system will determine if there is an implementation of the requested key agreement in the package requested, and throw an exception if there is not.

    Initializing a KeyAgreement Object

    You initialize a KeyAgreement object with your private information. In the case of Diffie-Hellman, you initialize it with your Diffie-Hellman private key. Additional initialization information might contain a source of randomness and/or a set of algorithm parameters. Note that if the requested key agreement algorithm requires the specification of algorithm parameters, and only a key, but no parameters are provided to initialize the KeyAgreement object, the key must contain the required algorithm parameters. (For example, the Diffie-Hellman algorithm uses a prime modulus p and a base generator g as its parameters.)

    To initialize a KeyAgreement object, call one of its init methods:

     public void init(Key key);

    public void init(Key key, SecureRandom random);

    public void init(Key key, AlgorithmParameterSpec params);

    public void init(Key key, AlgorithmParameterSpec params,
    SecureRandom random);

    Executing a KeyAgreement Phase

    Every key agreement protocol consists of a number of phases that need to be executed by each party involved in the key agreement.

    To execute the next phase in the key agreement, call the doPhase method:

     public Key doPhase(Key key, boolean lastPhase);

    The key parameter contains the key to be processed by that phase. In most cases, this is the public key of one of the other parties involved in the key agreement, or an intermediate key that was generated by a previous phase. doPhase might return an intermediate key that you might have to send to the other parties of this key agreement, so they can process it in a subsequent phase.

    The lastPhase parameter specifies whether or not the phase to be executed is the last one in the key agreeement: A value of FALSE indicates that this is not the last phase of the key agreement (there are more phases to follow), and a value of TRUE indicates that this is the last phase of the key agreement and the key agreement is completed, i.e., generateSecret can be called next.

    In the example of Diffie-Hellman between two parties (see Appendix D), you call doPhase once, with lastPhase set to TRUE. In the example of Diffie-Hellman between three parties, you call doPhase twice: the first time with lastPhase set to FALSE, the 2nd time with lastPhase set to TRUE.

    Generating the Shared Secret

    After each party has executed all the required key agreement phases, it can compute the shared secret by calling one of the generateSecret methods:

     public byte[] generateSecret();

    public int generateSecret(byte[] sharedSecret, int offset);

    public SecretKey generateSecret(String algorithm);
  • The Mac Class

    The Mac class provides the functionality of a Message Authentication Code (MAC). Please refer to the code example in Appendix D.

    Creating a Mac Object

    Like other engine classes in the API, Mac objects are created using the getInstance factory methods of the Mac class. A factory method is a static method that returns an instance of a class, in this case, an instance of Mac, which provides the requested MAC algorithm.

    getInstance takes as its argument the name of a MAC algorithm. Optionally, a package provider name can be specified:

     public static Mac getInstance(String algorithm);

    public static Mac getInstance(String algorithm,
    String provider);

    If just an algorithm name is specified, the system will determine if there is an implementation of the requested MAC algorithm available in the environment, and if there is more than one, whether there is a preferred one.

    If both an algorithm name and a package provider are specified, the system will determine if there is an implementation of the requested MAC algorithm in the package requested, and throw an exception if there is not.

    Initializing a Mac Object

    A Mac object is always initialized with a (secret) key and can optionally be initialized with a set of parameters, depending on the underlying MAC algorithm.

    To initialize a Mac object, call one of its init methods:

     public void init(Key key);

    public void init(Key key, AlgorithmParameterSpec params);

    You can initialize your Mac object with any (secret-)key object that implements the javax.crypto.SecretKey interface. This object could be one that is returned by javax.crypto.KeyGenerator.generateKey(), or one that is the result of a key agreement protocol, as returned by javax.crypto.KeyAgreement.generateSecret(), or an instance of javax.crypto.spec.SecretKeySpec.

    With some MAC algorithms, the (secret-)key algorithm associated with the (secret-)key object used to initialize the Mac object does not matter (this is the case with the HMAC-MD5 and HMAC-SHA1 implementations of the IBMJCE provider). With others, however, the (secret-)key algorithm does matter, and an InvalidKeyException is thrown if a (secret-)key object with an inappropriate (secret-)key algorithm is used.

    Computing a MAC

    A MAC can be computed in one step (single-part operation) or in multiple steps (multiple-part operation). A multiple-part operation is useful if you do not know in advance how long the data is going to be, or if the data is too long to be stored in memory all at once.

    To compute the MAC of some data in a single step, call the following doFinal method:

     public byte[] doFinal(byte[] input);

    To compute the MAC of some data in multiple steps, call one of the update methods:

     public void update(byte input);

    public void update(byte[] input);

    public void update(byte[] input, int inputOffset, int inputLen);

    A multiple-part operation must be terminated by the above doFinal method (if there is still some input data left for the last step), or by one of the following doFinal methods (if there is no input data left for the last step):

     public byte[] doFinal();

    public void doFinal(byte[] output, int outOffset);

Application Exportability

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 (and later) 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 the JCE framework.

The JCE 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 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 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 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 framework.

JCE comes with two JAR files:

  • US_export_policy.jar
    containing policy files representing U.S. government export rules.
  • local_policy.jar
    containing policy files intended to represent local government restrictions. (Note: At this time, the local jurisdiction policy files are not actually country-specific; everyone not in the U.S. or Canada gets the same "local" policy files.).

These JAR files are signed by the same entity 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 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, 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 need.

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. When JCE is running such applications, for each cryptography algorithm utilized, JCE 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. (When applications are unrestricted the JAR files for domestic users do not currently contain any exempt policy files, and 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 of the application, and the conditions (if any) for those permissions. 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 string in quotation marks specifying the standard name of a cryptography algorithm, such as "DES" or "RSA".

The <exemption mechanism name>, when specified, is a string in quotation marks 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 might 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 quotation) for an <alg_name> option means "all algorithms."


How to Make Applications "Exempt" from Cryptographic Restrictions

[Note 1: This section is applicable developers. It is only for people whose applications can 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 can 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:

  • It must have a permission policy file bundled with it in a JAR file. The permission policy file specifies the cryptography-related permissions pf the application, and conditions (if any) of those permissions.

  • The JAR file containing the application and the permission policy file must have been signed using a code-signing certificate issued after the application was accepted as exempt by the U.S. government.

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 code searches the installed providers for one that implements the specified exemption mechanism. If it finds such a provider, JCE 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 (using 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.

After 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 the cryptography-related permissions of the application, and the conditions (if any) of those permissions.

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, 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 (such as 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 make this specification, 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" when 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 exemption mechanism names that can be used are:

  • 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, 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 (through a call to its getInstance method) and that application has an associated permission policy file, JCE 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 files 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 allowed only 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 you should 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>

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

    This command 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 ("<" and ">") represent the actual values that must be supplied. For example, <alias> must be replaced with whatever alias name you want 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 the commands 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, using email, the CSR and contact information to javasec@us.ibm.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 e-mail 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.

    After 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 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 the one that 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 (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 using the following command:

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 (because 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 distribution. 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 that implements the exemption mechanism must be installed. Therefore, 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 Installing Providers for JCE.

Note: The "IBMJCE" provider 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 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 algorithms 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 that your application will utilize. (You can generate a key of a particular size by, for example, using a javax.crypto.KeyGenerator and calling its i