Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/openjdk-multiarch-jdk8u
Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/test/com/sun/crypto/provider/KeyAgreement/DHKeyAgreement2.java
38867 views
1
/*
2
* Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
3
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4
*
5
* This code is free software; you can redistribute it and/or modify it
6
* under the terms of the GNU General Public License version 2 only, as
7
* published by the Free Software Foundation.
8
*
9
* This code is distributed in the hope that it will be useful, but WITHOUT
10
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12
* version 2 for more details (a copy is included in the LICENSE file that
13
* accompanied this code).
14
*
15
* You should have received a copy of the GNU General Public License version
16
* 2 along with this work; if not, write to the Free Software Foundation,
17
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18
*
19
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20
* or visit www.oracle.com if you need additional information or have any
21
* questions.
22
*/
23
24
/*
25
* @test
26
* @bug 7146728
27
* @summary DHKeyAgreement2
28
* @author Jan Luehe
29
* @run main/othervm -Djdk.crypto.KeyAgreement.legacyKDF=true DHKeyAgreement2
30
*/
31
32
import java.io.*;
33
import java.math.BigInteger;
34
import java.security.*;
35
import java.security.spec.*;
36
import java.security.interfaces.*;
37
import javax.crypto.*;
38
import javax.crypto.spec.*;
39
import javax.crypto.interfaces.*;
40
import com.sun.crypto.provider.SunJCE;
41
42
import sun.misc.HexDumpEncoder;
43
44
/**
45
* This test utility executes the Diffie-Hellman key agreement protocol
46
* between 2 parties: Alice and Bob.
47
*
48
* By default, preconfigured parameters (1024 bit prime modulus and base
49
* generator used by SKIP) are used.
50
* If this program is called with the "-gen" option, a new set of parameters
51
* are created.
52
*/
53
54
public class DHKeyAgreement2 {
55
56
private static final String SUNJCE = "SunJCE";
57
private DHKeyAgreement2() {}
58
59
public static void main(String argv[]) throws Exception {
60
String mode = "USE_SKIP_DH_PARAMS";
61
62
DHKeyAgreement2 keyAgree = new DHKeyAgreement2();
63
64
if (argv.length > 1) {
65
keyAgree.usage();
66
throw new Exception("Wrong number of command options");
67
} else if (argv.length == 1) {
68
if (!(argv[0].equals("-gen"))) {
69
keyAgree.usage();
70
throw new Exception("Unrecognized flag: " + argv[0]);
71
}
72
mode = "GENERATE_DH_PARAMS";
73
}
74
75
keyAgree.run(mode);
76
System.out.println("Test Passed");
77
}
78
79
private void run(String mode) throws Exception {
80
81
DHParameterSpec dhSkipParamSpec;
82
83
if (mode.equals("GENERATE_DH_PARAMS")) {
84
// Some central authority creates new DH parameters
85
System.err.println("Creating Diffie-Hellman parameters ...");
86
AlgorithmParameterGenerator paramGen
87
= AlgorithmParameterGenerator.getInstance("DH", SUNJCE);
88
paramGen.init(512);
89
AlgorithmParameters params = paramGen.generateParameters();
90
dhSkipParamSpec = (DHParameterSpec)params.getParameterSpec
91
(DHParameterSpec.class);
92
} else {
93
// use some pre-generated, default DH parameters
94
System.err.println("Using SKIP Diffie-Hellman parameters");
95
dhSkipParamSpec = new DHParameterSpec(skip1024Modulus,
96
skip1024Base);
97
}
98
99
/*
100
* Alice creates her own DH key pair, using the DH parameters from
101
* above
102
*/
103
System.err.println("ALICE: Generate DH keypair ...");
104
KeyPairGenerator aliceKpairGen = KeyPairGenerator.getInstance("DH", SUNJCE);
105
aliceKpairGen.initialize(dhSkipParamSpec);
106
KeyPair aliceKpair = aliceKpairGen.generateKeyPair();
107
System.out.println("Alice DH public key:\n" +
108
aliceKpair.getPublic().toString());
109
System.out.println("Alice DH private key:\n" +
110
aliceKpair.getPrivate().toString());
111
DHParameterSpec dhParamSpec =
112
((DHPublicKey)aliceKpair.getPublic()).getParams();
113
AlgorithmParameters algParams = AlgorithmParameters.getInstance("DH", SUNJCE);
114
algParams.init(dhParamSpec);
115
System.out.println("Alice DH parameters:\n"
116
+ algParams.toString());
117
118
// Alice executes Phase1 of her version of the DH protocol
119
System.err.println("ALICE: Execute PHASE1 ...");
120
KeyAgreement aliceKeyAgree = KeyAgreement.getInstance("DH", SUNJCE);
121
aliceKeyAgree.init(aliceKpair.getPrivate());
122
123
// Alice encodes her public key, and sends it over to Bob.
124
byte[] alicePubKeyEnc = aliceKpair.getPublic().getEncoded();
125
126
/*
127
* Let's turn over to Bob. Bob has received Alice's public key
128
* in encoded format.
129
* He instantiates a DH public key from the encoded key material.
130
*/
131
KeyFactory bobKeyFac = KeyFactory.getInstance("DH", SUNJCE);
132
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec
133
(alicePubKeyEnc);
134
PublicKey alicePubKey = bobKeyFac.generatePublic(x509KeySpec);
135
136
/*
137
* Bob gets the DH parameters associated with Alice's public key.
138
* He must use the same parameters when he generates his own key
139
* pair.
140
*/
141
dhParamSpec = ((DHPublicKey)alicePubKey).getParams();
142
143
// Bob creates his own DH key pair
144
System.err.println("BOB: Generate DH keypair ...");
145
KeyPairGenerator bobKpairGen = KeyPairGenerator.getInstance("DH", SUNJCE);
146
bobKpairGen.initialize(dhParamSpec);
147
KeyPair bobKpair = bobKpairGen.generateKeyPair();
148
System.out.println("Bob DH public key:\n" +
149
bobKpair.getPublic().toString());
150
System.out.println("Bob DH private key:\n" +
151
bobKpair.getPrivate().toString());
152
153
// Bob executes Phase1 of his version of the DH protocol
154
System.err.println("BOB: Execute PHASE1 ...");
155
KeyAgreement bobKeyAgree = KeyAgreement.getInstance("DH", SUNJCE);
156
bobKeyAgree.init(bobKpair.getPrivate());
157
158
// Bob encodes his public key, and sends it over to Alice.
159
byte[] bobPubKeyEnc = bobKpair.getPublic().getEncoded();
160
161
/*
162
* Alice uses Bob's public key for Phase2 of her version of the DH
163
* protocol.
164
* Before she can do so, she has to instanticate a DH public key
165
* from Bob's encoded key material.
166
*/
167
KeyFactory aliceKeyFac = KeyFactory.getInstance("DH", SUNJCE);
168
x509KeySpec = new X509EncodedKeySpec(bobPubKeyEnc);
169
PublicKey bobPubKey = aliceKeyFac.generatePublic(x509KeySpec);
170
System.err.println("ALICE: Execute PHASE2 ...");
171
aliceKeyAgree.doPhase(bobPubKey, true);
172
173
/*
174
* Bob uses Alice's public key for Phase2 of his version of the DH
175
* protocol.
176
*/
177
System.err.println("BOB: Execute PHASE2 ...");
178
bobKeyAgree.doPhase(alicePubKey, true);
179
180
/*
181
* At this stage, both Alice and Bob have completed the DH key
182
* agreement protocol.
183
* Each generates the (same) shared secret.
184
*/
185
byte[] aliceSharedSecret = aliceKeyAgree.generateSecret();
186
int aliceLen = aliceSharedSecret.length;
187
188
// check if alice's key agreement has been reset afterwards
189
try {
190
aliceKeyAgree.generateSecret();
191
throw new Exception("Error: alice's KeyAgreement not reset");
192
} catch (IllegalStateException e) {
193
System.out.println("EXPECTED: " + e.getMessage());
194
}
195
196
byte[] bobSharedSecret = new byte[aliceLen];
197
int bobLen;
198
try {
199
// provide output buffer that is too short
200
bobLen = bobKeyAgree.generateSecret(bobSharedSecret, 1);
201
} catch (ShortBufferException e) {
202
System.out.println("EXPECTED: " + e.getMessage());
203
}
204
// retry w/ output buffer of required size
205
bobLen = bobKeyAgree.generateSecret(bobSharedSecret, 0);
206
207
// check if bob's key agreement has been reset afterwards
208
try {
209
bobKeyAgree.generateSecret(bobSharedSecret, 0);
210
throw new Exception("Error: bob's KeyAgreement not reset");
211
} catch (IllegalStateException e) {
212
System.out.println("EXPECTED: " + e.getMessage());
213
}
214
215
System.out.println("Alice secret: " + toHexString(aliceSharedSecret));
216
System.out.println("Bob secret: " + toHexString(bobSharedSecret));
217
218
if (aliceLen != bobLen) {
219
throw new Exception("Shared secrets have different lengths");
220
}
221
for (int i=0; i<aliceLen; i++) {
222
if (aliceSharedSecret[i] != bobSharedSecret[i]) {
223
throw new Exception("Shared secrets differ");
224
}
225
}
226
System.err.println("Shared secrets are the same");
227
228
// Now let's return the shared secret as a SecretKey object
229
// and use it for encryption
230
System.out.println("Return shared secret as SecretKey object ...");
231
bobKeyAgree.doPhase(alicePubKey, true);
232
SecretKey desKey = bobKeyAgree.generateSecret("DES");
233
234
Cipher desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
235
desCipher.init(Cipher.ENCRYPT_MODE, desKey);
236
237
byte[] cleartext = "This is just an example".getBytes();
238
byte[] ciphertext = desCipher.doFinal(cleartext);
239
240
desCipher.init(Cipher.DECRYPT_MODE, desKey);
241
byte[] cleartext1 = desCipher.doFinal(ciphertext);
242
243
int clearLen = cleartext.length;
244
int clear1Len = cleartext1.length;
245
if (clearLen != clear1Len) {
246
throw new Exception("DIFFERENT");
247
}
248
for (int i=0; i < clear1Len; i++) {
249
if (cleartext[i] != cleartext1[i]) {
250
throw new Exception("DIFFERENT");
251
}
252
}
253
System.err.println("SAME");
254
}
255
256
/*
257
* Converts a byte to hex digit and writes to the supplied buffer
258
*/
259
private void byte2hex(byte b, StringBuffer buf) {
260
char[] hexChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8',
261
'9', 'A', 'B', 'C', 'D', 'E', 'F' };
262
int high = ((b & 0xf0) >> 4);
263
int low = (b & 0x0f);
264
buf.append(hexChars[high]);
265
buf.append(hexChars[low]);
266
}
267
268
/*
269
* Converts a byte array to hex string
270
*/
271
private String toHexString(byte[] block) {
272
StringBuffer buf = new StringBuffer();
273
274
int len = block.length;
275
276
for (int i = 0; i < len; i++) {
277
byte2hex(block[i], buf);
278
if (i < len-1) {
279
buf.append(":");
280
}
281
}
282
return buf.toString();
283
}
284
285
/*
286
* Prints the usage of this test.
287
*/
288
private void usage() {
289
System.err.print("DHKeyAgreement usage: ");
290
System.err.println("[-gen]");
291
}
292
293
// The 1024 bit Diffie-Hellman modulus values used by SKIP
294
private static final byte skip1024ModulusBytes[] = {
295
(byte)0xF4, (byte)0x88, (byte)0xFD, (byte)0x58,
296
(byte)0x4E, (byte)0x49, (byte)0xDB, (byte)0xCD,
297
(byte)0x20, (byte)0xB4, (byte)0x9D, (byte)0xE4,
298
(byte)0x91, (byte)0x07, (byte)0x36, (byte)0x6B,
299
(byte)0x33, (byte)0x6C, (byte)0x38, (byte)0x0D,
300
(byte)0x45, (byte)0x1D, (byte)0x0F, (byte)0x7C,
301
(byte)0x88, (byte)0xB3, (byte)0x1C, (byte)0x7C,
302
(byte)0x5B, (byte)0x2D, (byte)0x8E, (byte)0xF6,
303
(byte)0xF3, (byte)0xC9, (byte)0x23, (byte)0xC0,
304
(byte)0x43, (byte)0xF0, (byte)0xA5, (byte)0x5B,
305
(byte)0x18, (byte)0x8D, (byte)0x8E, (byte)0xBB,
306
(byte)0x55, (byte)0x8C, (byte)0xB8, (byte)0x5D,
307
(byte)0x38, (byte)0xD3, (byte)0x34, (byte)0xFD,
308
(byte)0x7C, (byte)0x17, (byte)0x57, (byte)0x43,
309
(byte)0xA3, (byte)0x1D, (byte)0x18, (byte)0x6C,
310
(byte)0xDE, (byte)0x33, (byte)0x21, (byte)0x2C,
311
(byte)0xB5, (byte)0x2A, (byte)0xFF, (byte)0x3C,
312
(byte)0xE1, (byte)0xB1, (byte)0x29, (byte)0x40,
313
(byte)0x18, (byte)0x11, (byte)0x8D, (byte)0x7C,
314
(byte)0x84, (byte)0xA7, (byte)0x0A, (byte)0x72,
315
(byte)0xD6, (byte)0x86, (byte)0xC4, (byte)0x03,
316
(byte)0x19, (byte)0xC8, (byte)0x07, (byte)0x29,
317
(byte)0x7A, (byte)0xCA, (byte)0x95, (byte)0x0C,
318
(byte)0xD9, (byte)0x96, (byte)0x9F, (byte)0xAB,
319
(byte)0xD0, (byte)0x0A, (byte)0x50, (byte)0x9B,
320
(byte)0x02, (byte)0x46, (byte)0xD3, (byte)0x08,
321
(byte)0x3D, (byte)0x66, (byte)0xA4, (byte)0x5D,
322
(byte)0x41, (byte)0x9F, (byte)0x9C, (byte)0x7C,
323
(byte)0xBD, (byte)0x89, (byte)0x4B, (byte)0x22,
324
(byte)0x19, (byte)0x26, (byte)0xBA, (byte)0xAB,
325
(byte)0xA2, (byte)0x5E, (byte)0xC3, (byte)0x55,
326
(byte)0xE9, (byte)0x2F, (byte)0x78, (byte)0xC7
327
};
328
329
// The SKIP 1024 bit modulus
330
private static final BigInteger skip1024Modulus
331
= new BigInteger(1, skip1024ModulusBytes);
332
333
// The base used with the SKIP 1024 bit modulus
334
private static final BigInteger skip1024Base = BigInteger.valueOf(2);
335
}
336
337