~ /code /keyexchange
Code · Key exchange

KeyExchange.java

Define key-pair generation and shared-secret computation for each participant.

35 linesextends ParametersmodPow

Role in the system#

Each instance is one participant. It draws a private key in the range 1 to q − 2 with SecureRandom, publishes α^X mod q, and raises the other side’s public key to its own private exponent.

Source#

KeyExchange.java
import java.math.BigInteger;
import java.security.SecureRandom;

public class KeyExchange extends Parameters {

    private SecureRandom random = new SecureRandom();

    private BigInteger privateKey;
    private BigInteger publicKey;

    public KeyExchange(BigInteger q, BigInteger alpha) {
        super(q, alpha);
        generateKeys();
    }

    private void generateKeys() {
        this.privateKey = new BigInteger(getQ().bitLength(), random)
                .mod(getQ().subtract(BigInteger.TWO))
                .add(BigInteger.ONE);

        this.publicKey = getAlpha().modPow(privateKey, getQ());
    }

    public BigInteger computeSharedKey(BigInteger otherPublic) {
        return otherPublic.modPow(privateKey, getQ());
    }

    public BigInteger getPrivateKey() {
        return privateKey;
    }

    public BigInteger getPublicKey() {
        return publicKey;
    }
}