FileDocCategorySizeDatePackage
DHAgreement.javaAPI DocExample5032Sat Jan 13 14:02:46 GMT 2001javasec.samples.ch10

DHAgreement.java

package javasec.samples.ch10;

import java.math.*;
import java.security.*;
import java.security.spec.*;

import javax.crypto.*;
import javax.crypto.spec.*;
import javax.crypto.interfaces.*;

public class DHAgreement implements Runnable {
    byte bob[], alice[];
    boolean doneAlice = false;
    byte[] ciphertext;

    BigInteger aliceP, aliceG;
    int aliceL;

    public synchronized void run() {
        if (!doneAlice) {
            doneAlice = true;
            doAlice();
        }
        else doBob();
    }

    public synchronized void doAlice() {
        try {
            // Step 1:  Alice generates a key pair
            KeyPairGenerator kpg = KeyPairGenerator.getInstance("DH");
            kpg.initialize(1024);
            KeyPair kp = kpg.generateKeyPair();
            
            // Step 2:  Alice sends the public key and the
            //         Diffie-Hellman key parameters to Bob
            Class dhClass = Class.forName(
                                "javax.crypto.spec.DHParameterSpec");
            DHParameterSpec dhSpec = (
                            (DHPublicKey) kp.getPublic()).getParams();
            aliceG = dhSpec.getG();
            aliceP = dhSpec.getP();
            aliceL = dhSpec.getL();
            alice = kp.getPublic().getEncoded();
            notify();

            // Step 4 part 1:  Alice performs the first phase of the
            //        protocol with her private key
            KeyAgreement ka = KeyAgreement.getInstance("DH");
            ka.init(kp.getPrivate());

            // Step 4 part 2:  Alice performs the second phase of the
            //        protocol with Bob