javax.crypto.Cipher

The javax.crypto.Cipher class encapsulates a cipher algorithm. A Cipher either encrypts data or decrypts data. The Cipher class encompasses both asymmetric (public key) and symmetric (private key) algorithms.

This class is part of the JCE, a piece of software that cannot be exported from the United States. For a description of the JCE, refer to Chapter 3. Groups outside the United States have implemented the JCE based on its documentation. Two such implementations are Cryptix (http://www.systemics.com/software/cryptix-java/) and IAIK-JCE (http://www.jce.iaik.tu-graz.ac.at/).

Cipher is an abstract class, so you can’t instantiate it directly. Like the classes in the JCA, it provides factory methods that return useful instances. Using a Cipher is a three-step process:

  1. Obtain a Cipher using the getInstance() factory method.

  2. Initialize the Cipher for encryption or decryption using init(). These methods accept a mode (either Cipher.ENCRYPT_MODE or Cipher.DECRYPT_MODE) and a Key. The type of key you use, public, private, or secret, depends on the Cipher’s algorithm.

  3. Encrypt or decrypt data using the update() and doFinal() methods.

In the SecretWriting example from Chapter 1, for the encrypting case, these steps look like:

Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] raw = cipher.doFinal(stringBytes);

You probably noticed that the call to getInstance() specifies more than just an algorithm name. As a matter of ...

Get Java Cryptography now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.