The ElGamalCipher class contains the magic of the ElGamal cipher algorithm. This class indirectly extends javax.crypto.CipherSpi; it lives in the oreilly.jonathan.crypto package along with the rest of the ElGamal classes. Just as the signature classes implemented the methods of SignatureSpi, ElGamalCipher needs to implement the methods of CipherSpi.

To simplify the implementation of the ElGamal cipher, this class is a subclass of BlockCipher, which was presented in Chapter 7. BlockCipher provides buffering and block handling and saves some trouble in implementing the ElGamal algorithm:

package oreilly.jonathan.crypto;

import java.math.BigInteger;

import javax.crypto.*;

public class ElGamalCipher
    extends BlockCipher {

The block sizes of the cipher depend on the size of its key, as discussed earlier. When the cipher is initialized for encryption or decryption, we calculate the size of a plaintext block and the size of a ciphertext block. The key itself and the block sizes are stored in member variables. We also store the state of the cipher (either Cipher.ENCRYPT_MODE or Cipher.DECRYPT_MODE) and whatever SecureRandom is passed to our ElGamalCipher when it is initialized:

  protected int mState;
  protected Key mKey;
  protected SecureRandom mSecureRandom;
  protected int mPlainBlockSize;
  protected int mCipherBlockSize;

This class supports no modes or padding, so engineSetMode() and engineSetPadding() both throw exceptions when called: ...

Get Java Cryptography now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.