Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
 package org.bouncycastle.crypto.agreement;
a Diffie-Hellman key exchange engine.

note: This uses MTI/A0 key agreement in order to make the key agreement secure against passive attacks. If you're doing Diffie-Hellman and both parties have long term public keys you should look at using this. For further information have a look at RFC 2631.

It's possible to extend this to more than two parties as well, for the moment that is left as an exercise for the reader.

public class DHAgreement
    private DHPrivateKeyParameters  key;
    private DHParameters            dhParams;
    private BigInteger              privateValue;
    private SecureRandom            random;
    public void init(
        CipherParameters    param)
        AsymmetricKeyParameter  kParam;
        if (param instanceof ParametersWithRandom)
            ParametersWithRandom    rParam = (ParametersWithRandom)param;
            this. = rParam.getRandom();
            kParam = (AsymmetricKeyParameter)rParam.getParameters();
            this. = new SecureRandom();
            kParam = (AsymmetricKeyParameter)param;
        if (!(kParam instanceof DHPrivateKeyParameters))
            throw new IllegalArgumentException("DHEngine expects DHPrivateKeyParameters");
        this. = (DHPrivateKeyParameters)kParam;
        this. = .getParameters();

calculate our initial message.
    public BigInteger calculateMessage()
        DHKeyPairGenerator dhGen = new DHKeyPairGenerator();
        dhGen.init(new DHKeyGenerationParameters());
        AsymmetricCipherKeyPair dhPair = dhGen.generateKeyPair();
        this. = ((DHPrivateKeyParameters)dhPair.getPrivate()).getX();
        return ((DHPublicKeyParameters)dhPair.getPublic()).getY();

given a message from a given party and the corresponding public key, calculate the next message in the agreement sequence. In this case this will represent the shared secret.
        DHPublicKeyParameters   pub,
        BigInteger              message)
        if (!pub.getParameters().equals())
            throw new IllegalArgumentException("Diffie-Hellman public key has wrong parameters.");
        BigInteger p = .getP();
        return message.modPow(.getX(), p).multiply(pub.getY().modPow(p)).mod(p);
New to GrepCode? Check out our FAQ X