Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/mobile
Path: blob/master/test/jdk/sun/security/provider/SecureRandom/DrbgCavp.java
41155 views
1
/*
2
* Copyright (c) 2016, 2018, 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
import sun.security.provider.EntropySource;
25
import sun.security.provider.MoreDrbgParameters;
26
27
import javax.crypto.Cipher;
28
import java.io.BufferedReader;
29
import java.io.ByteArrayOutputStream;
30
import java.io.File;
31
import java.io.InputStream;
32
import java.io.InputStreamReader;
33
import java.io.PrintStream;
34
import java.lang.*;
35
import java.security.NoSuchAlgorithmException;
36
import java.security.SecureRandom;
37
import java.security.DrbgParameters;
38
import java.util.ArrayDeque;
39
import java.util.Arrays;
40
import java.util.Queue;
41
import java.util.stream.Stream;
42
import java.util.zip.ZipEntry;
43
import java.util.zip.ZipFile;
44
import java.util.zip.ZipInputStream;
45
46
import static java.security.DrbgParameters.Capability.*;
47
48
/**
49
* The Known-output DRBG test. The test vector can be downloaded from
50
* https://csrc.nist.gov/CSRC/media/Projects/Cryptographic-Algorithm-Validation-Program/documents/drbg/drbgtestvectors.zip.
51
* The test is described on https://csrc.nist.gov/Projects/Cryptographic-Algorithm-Validation-Program/Random-Number-Generators.
52
*
53
* Manually run this test with
54
*
55
* java DrbgCavp drbgtestvectors.zip
56
*
57
*/
58
public class DrbgCavp {
59
60
// the current nonce
61
private static byte[] nonce;
62
63
// A buffer to store test materials for the current call and
64
// can be printed out of an error occurs.
65
private static ByteArrayOutputStream bout = new ByteArrayOutputStream();
66
67
// Save err for restoring
68
private static PrintStream err = System.err;
69
70
private static final int AES_LIMIT;
71
72
static {
73
try {
74
AES_LIMIT = Cipher.getMaxAllowedKeyLength("AES");
75
} catch (Exception e) {
76
// should not happen
77
throw new AssertionError("Cannot detect AES");
78
}
79
}
80
81
public static void main(String[] args) throws Exception {
82
83
if (args.length != 1) {
84
System.out.println("Usage: java DrbgCavp drbgtestvectors.zip");
85
return;
86
}
87
File tv = new File(args[0]);
88
89
EntropySource es = new TestEntropySource();
90
System.setErr(new PrintStream(bout));
91
92
// The testsuite is a zip file containing more zip files for different
93
// working modes. Each internal zip file contains test materials for
94
// different mechanisms.
95
96
try (ZipFile zf = new ZipFile(tv)) {
97
String[] modes = {"no_reseed", "pr_false", "pr_true"};
98
for (String mode : modes) {
99
try (ZipInputStream zis = new ZipInputStream(zf.getInputStream(
100
zf.getEntry("drbgvectors_" + mode + ".zip")))) {
101
while (true) {
102
ZipEntry ze = zis.getNextEntry();
103
if (ze == null) {
104
break;
105
}
106
String fname = ze.getName();
107
if (fname.equals("Hash_DRBG.txt")
108
|| fname.equals("HMAC_DRBG.txt")
109
|| fname.equals("CTR_DRBG.txt")) {
110
String algorithm
111
= fname.substring(0, fname.length() - 4);
112
test(mode, algorithm, es, zis);
113
}
114
}
115
}
116
}
117
} finally {
118
System.setErr(err);
119
}
120
}
121
122
/**
123
* A special entropy source you can set entropy input at will.
124
*/
125
private static class TestEntropySource implements EntropySource {
126
127
private static Queue<byte[]> data = new ArrayDeque<>();
128
129
@Override
130
public byte[] getEntropy(int minEntropy, int minLength,
131
int maxLength, boolean pr) {
132
byte[] result = data.poll();
133
if (result == null
134
|| result.length < minLength
135
|| result.length > maxLength) {
136
throw new RuntimeException("Invalid entropy: " +
137
"need [" + minLength + ", " + maxLength + "], " +
138
(result == null ? "none" : "has " + result.length));
139
}
140
return result;
141
}
142
143
private static void setEntropy(byte[] input) {
144
data.offer(input);
145
}
146
147
private static void clearEntropy() {
148
data.clear();
149
}
150
}
151
152
/**
153
* The test.
154
*
155
* // Algorithm line, might contain usedf flag
156
* [AES-128 use df]
157
* // Ignored, use mode argument
158
* [PredictionResistance = True]
159
* // Ignored, just read EntropyInput
160
* [EntropyInputLen = 128]
161
* // Ignored, just read Nonce
162
* [NonceLen = 64]
163
* // Ignored, just read PersonalizationString
164
* [PersonalizationStringLen = 128]
165
* // Ignored, just read AdditionalInput
166
* [AdditionalInputLen = 128]
167
* // Used to allocate buffer for nextBytes() call
168
* [ReturnedBitsLen = 512]
169
*
170
* // A sign we can ignore old unused entropy input
171
* COUNT = 0
172
*
173
* // Instantiate
174
* EntropyInput = 92898f...
175
* Nonce = c2a4d9...
176
* PersonalizationString = ea65ee... // Enough to call getInstance()
177
*
178
* // Reseed
179
* EntropyInputReseed = bfd503...
180
* AdditionalInputReseed = 009e0b... // Enough to call reseed()
181
*
182
* // Generation
183
* AdditionalInput = 1a40fa.... // Enough to call nextBytes() for PR off
184
* EntropyInputPR = 20728a... // Enough to call nextBytes() for PR on
185
* ReturnedBits = 5a3539... // Compare this to last nextBytes() output
186
*
187
* @param mode one of "no_reseed", "pr_false", "pr_true"
188
* @param mech one of "Hash_DRBG", "HMAC_DRBG", "CTR_DRBG"
189
* @param es our own entropy source
190
* @param is test material
191
*/
192
private static void test(String mode, String mech, EntropySource es,
193
InputStream is) throws Exception {
194
195
SecureRandom hd = null;
196
197
// Expected output length in bits as in [ReturnedBitsLen]
198
int outLen = 0;
199
200
// DRBG algorithm as in the algorithm line
201
String algorithm = null;
202
203
// When CTR_DRBG uses a derivation function as in the algorithm line
204
boolean usedf = false;
205
206
// Additional input as in "AdditionalInput"
207
byte[] additional = null;
208
209
// Random bits generated
210
byte[] output = null;
211
212
// Prediction resistance flag, determined by mode
213
boolean isPr = false;
214
215
StringBuilder sb = new StringBuilder();
216
217
int lineno = 0;
218
219
System.out.println(mode + "/" + mech);
220
221
try (Stream<String> lines =
222
new BufferedReader(new InputStreamReader(is)).lines()) {
223
for (String s: (Iterable<String>) lines::iterator) {
224
lineno++;
225
err.print(hd == null ? '-' : '*');
226
Line l = new Line(s);
227
if (l.key.contains("no df") || l.key.contains("use df") ||
228
l.key.startsWith("SHA-")) {
229
sb = new StringBuilder();
230
bout.reset();
231
}
232
sb.append(String.format(
233
"%9s %4s %5d %s\n", mode, mech, lineno, s));
234
switch (l.key) {
235
case "3KeyTDEA no df":
236
case "AES-128 no df":
237
case "AES-192 no df":
238
case "AES-256 no df":
239
case "3KeyTDEA use df":
240
case "AES-128 use df":
241
case "AES-192 use df":
242
case "AES-256 use df":
243
algorithm = l.key.split(" ")[0];
244
usedf = l.key.contains("use df");
245
break;
246
case "ReturnedBitsLen":
247
outLen = l.vint();
248
output = new byte[outLen / 8];
249
break;
250
case "EntropyInput":
251
TestEntropySource.setEntropy(l.vdata());
252
break;
253
case "Nonce":
254
nonce = l.vdata();
255
break;
256
case "COUNT":
257
// Remove unused entropy (say, when AES-256 is skipped)
258
TestEntropySource.clearEntropy();
259
break;
260
case "PersonalizationString":
261
try {
262
isPr = mode.equals("pr_true");
263
byte[] ps = null;
264
if (l.vdata().length != 0) {
265
ps = l.vdata();
266
}
267
268
// MoreDrbgParameters must be used because we
269
// want to set entropy input and nonce. Since
270
// it can also set mechanism, algorithm and usedf,
271
// we don't need to touch securerandom.drbg.config.
272
hd = SecureRandom.getInstance("DRBG",
273
new MoreDrbgParameters(es, mech, algorithm,
274
nonce, usedf,
275
DrbgParameters.instantiation(
276
-1,
277
isPr ? PR_AND_RESEED
278
: RESEED_ONLY,
279
ps)),
280
"SUN");
281
} catch (NoSuchAlgorithmException iae) {
282
// We don't support SHA-1 and 3KeyTDEA. AES-192 or
283
// AES-256 might not be available. This is OK.
284
if (algorithm.equals("SHA-1") ||
285
algorithm.equals("3KeyTDEA") ||
286
((algorithm.equals("AES-192")
287
|| algorithm.equals("AES-256"))
288
&& AES_LIMIT == 128)) {
289
hd = null;
290
} else {
291
throw iae;
292
}
293
}
294
break;
295
case "EntropyInputReseed":
296
TestEntropySource.setEntropy(l.vdata());
297
break;
298
case "AdditionalInputReseed":
299
if (l.vdata().length == 0) {
300
additional = null;
301
} else {
302
additional = l.vdata();
303
}
304
if (hd != null) {
305
if (additional == null) {
306
hd.reseed();
307
} else {
308
hd.reseed(DrbgParameters.reseed(
309
isPr, additional));
310
}
311
}
312
break;
313
case "EntropyInputPR":
314
if (l.vdata().length != 0) {
315
TestEntropySource.setEntropy(l.vdata());
316
}
317
if (mode.equals("pr_true")) {
318
if (hd != null) {
319
if (additional == null) {
320
hd.nextBytes(output);
321
} else {
322
hd.nextBytes(output,
323
DrbgParameters.nextBytes(
324
-1, isPr, additional));
325
}
326
}
327
}
328
break;
329
case "AdditionalInput":
330
if (l.vdata().length == 0) {
331
additional = null;
332
} else {
333
additional = l.vdata();
334
}
335
if (!mode.equals("pr_true")) {
336
if (hd != null) {
337
if (additional == null) {
338
hd.nextBytes(output);
339
} else {
340
hd.nextBytes(output,
341
DrbgParameters.nextBytes(
342
-1, isPr, additional));
343
}
344
}
345
}
346
break;
347
case "ReturnedBits":
348
if (hd != null) {
349
if (!Arrays.equals(output, l.vdata())) {
350
throw new Exception("\nExpected: " +
351
l.value + "\n Actual: " + hex(output));
352
}
353
}
354
break;
355
default:
356
// Algorithm line for Hash_DRBG and HMAC_DRBG
357
if (l.key.startsWith("SHA-")) {
358
algorithm = l.key;
359
}
360
}
361
}
362
err.println();
363
} catch (Exception e) {
364
err.println();
365
err.println(sb.toString());
366
err.println(bout.toString());
367
throw e;
368
}
369
}
370
371
/**
372
* Parse a line from test material.
373
*
374
* Brackets are removed. Key and value separated.
375
*/
376
static class Line {
377
378
final String key;
379
final String value;
380
381
Line(String s) {
382
s = s.trim();
383
if (s.length() >= 2) {
384
if (s.charAt(0) == '[') {
385
s = s.substring(1, s.length() - 1);
386
}
387
}
388
if (s.indexOf('=') < 0) {
389
key = s;
390
value = null;
391
} else {
392
key = s.substring(0, s.indexOf('=')).trim();
393
value = s.substring(s.indexOf('=') + 1).trim();
394
}
395
}
396
397
int vint() {
398
return Integer.parseInt(value);
399
}
400
401
byte[] vdata() {
402
return xeh(value);
403
}
404
}
405
406
// Bytes to HEX
407
private static String hex(byte[] in) {
408
StringBuilder sb = new StringBuilder();
409
for (byte b: in) {
410
sb.append(String.format("%02x", b&0xff));
411
}
412
return sb.toString();
413
}
414
415
// HEX to bytes
416
private static byte[] xeh(String in) {
417
in = in.replaceAll(" ", "");
418
int len = in.length() / 2;
419
byte[] out = new byte[len];
420
for (int i = 0; i < len; i++) {
421
out[i] = (byte) Integer.parseInt(
422
in.substring(i * 2, i * 2 + 2), 16);
423
}
424
return out;
425
}
426
}
427
428