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