Generating Keys

Key Classes

As shown earlier, an ElGamal public key consists of p, g, and y. The matching private key is x. We’ll need classes to encapsulate these values.

If you look back at the algorithm for verifying a signature, you’ll notice it uses not only x, but p and g as well. Thus, we’ll make our private key class contain p, g, and x. The public and private key classes then both descend from ElGamalKey, which is simply a container for p and g.

package oreilly.jonathan.crypto;

import java.math.BigInteger;
import java.security.*;

public class ElGamalKey
    implements Key {
  private BigInteger mP, mG;
  
  protected ElGamalKey(BigInteger g, BigInteger p) {
    mG = g;
    mP = p;
  }
  
  protected BigInteger getG() { return mG; }
  protected BigInteger getP() { return mP; }
  
  public String getAlgorithm() { return "ElGamal"; }
  public String getFormat() { return "NONE"; }
  public byte[] getEncoded() { return null; }
}

The ElGamal public key consists of p, g, and y. Because p and g are already contained in ElGamalKey, the public key class has to contain just y:

package oreilly.jonathan.crypto;

import java.math.BigInteger;
import java.security.*;

public class ElGamalPublicKey
    extends ElGamalKey
    implements PublicKey {
  private BigInteger mY;
  
  protected ElGamalPublicKey(BigInteger y, BigInteger g, BigInteger p) {
    super(g, p);
    mY = y;
  }
  
  protected BigInteger getY() { return mY; }
}

And ElGamalPrivateKey simply holds x:

package oreilly.jonathan.crypto; import java.math.BigInteger; import java.security.*; public class ...

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.