1:
37:
38:
39: package ;
40:
41: import ;
42:
43: import ;
44:
45: import ;
46: import ;
47: import ;
48: import ;
49: import ;
50: import ;
51:
52: import ;
53: import ;
54: import ;
55: import ;
56: import ;
57: import ;
58:
59:
64: public final class DiffieHellmanImpl extends KeyAgreementSpi
65: {
66:
67:
68: private DHPrivateKey key;
69:
70:
71: private BigInteger result;
72:
73:
74: private boolean last_phase_done;
75:
76:
77: public DiffieHellmanImpl ()
78: {
79: key = null;
80: result = null;
81: last_phase_done = false;
82: }
83:
84:
85:
86: protected Key engineDoPhase (final Key incoming, final boolean lastPhase)
87: throws InvalidKeyException
88: {
89: if (key == null)
90: throw new IllegalStateException ("not initialized");
91: if (last_phase_done)
92: throw new IllegalStateException ("last phase already done");
93:
94: if (!(incoming instanceof DHPublicKey))
95: throw new InvalidKeyException ("expecting javax.crypto.interfaces.DHPublicKey");
96: DHPublicKey pub = (DHPublicKey) incoming;
97: DHParameterSpec s1 = key.getParams();
98: DHParameterSpec s2 = pub.getParams();
99: if (!s1.getG().equals (s2.getG())
100: || !s1.getP().equals (s2.getP())
101: || s1.getL() != s2.getL())
102: throw new InvalidKeyException ("supplied key is not compatible");
103:
104: result = pub.getY().modPow (key.getX(), s1.getP());
105: if (lastPhase)
106: {
107: last_phase_done = true;
108: return null;
109: }
110:
111: throw new IllegalArgumentException ("only supports two-party Diffie Hellman");
112: }
113:
114: protected byte[] engineGenerateSecret ()
115: {
116: if (result == null || !last_phase_done)
117: throw new IllegalStateException ("not finished");
118:
119: byte[] buf = result.toByteArray ();
120: if (buf[0] == 0x00)
121: {
122: byte[] buf2 = new byte[buf.length - 1];
123: System.arraycopy (buf, 1, buf2, 0, buf2.length);
124: buf = buf2;
125: }
126: return buf;
127: }
128:
129: protected int engineGenerateSecret (final byte[] secret, final int offset)
130: {
131: byte[] s = engineGenerateSecret();
132: System.arraycopy (s, 0, secret, offset, s.length);
133: return s.length;
134: }
135:
136: protected SecretKey engineGenerateSecret (final String algorithm)
137: throws InvalidKeyException
138: {
139: byte[] s = engineGenerateSecret();
140: return new SecretKeySpec (s, algorithm);
141: }
142:
143: protected void engineInit (final Key key, final SecureRandom random)
144: throws InvalidKeyException
145: {
146: if (!(key instanceof DHPrivateKey))
147: throw new InvalidKeyException ("not a javax.crypto.interfaces.DHPrivateKey");
148: this.key = (DHPrivateKey) key;
149: result = null;
150: last_phase_done = false;
151: }
152:
153: protected void engineInit (final Key key, final AlgorithmParameterSpec params,
154: final SecureRandom random)
155: throws InvalidKeyException
156: {
157: engineInit (key, random);
158: }
159: }