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 here 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.