01: package org.bouncycastle.crypto.agreement;
02:
03: import java.math.BigInteger;
04:
05: import org.bouncycastle.crypto.BasicAgreement;
06: import org.bouncycastle.crypto.CipherParameters;
07: import org.bouncycastle.crypto.params.DHParameters;
08: import org.bouncycastle.crypto.params.DHPublicKeyParameters;
09: import org.bouncycastle.crypto.params.DHPrivateKeyParameters;
10: import org.bouncycastle.crypto.params.AsymmetricKeyParameter;
11: import org.bouncycastle.crypto.params.ParametersWithRandom;
12:
13: /**
14: * a Diffie-Hellman key agreement class.
15: * <p>
16: * note: This is only the basic algorithm, it doesn't take advantage of
17: * long term public keys if they are available. See the DHAgreement class
18: * for a "better" implementation.
19: */
20: public class DHBasicAgreement implements BasicAgreement {
21: private DHPrivateKeyParameters key;
22: private DHParameters dhParams;
23:
24: public void init(CipherParameters param) {
25: AsymmetricKeyParameter kParam;
26:
27: if (param instanceof ParametersWithRandom) {
28: ParametersWithRandom rParam = (ParametersWithRandom) param;
29: kParam = (AsymmetricKeyParameter) rParam.getParameters();
30: } else {
31: kParam = (AsymmetricKeyParameter) param;
32: }
33:
34: if (!(kParam instanceof DHPrivateKeyParameters)) {
35: throw new IllegalArgumentException(
36: "DHEngine expects DHPrivateKeyParameters");
37: }
38:
39: this .key = (DHPrivateKeyParameters) kParam;
40: this .dhParams = key.getParameters();
41: }
42:
43: /**
44: * given a short term public key from a given party calculate the next
45: * message in the agreement sequence.
46: */
47: public BigInteger calculateAgreement(CipherParameters pubKey) {
48: DHPublicKeyParameters pub = (DHPublicKeyParameters) pubKey;
49:
50: if (!pub.getParameters().equals(dhParams)) {
51: throw new IllegalArgumentException(
52: "Diffie-Hellman public key has wrong parameters.");
53: }
54:
55: return pub.getY().modPow(key.getX(), dhParams.getP());
56: }
57: }
|