blob: 6359ecdbd76d02bcc746058ef2ffd2f6d3572d84 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
|
package org.spongycastle.crypto.agreement;
import java.math.BigInteger;
import org.spongycastle.crypto.BasicAgreement;
import org.spongycastle.crypto.CipherParameters;
import org.spongycastle.crypto.params.AsymmetricKeyParameter;
import org.spongycastle.crypto.params.DHParameters;
import org.spongycastle.crypto.params.DHPrivateKeyParameters;
import org.spongycastle.crypto.params.DHPublicKeyParameters;
import org.spongycastle.crypto.params.ParametersWithRandom;
/**
* a Diffie-Hellman key agreement class.
* <p>
* note: This is only the basic algorithm, it doesn't take advantage of
* long term public keys if they are available. See the DHAgreement class
* for a "better" implementation.
*/
public class DHBasicAgreement
implements BasicAgreement
{
private DHPrivateKeyParameters key;
private DHParameters dhParams;
public void init(
CipherParameters param)
{
AsymmetricKeyParameter kParam;
if (param instanceof ParametersWithRandom)
{
ParametersWithRandom rParam = (ParametersWithRandom)param;
kParam = (AsymmetricKeyParameter)rParam.getParameters();
}
else
{
kParam = (AsymmetricKeyParameter)param;
}
if (!(kParam instanceof DHPrivateKeyParameters))
{
throw new IllegalArgumentException("DHEngine expects DHPrivateKeyParameters");
}
this.key = (DHPrivateKeyParameters)kParam;
this.dhParams = key.getParameters();
}
public int getFieldSize()
{
return (key.getParameters().getP().bitLength() + 7) / 8;
}
/**
* given a short term public key from a given party calculate the next
* message in the agreement sequence.
*/
public BigInteger calculateAgreement(
CipherParameters pubKey)
{
DHPublicKeyParameters pub = (DHPublicKeyParameters)pubKey;
if (!pub.getParameters().equals(dhParams))
{
throw new IllegalArgumentException("Diffie-Hellman public key has wrong parameters.");
}
return pub.getY().modPow(key.getX(), dhParams.getP());
}
}
|