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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
|
/*
* ECTester, tool for testing Elliptic curve cryptography implementations.
* Copyright (c) 2016-2018 Petr Svenda <petr@svenda.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package cz.crcs.ectester.standalone;
import cz.crcs.ectester.common.cli.*;
import cz.crcs.ectester.common.ec.EC_Curve;
import cz.crcs.ectester.common.output.TestWriter;
import cz.crcs.ectester.common.test.TestException;
import cz.crcs.ectester.common.util.ByteUtil;
import cz.crcs.ectester.common.util.ECUtil;
import cz.crcs.ectester.data.EC_Store;
import cz.crcs.ectester.standalone.consts.KeyAgreementIdent;
import cz.crcs.ectester.standalone.consts.KeyPairGeneratorIdent;
import cz.crcs.ectester.standalone.consts.SignatureIdent;
import cz.crcs.ectester.standalone.libs.*;
import cz.crcs.ectester.standalone.output.TextTestWriter;
import cz.crcs.ectester.standalone.output.XMLTestWriter;
import cz.crcs.ectester.standalone.output.YAMLTestWriter;
import cz.crcs.ectester.standalone.test.suites.StandaloneDefaultSuite;
import cz.crcs.ectester.standalone.test.suites.StandaloneTestSuite;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import javax.crypto.KeyAgreement;
import javax.crypto.SecretKey;
import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.Field;
import java.nio.file.Files;
import java.security.*;
import java.security.interfaces.ECPrivateKey;
import java.security.interfaces.ECPublicKey;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.ECGenParameterSpec;
import java.security.spec.ECParameterSpec;
import java.util.*;
import java.util.stream.Collectors;
/**
* Standalone part of ECTester, a tool for testing Elliptic curve implementations in software libraries.
*
* @author Jan Jancar johny@neuromancer.sk
* @version v0.3.0
*/
public class ECTesterStandalone {
private ProviderECLibrary[] libs = new ProviderECLibrary[]{
new SunECLib(),
new BouncyCastleLib(),
new TomcryptLib(),
new BotanLib(),
new CryptoppLib(),
new OpensslLib(),
new BoringsslLib(),
new GcryptLib(),
new MscngLib(),
new WolfCryptLib()};
private Config cfg;
private Options opts = new Options();
private TreeParser optParser;
private TreeCommandLine cli;
public static final String VERSION = "v0.3.0";
private static final String DESCRIPTION = "ECTesterStandalone " + VERSION + ", an Elliptic Curve Cryptography support tester/utility.";
private static final String LICENSE = "MIT Licensed\nCopyright (c) 2016-2018 Petr Svenda <petr@svenda.com>";
private static final String CLI_HEADER = "\n" + DESCRIPTION + "\n\n";
private static final String CLI_FOOTER = "\n" + LICENSE;
private void run(String[] args) {
try {
cli = parseArgs(args);
if (cli.hasOption("version")) {
CLITools.version(DESCRIPTION, LICENSE);
return;
} else if (cli.hasOption("help") || cli.getNext() == null) {
String command = cli.getOptionValue("help");
if (command == null) {
CLITools.help("ECTesterStandalone.jar", CLI_HEADER, opts, optParser, CLI_FOOTER, true);
} else {
CLITools.help(CLI_HEADER, optParser, CLI_FOOTER, command);
}
return;
}
for (ECLibrary lib : libs) {
lib.initialize();
}
cfg = new Config(libs);
if (!cfg.readOptions(cli)) {
return;
}
if (cli.isNext("list-libs")) {
listLibraries();
} else if (cli.isNext("list-data")) {
CLITools.listNamed(EC_Store.getInstance(), cli.getNext().getArg(0));
} else if (cli.isNext("list-suites")) {
listSuites();
} else if (cli.isNext("ecdh")) {
ecdh();
} else if (cli.isNext("ecdsa")) {
ecdsa();
} else if (cli.isNext("generate")) {
generate();
} else if (cli.isNext("test")) {
test();
} else if (cli.isNext("export")) {
export();
}
} catch (ParseException | ParserConfigurationException | IOException ex) {
System.err.println(ex.getMessage());
} catch (InvalidAlgorithmParameterException | InvalidParameterException e) {
System.err.println("Invalid algorithm parameter: " + e.getMessage());
} catch (NoSuchAlgorithmException nsaex) {
System.err.println("Algorithm not supported by the selected library: " + nsaex.getMessage());
nsaex.printStackTrace();
} catch (InvalidKeyException | SignatureException e) {
e.printStackTrace();
}
}
private TreeCommandLine parseArgs(String[] args) throws ParseException {
Map<String, ParserOptions> actions = new TreeMap<>();
Option namedCurve = Option.builder("nc").longOpt("named-curve").desc("Use a named curve, from CurveDB: <cat/id>").hasArg().argName("cat/id").optionalArg(false).build();
Option curveName = Option.builder("cn").longOpt("curve-name").desc("Use a named curve, search from curves supported by the library: <name>").hasArg().argName("name").optionalArg(false).build();
Option bits = Option.builder("b").longOpt("bits").hasArg().argName("n").optionalArg(false).desc("What size of curve to use.").build();
Options testOpts = new Options();
testOpts.addOption(bits);
testOpts.addOption(namedCurve);
testOpts.addOption(curveName);
testOpts.addOption(Option.builder("gt").longOpt("kpg-type").desc("Set the KeyPairGenerator object [type].").hasArg().argName("type").optionalArg(false).build());
testOpts.addOption(Option.builder("kt").longOpt("ka-type").desc("Set the KeyAgreement object [type].").hasArg().argName("type").optionalArg(false).build());
testOpts.addOption(Option.builder("st").longOpt("sig-type").desc("Set the Signature object [type].").hasArg().argName("type").optionalArg(false).build());
testOpts.addOption(Option.builder("f").longOpt("format").desc("Set the output format, one of text,yaml,xml.").hasArg().argName("format").optionalArg(false).build());
testOpts.addOption(Option.builder().longOpt("key-type").desc("Set the key [algorithm] for which the key should be derived in KeyAgreements with KDF. Default is \"AES\".").hasArg().argName("algorithm").optionalArg(false).build());
List<Argument> testArgs = new LinkedList<>();
testArgs.add(new Argument("test-suite", "The test suite to run.", true));
ParserOptions test = new ParserOptions(new TreeParser(Collections.emptyMap(), true, testArgs), testOpts, "Test a library.");
actions.put("test", test);
Options ecdhOpts = new Options();
ecdhOpts.addOption(bits);
ecdhOpts.addOption(namedCurve);
ecdhOpts.addOption(curveName);
ecdhOpts.addOption(Option.builder("t").longOpt("type").desc("Set KeyAgreement object [type].").hasArg().argName("type").optionalArg(false).build());
ecdhOpts.addOption(Option.builder().longOpt("key-type").desc("Set the key [algorithm] for which the key should be derived in KeyAgreements with KDF. Default is \"AES\".").hasArg().argName("algorithm").optionalArg(false).build());
ecdhOpts.addOption(Option.builder("n").longOpt("amount").hasArg().argName("amount").optionalArg(false).desc("Do ECDH [amount] times.").build());
ParserOptions ecdh = new ParserOptions(new DefaultParser(), ecdhOpts, "Perform EC based KeyAgreement.");
actions.put("ecdh", ecdh);
Options ecdsaOpts = new Options();
ecdsaOpts.addOption(bits);
ecdsaOpts.addOption(namedCurve);
ecdsaOpts.addOption(curveName);
ecdsaOpts.addOption(Option.builder("t").longOpt("type").desc("Set Signature object [type].").hasArg().argName("type").optionalArg(false).build());
ecdsaOpts.addOption(Option.builder("n").longOpt("amount").hasArg().argName("amount").optionalArg(false).desc("Do ECDSA [amount] times.").build());
ecdsaOpts.addOption(Option.builder("f").longOpt("file").hasArg().argName("file").optionalArg(false).desc("Input [file] to sign.").build());
ParserOptions ecdsa = new ParserOptions(new DefaultParser(), ecdsaOpts, "Perform EC based Signature.");
actions.put("ecdsa", ecdsa);
Options generateOpts = new Options();
generateOpts.addOption(bits);
generateOpts.addOption(namedCurve);
generateOpts.addOption(curveName);
generateOpts.addOption(Option.builder("n").longOpt("amount").hasArg().argName("amount").optionalArg(false).desc("Generate [amount] of EC keys.").build());
generateOpts.addOption(Option.builder("t").longOpt("type").hasArg().argName("type").optionalArg(false).desc("Set KeyPairGenerator object [type].").build());
ParserOptions generate = new ParserOptions(new DefaultParser(), generateOpts, "Generate EC keypairs.");
actions.put("generate", generate);
Options exportOpts = new Options();
exportOpts.addOption(bits);
exportOpts.addOption(Option.builder("t").longOpt("type").hasArg().argName("type").optionalArg(false).desc("Set KeyPair object [type].").build());
ParserOptions export = new ParserOptions(new DefaultParser(), exportOpts, "Export default curve parameters.");
actions.put("export", export);
Options listDataOpts = new Options();
List<Argument> listDataArgs = new LinkedList<>();
listDataArgs.add(new Argument("what", "what to list.", false));
ParserOptions listData = new ParserOptions(new TreeParser(Collections.emptyMap(), false, listDataArgs), listDataOpts, "List/show contained EC domain parameters/keys.");
actions.put("list-data", listData);
Options listLibsOpts = new Options();
ParserOptions listLibs = new ParserOptions(new DefaultParser(), listLibsOpts, "List supported libraries.");
actions.put("list-libs", listLibs);
Options listSuitesOpts = new Options();
ParserOptions listSuites = new ParserOptions(new DefaultParser(), listSuitesOpts, "List supported test suites.");
actions.put("list-suites", listSuites);
List<Argument> baseArgs = new LinkedList<>();
baseArgs.add(new Argument("lib", "What library to use.", false));
optParser = new TreeParser(actions, false, baseArgs);
opts.addOption(Option.builder("V").longOpt("version").desc("Print version info.").build());
opts.addOption(Option.builder("h").longOpt("help").desc("Print help(about <command>).").hasArg().argName("command").optionalArg(true).build());
opts.addOption(Option.builder("C").longOpt("color").desc("Print stuff with color, requires ANSI terminal.").build());
return optParser.parse(opts, args);
}
/**
*
*/
private void listLibraries() {
for (ProviderECLibrary lib : libs) {
if (lib.isInitialized() && (cfg.selected == null || lib == cfg.selected)) {
System.out.println("\t- " + Colors.bold(lib.name()));
Set<KeyPairGeneratorIdent> kpgs = lib.getKPGs();
if (!kpgs.isEmpty()) {
System.out.println(Colors.bold("\t\t- KeyPairGenerators: ") + String.join(", ", kpgs.stream().map(KeyPairGeneratorIdent::getName).collect(Collectors.toList())));
}
Set<KeyAgreementIdent> eckas = lib.getKAs();
if (!eckas.isEmpty()) {
System.out.println(Colors.bold("\t\t- KeyAgreements: ") + String.join(", ", eckas.stream().map(KeyAgreementIdent::getName).collect(Collectors.toList())));
}
Set<SignatureIdent> sigs = lib.getSigs();
if (!sigs.isEmpty()) {
System.out.println(Colors.bold("\t\t- Signatures: ") + String.join(", ", sigs.stream().map(SignatureIdent::getName).collect(Collectors.toList())));
}
Set<String> curves = lib.getCurves();
if (!curves.isEmpty()) {
System.out.println(Colors.bold("\t\t- Curves: ") + String.join(", ", curves));
}
System.out.println();
}
}
}
/**
*
*/
private void listSuites() {
StandaloneTestSuite[] suites = new StandaloneTestSuite[]{new StandaloneDefaultSuite(null, null, null)};
for (StandaloneTestSuite suite : suites) {
System.out.println(" - " + suite.getName());
for (String line : suite.getDescription()) {
System.out.println("\t" + line);
}
}
}
/**
*
*/
private void ecdh() throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException {
ProviderECLibrary lib = cfg.selected;
String algo = cli.getOptionValue("ecdh.type", "ECDH");
String keyAlgo = cli.getOptionValue("ecdh.key-type", "AES");
KeyAgreementIdent kaIdent = lib.getKAs().stream()
.filter((ident) -> ident.contains(algo))
.findFirst()
.orElse(null);
String baseAlgo;
if (algo.contains("with")) {
baseAlgo = algo.split("with")[0];
} else {
baseAlgo = algo;
}
KeyPairGeneratorIdent kpIdent = lib.getKPGs().stream()
.filter((ident) -> ident.contains(algo))
.findFirst()
.orElse(lib.getKPGs().stream()
.filter((ident) -> ident.contains(baseAlgo))
.findFirst()
.orElse(lib.getKPGs().stream()
.filter((ident) -> ident.contains("ECDH"))
.findFirst()
.orElse(lib.getKPGs().stream()
.filter((ident) -> ident.contains("EC"))
.findFirst()
.orElse(null))));
if (kaIdent == null || kpIdent == null) {
throw new NoSuchAlgorithmException(algo);
} else {
KeyAgreement ka = kaIdent.getInstance(lib.getProvider());
KeyPairGenerator kpg = kpIdent.getInstance(lib.getProvider());
AlgorithmParameterSpec spec = null;
if (cli.hasOption("ecdh.bits")) {
int bits = Integer.parseInt(cli.getOptionValue("ecdh.bits"));
kpg.initialize(bits);
} else if (cli.hasOption("ecdh.named-curve")) {
String curveName = cli.getOptionValue("ecdh.named-curve");
EC_Curve curve = EC_Store.getInstance().getObject(EC_Curve.class, curveName);
if (curve == null) {
System.err.println("Curve not found: " + curveName);
return;
}
spec = curve.toSpec();
kpg.initialize(spec);
} else if (cli.hasOption("ecdh.curve-name")) {
String curveName = cli.getOptionValue("ecdh.curve-name");
spec = new ECGenParameterSpec(curveName);
kpg.initialize(spec);
}
System.out.println("index;nanotime;pubW;privS;secret");
int amount = Integer.parseInt(cli.getOptionValue("ecdh.amount", "1"));
for (int i = 0; i < amount; ++i) {
KeyPair one = kpg.genKeyPair();
KeyPair other = kpg.genKeyPair();
ECPrivateKey privkey = (ECPrivateKey) one.getPrivate();
ECPublicKey pubkey = (ECPublicKey) other.getPublic();
long elapsed = -System.nanoTime();
if (spec instanceof ECParameterSpec) {
ka.init(privkey, spec);
} else {
ka.init(privkey);
}
ka.doPhase(pubkey, true);
elapsed += System.nanoTime();
SecretKey derived;
byte[] result;
elapsed -= System.nanoTime();
if (kaIdent.requiresKeyAlgo()) {
derived = ka.generateSecret(keyAlgo);
result = derived.getEncoded();
} else {
result = ka.generateSecret();
}
elapsed += System.nanoTime();
ka = kaIdent.getInstance(lib.getProvider());
String pub = ByteUtil.bytesToHex(ECUtil.toX962Uncompressed(pubkey.getW(), pubkey.getParams()), false);
String priv = ByteUtil.bytesToHex(privkey.getS().toByteArray(), false);
String dh = ByteUtil.bytesToHex(result, false);
System.out.println(String.format("%d;%d;%s;%s;%s", i, elapsed, pub, priv, dh));
}
}
}
/**
*
*/
private void ecdsa() throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, IOException, SignatureException {
byte[] data;
String dataString;
if (cli.hasOption("ecdsa.file")) {
String fileName = cli.getOptionValue("ecdsa.file");
File in = new File(fileName);
long len = in.length();
if (len == 0) {
throw new FileNotFoundException(fileName);
}
data = Files.readAllBytes(in.toPath());
dataString = "";
} else {
SecureRandom random = new SecureRandom();
data = new byte[32];
random.nextBytes(data);
dataString = ByteUtil.bytesToHex(data, false);
}
ProviderECLibrary lib = cfg.selected;
String algo = cli.getOptionValue("ecdsa.type", "ECDSA");
SignatureIdent sigIdent = lib.getSigs().stream()
.filter((ident) -> ident.contains(algo))
.findFirst()
.orElse(null);
String baseAlgo;
if (algo.contains("with")) {
baseAlgo = algo.split("with")[1];
} else {
baseAlgo = algo;
}
KeyPairGeneratorIdent kpIdent = lib.getKPGs().stream()
.filter((ident) -> ident.contains(algo))
.findFirst()
.orElse(lib.getKPGs().stream()
.filter((ident) -> ident.contains(baseAlgo))
.findFirst()
.orElse(lib.getKPGs().stream()
.filter((ident) -> ident.contains("ECDSA"))
.findFirst()
.orElse(lib.getKPGs().stream()
.filter((ident) -> ident.contains("EC"))
.findFirst()
.orElse(null))));
if (sigIdent == null || kpIdent == null) {
throw new NoSuchAlgorithmException(algo);
} else {
Signature sig = sigIdent.getInstance(lib.getProvider());
KeyPairGenerator kpg = kpIdent.getInstance(lib.getProvider());
if (cli.hasOption("ecdsa.bits")) {
int bits = Integer.parseInt(cli.getOptionValue("ecdsa.bits"));
kpg.initialize(bits);
} else if (cli.hasOption("ecdsa.named-curve")) {
String curveName = cli.getOptionValue("ecdsa.named-curve");
EC_Curve curve = EC_Store.getInstance().getObject(EC_Curve.class, curveName);
if (curve == null) {
System.err.println("Curve not found: " + curveName);
return;
}
kpg.initialize(curve.toSpec());
} else if (cli.hasOption("ecdsa.curve-name")) {
String curveName = cli.getOptionValue("ecdsa.curve-name");
kpg.initialize(new ECGenParameterSpec(curveName));
}
System.out.println("index;data;signtime;verifytime;pubW;privS;signature;verified");
int amount = Integer.parseInt(cli.getOptionValue("ecdsa.amount", "1"));
for (int i = 0; i < amount; ++i) {
KeyPair one = kpg.genKeyPair();
ECPrivateKey privkey = (ECPrivateKey) one.getPrivate();
ECPublicKey pubkey = (ECPublicKey) one.getPublic();
sig.initSign(privkey);
sig.update(data);
long signTime = -System.nanoTime();
byte[] signature = sig.sign();
signTime += System.nanoTime();
sig.initVerify(pubkey);
sig.update(data);
long verifyTime = -System.nanoTime();
boolean verified = sig.verify(signature);
verifyTime += System.nanoTime();
String pub = ByteUtil.bytesToHex(ECUtil.toX962Uncompressed(pubkey.getW(), pubkey.getParams()), false);
String priv = ByteUtil.bytesToHex(privkey.getS().toByteArray(), false);
String sign = ByteUtil.bytesToHex(signature, false);
System.out.println(String.format("%d;%s;%d;%d;%s;%s;%s;%d", i, dataString, signTime, verifyTime, pub, priv, sign, verified ? 1 : 0));
}
}
}
/**
*
*/
private void generate() throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {
ProviderECLibrary lib = cfg.selected;
KeyPairGeneratorIdent ident = null;
String algo = cli.getOptionValue("generate.type", "EC");
for (KeyPairGeneratorIdent kpIdent : lib.getKPGs()) {
if (kpIdent.contains(algo)) {
ident = kpIdent;
break;
}
}
if (ident == null) {
throw new NoSuchAlgorithmException(algo);
} else {
KeyPairGenerator kpg = ident.getInstance(lib.getProvider());
if (cli.hasOption("generate.bits")) {
int bits = Integer.parseInt(cli.getOptionValue("generate.bits"));
kpg.initialize(bits);
} else if (cli.hasOption("generate.named-curve")) {
String curveName = cli.getOptionValue("generate.named-curve");
EC_Curve curve = EC_Store.getInstance().getObject(EC_Curve.class, curveName);
if (curve == null) {
System.err.println("Curve not found: " + curveName);
return;
}
kpg.initialize(curve.toSpec());
} else if (cli.hasOption("generate.curve-name")) {
String curveName = cli.getOptionValue("generate.curve-name");
kpg.initialize(new ECGenParameterSpec(curveName));
}
System.out.println("index;nanotime;pubW;privS");
int amount = Integer.parseInt(cli.getOptionValue("generate.amount", "1"));
for (int i = 0; i < amount; ++i) {
long elapsed = -System.nanoTime();
KeyPair kp = kpg.genKeyPair();
elapsed += System.nanoTime();
ECPublicKey publicKey = (ECPublicKey) kp.getPublic();
ECPrivateKey privateKey = (ECPrivateKey) kp.getPrivate();
String pub = ByteUtil.bytesToHex(ECUtil.toX962Uncompressed(publicKey.getW(), publicKey.getParams()), false);
String priv = ByteUtil.bytesToHex(privateKey.getS().toByteArray(), false);
System.out.println(String.format("%d;%d;%s;%s", i, elapsed, pub, priv));
}
}
}
/**
*
*/
private void test() throws TestException, ParserConfigurationException {
TestWriter writer;
switch (cli.getOptionValue("test.format", "text").toLowerCase()) {
case "yaml":
case "yml":
writer = new YAMLTestWriter(System.out);
break;
case "xml":
writer = new XMLTestWriter(System.out);
break;
case "text":
default:
writer = new TextTestWriter(System.out);
break;
}
String suiteName = cli.getArg(0);
StandaloneTestSuite suite = new StandaloneDefaultSuite(writer, cfg, cli);
suite.run();
}
/**
*
*/
private void export() throws NoSuchAlgorithmException, IOException {
ProviderECLibrary lib = cfg.selected;
KeyPairGeneratorIdent ident = null;
String algo = cli.getOptionValue("export.type", "EC");
for (KeyPairGeneratorIdent kpIdent : lib.getKPGs()) {
if (kpIdent.contains(algo)) {
ident = kpIdent;
break;
}
}
if (ident == null) {
throw new NoSuchAlgorithmException(algo);
} else {
KeyPairGenerator kpg = ident.getInstance(lib.getProvider());
if (cli.hasOption("export.bits")) {
int bits = Integer.parseInt(cli.getOptionValue("export.bits"));
kpg.initialize(bits);
}
KeyPair kp = kpg.genKeyPair();
ECPrivateKey privateKey = (ECPrivateKey) kp.getPrivate();
ECParameterSpec params = privateKey.getParams();
System.out.println(params);
EC_Curve curve = EC_Curve.fromSpec(params);
curve.writeCSV(System.out);
}
}
public static void main(String[] args) {
ECTesterStandalone app = new ECTesterStandalone();
app.run(args);
}
/**
*
*/
public static class Config {
private ProviderECLibrary[] libs;
public ProviderECLibrary selected = null;
public boolean color = false;
public Config(ProviderECLibrary[] libs) {
this.libs = libs;
}
boolean readOptions(TreeCommandLine cli) {
color = cli.hasOption("color");
Colors.enabled = color;
if (cli.isNext("generate") || cli.isNext("export") || cli.isNext("ecdh") || cli.isNext("ecdsa") || cli.isNext("test")) {
if (!cli.hasArg(-1)) {
System.err.println("Missing library name argument.");
return false;
}
String next = cli.getNextName();
boolean hasBits = cli.hasOption(next + ".bits");
boolean hasNamedCurve = cli.hasOption(next + ".named-curve");
boolean hasCurveName = cli.hasOption(next + ".curve-name");
if (hasBits ^ hasNamedCurve ? hasCurveName : hasBits) {
System.err.println("You can only specify bitsize or a named curve/curve name, nor both.");
return false;
}
}
if (!cli.isNext("list-data") && !cli.isNext("list-suites")) {
String libraryName = cli.getArg(-1);
if (libraryName != null) {
List<ProviderECLibrary> matchedLibs = new LinkedList<>();
for (ProviderECLibrary lib : libs) {
if (lib.isInitialized() && lib.name().toLowerCase().contains(libraryName.toLowerCase())) {
matchedLibs.add(lib);
}
}
if (matchedLibs.size() == 0) {
System.err.println("No library " + libraryName + " found.");
return false;
} else if (matchedLibs.size() > 1) {
System.err.println("Multiple matching libraries found: " + String.join(",", matchedLibs.stream().map(ECLibrary::name).collect(Collectors.toList())));
return false;
} else {
selected = matchedLibs.get(0);
}
}
}
if (cli.hasOption("test.format")) {
String fmt = cli.getOptionValue("test.format");
String formats[] = new String[]{"text", "xml", "yaml", "yml"};
if (!Arrays.asList(formats).contains(fmt.toLowerCase())) {
System.err.println("Invalid format specified.");
return false;
}
}
return true;
}
}
}
|