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
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
|
/*
* Copyright (c) 2016-2017 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.reader;
import cz.crcs.ectester.applet.ECTesterApplet;
import cz.crcs.ectester.applet.EC_Consts;
import cz.crcs.ectester.data.EC_Category;
import cz.crcs.ectester.data.EC_Store;
import cz.crcs.ectester.reader.ec.*;
import javacard.security.KeyPair;
import org.apache.commons.cli.*;
import javax.smartcardio.CardException;
import java.io.*;
import java.nio.file.Files;
import java.util.*;
/**
* Reader part of ECTester, a tool for testing Elliptic curve support on javacards.
*
* @author Petr Svenda petr@svenda.com
* @author Jan Jancar johny@neuromancer.sk
*/
public class ECTester {
private CardMngr cardManager;
private DirtyLogger systemOutLogger;
private EC_Store dataStore;
//Options
private int optBits;
private boolean optAll;
private boolean optPrimeField = false;
private boolean optBinaryField = false;
private String optNamedCurve = null;
private String optCurveFile = null;
private boolean optCustomCurve = false;
private boolean optAnyPublic = false;
private String optNamedPublic = null;
private String optPublic = null;
private boolean optAnyPrivate = false;
private String optNamedPrivate = null;
private String optPrivate = null;
private boolean optAnyKey = false;
private String optNamedKey = null;
private String optKey = null;
private boolean optAnyKeypart = false;
private String optLog = null;
private boolean optVerbose = false;
private String optInput = null;
private String optOutput = null;
private boolean optFresh = false;
private boolean optSimulate = false;
//Action-related options
private String optListNamed;
private String optTestSuite;
private int optGenerateAmount;
private int optECDHCount;
private byte optECDHKA;
private int optECDSACount;
private Options opts = new Options();
private static final String CLI_HEADER = "\nECTester, a javacard Elliptic Curve Cryptograhy support tester/utility.\n\n";
private static final String CLI_FOOTER = "\nMIT Licensed\nCopyright (c) 2016-2017 Petr Svenda <petr@svenda.com>";
private static final byte[] SELECT_ECTESTERAPPLET = {(byte) 0x00, (byte) 0xa4, (byte) 0x04, (byte) 0x00, (byte) 0x0a,
(byte) 0x45, (byte) 0x43, (byte) 0x54, (byte) 0x65, (byte) 0x73, (byte) 0x74, (byte) 0x65, (byte) 0x72, (byte) 0x30, (byte) 0x31};
private static final byte[] AID = {(byte) 0x45, (byte) 0x43, (byte) 0x54, (byte) 0x65, (byte) 0x73, (byte) 0x74, (byte) 0x65, (byte) 0x72, (byte) 0x30, (byte) 0x31};
private static final byte[] INSTALL_DATA = new byte[10];
private void run(String[] args) {
try {
CommandLine cli = parseArgs(args);
//if help, print and quit
if (cli.hasOption("help")) {
help();
return;
}
//if not, read other options first, into attributes, then do action
if (!readOptions(cli)) {
return;
}
dataStore = new EC_Store();
//if list, print and quit
if (cli.hasOption("list-named")) {
list();
return;
}
//init CardManager
cardManager = new CardMngr(optVerbose, optSimulate);
//connect or simulate connection
if (optSimulate) {
if (!cardManager.prepareLocalSimulatorApplet(AID, INSTALL_DATA, ECTesterApplet.class)) {
System.err.println("Failed to establish a simulator.");
System.exit(1);
}
} else {
if (!cardManager.connectToCardSelect()) {
System.err.println("Failed to connect to card.");
System.exit(1);
}
cardManager.send(SELECT_ECTESTERAPPLET);
}
systemOutLogger = new DirtyLogger(optLog, true);
//do action
if (cli.hasOption("export")) {
export();
} else if (cli.hasOption("generate")) {
generate();
} else if (cli.hasOption("test")) {
test();
} else if (cli.hasOption("ecdh") || cli.hasOption("ecdhc")) {
ecdh();
} else if (cli.hasOption("ecdsa")) {
ecdsa();
}
//disconnect
cardManager.disconnectFromCard();
systemOutLogger.close();
} catch (MissingOptionException moex) {
System.err.println("Missing required options, one of:");
for (Object opt : moex.getMissingOptions().toArray()) {
if (opt instanceof OptionGroup) {
for (Option o : ((OptionGroup) opt).getOptions()) {
System.err.print("-" + o.getOpt());
if (o.hasLongOpt()) {
System.err.print("\t/ --" + o.getLongOpt() + " ");
}
if (o.hasArg()) {
if (o.hasOptionalArg()) {
System.err.print("[" + o.getArgName() + "] ");
} else {
System.err.print("<" + o.getArgName() + "> ");
}
}
if (o.getDescription() != null) {
System.err.print("\t\t\t" + o.getDescription());
}
System.err.println();
}
} else if (opt instanceof String) {
System.err.println(opt);
}
}
} catch (MissingArgumentException maex) {
System.err.println("Option, " + maex.getOption().getOpt() + " requires an argument: " + maex.getOption().getArgName());
} catch (NumberFormatException nfex) {
System.err.println("Not a number. " + nfex.getMessage());
} catch (FileNotFoundException fnfe) {
System.err.println("File " + fnfe.getMessage() + " not found.");
} catch (ParseException | IOException | CardException ex) {
System.err.println(ex.getMessage());
}
}
/**
* Parses command-line options.
*
* @param args cli arguments
* @return parsed CommandLine object
* @throws ParseException if there are any problems encountered while parsing the command line tokens
*/
private CommandLine parseArgs(String[] args) throws ParseException {
/*
* Actions:
* -h / --help
* -e / --export
* -g / --generate [amount]
* -t / --test [test_suite]
* -dh / --ecdh [count]
* -dhc / --ecdhc [count]
* -dsa / --ecdsa [count]
* -ln / --list-named
*
* Options:
* -b / --bit-size <b> // -a / --all
*
* -fp / --prime-field
* -f2m / --binary-field
*
* -u / --custom
* -nc / --named-curve <cat/id>
* -c / --curve <curve_file> field,a,b,gx,gy,r,k
*
* -pub / --public <pubkey_file> wx,wy
* -npub / --named-public <cat/id>
*
* -priv / --private <privkey_file> s
* -npriv / --named-private <cat/id>
*
* -k / --key <key_file> wx,wy,s
* -nk / --named-key <cat/id>
*
* -v / --verbose
*
* -i / --input <input_file>
* -o / --output <output_file>
* -l / --log [log_file]
*
* -f / --fresh
* -s / --simulate
*/
OptionGroup actions = new OptionGroup();
actions.setRequired(true);
actions.addOption(Option.builder("h").longOpt("help").desc("Print help.").build());
actions.addOption(Option.builder("ln").longOpt("list-named").desc("Print the list of supported named curves and keys.").hasArg().argName("what").optionalArg(true).build());
actions.addOption(Option.builder("e").longOpt("export").desc("Export the defaut curve parameters of the card(if any).").build());
actions.addOption(Option.builder("g").longOpt("generate").desc("Generate [amount] of EC keys.").hasArg().argName("amount").optionalArg(true).build());
actions.addOption(Option.builder("t").longOpt("test").desc("Test ECC support. [test_suite]:\n- default:\n- invalid:\n- wrong:\n- nonprime:\n- smallpub:\n- test-vectors:").hasArg().argName("test_suite").optionalArg(true).build());
actions.addOption(Option.builder("dh").longOpt("ecdh").desc("Do ECDH, [count] times.").hasArg().argName("count").optionalArg(true).build());
actions.addOption(Option.builder("dhc").longOpt("ecdhc").desc("Do ECDHC, [count] times.").hasArg().argName("count").optionalArg(true).build());
actions.addOption(Option.builder("dsa").longOpt("ecdsa").desc("Sign data with ECDSA, [count] times.").hasArg().argName("count").optionalArg(true).build());
opts.addOptionGroup(actions);
OptionGroup size = new OptionGroup();
size.addOption(Option.builder("b").longOpt("bit-size").desc("Set curve size.").hasArg().argName("bits").build());
size.addOption(Option.builder("a").longOpt("all").desc("Test all curve sizes.").build());
opts.addOptionGroup(size);
opts.addOption(Option.builder("fp").longOpt("prime-field").desc("Use a prime field.").build());
opts.addOption(Option.builder("f2m").longOpt("binary-field").desc("Use a binary field.").build());
OptionGroup curve = new OptionGroup();
curve.addOption(Option.builder("nc").longOpt("named-curve").desc("Use a named curve, from CurveDB: <cat/id>").hasArg().argName("cat/id").build());
curve.addOption(Option.builder("c").longOpt("curve").desc("Use curve from file <curve_file> (field,a,b,gx,gy,r,k).").hasArg().argName("curve_file").build());
curve.addOption(Option.builder("u").longOpt("custom").desc("Use a custom curve (applet-side embedded, SECG curves).").build());
opts.addOptionGroup(curve);
OptionGroup pub = new OptionGroup();
pub.addOption(Option.builder("npub").longOpt("named-public").desc("Use public key from KeyDB: <cat/id>").hasArg().argName("cat/id").build());
pub.addOption(Option.builder("pub").longOpt("public").desc("Use public key from file <pubkey_file> (wx,wy).").hasArg().argName("pubkey_file").build());
opts.addOptionGroup(pub);
OptionGroup priv = new OptionGroup();
priv.addOption(Option.builder("npriv").longOpt("named-private").desc("Use private key from KeyDB: <cat/id>").hasArg().argName("cat/id").build());
priv.addOption(Option.builder("priv").longOpt("private").desc("Use private key from file <privkey_file> (s).").hasArg().argName("privkey_file").build());
opts.addOptionGroup(priv);
OptionGroup key = new OptionGroup();
key.addOption(Option.builder("nk").longOpt("named-key").desc("Use keyPair from KeyDB: <cat/id>").hasArg().argName("cat/id").build());
key.addOption(Option.builder("k").longOpt("key").desc("Use keyPair from file <key_file> (wx,wy,s).").hasArg().argName("key_file").build());
opts.addOptionGroup(key);
opts.addOption(Option.builder("i").longOpt("input").desc("Input from file <input_file>, for ECDSA signing.").hasArg().argName("input_file").build());
opts.addOption(Option.builder("o").longOpt("output").desc("Output into file <output_file>.").hasArg().argName("output_file").build());
opts.addOption(Option.builder("l").longOpt("log").desc("Log output into file [log_file].").hasArg().argName("log_file").optionalArg(true).build());
opts.addOption(Option.builder("v").longOpt("verbose").desc("Turn on verbose logging.").build());
opts.addOption(Option.builder("f").longOpt("fresh").desc("Generate fresh keys (set domain parameters before every generation).").build());
opts.addOption(Option.builder("s").longOpt("simulate").desc("Simulate a card with jcardsim instead of using a terminal.").build());
CommandLineParser parser = new DefaultParser();
return parser.parse(opts, args);
}
/**
* Reads and validates options, also sets defaults.
*
* @param cli cli object, with parsed args
* @return whether the options are valid.
*/
private boolean readOptions(CommandLine cli) {
optBits = Integer.parseInt(cli.getOptionValue("bit-size", "0"));
optAll = cli.hasOption("all");
optPrimeField = cli.hasOption("fp");
optBinaryField = cli.hasOption("f2m");
optNamedCurve = cli.getOptionValue("named-curve");
optCustomCurve = cli.hasOption("custom");
optCurveFile = cli.getOptionValue("curve");
optNamedPublic = cli.getOptionValue("named-public");
optPublic = cli.getOptionValue("public");
optAnyPublic = (optPublic != null) || (optNamedPublic != null);
optNamedPrivate = cli.getOptionValue("named-private");
optPrivate = cli.getOptionValue("private");
optAnyPrivate = (optPrivate != null) || (optNamedPrivate != null);
optNamedKey = cli.getOptionValue("named-key");
optKey = cli.getOptionValue("key");
optAnyKey = (optKey != null) || (optNamedKey != null);
optAnyKeypart = optAnyKey || optAnyPublic || optAnyPrivate;
if (cli.hasOption("log")) {
optLog = cli.getOptionValue("log", String.format("ECTESTER_log_%d.log", System.currentTimeMillis() / 1000));
}
optVerbose = cli.hasOption("verbose");
optInput = cli.getOptionValue("input");
optOutput = cli.getOptionValue("output");
optFresh = cli.hasOption("fresh");
optSimulate = cli.hasOption("simulate");
if (cli.hasOption("list-named")) {
optListNamed = cli.getOptionValue("list-named");
return true;
}
if ((optKey != null || optNamedKey != null) && (optPublic != null || optPrivate != null || optNamedPublic != null || optNamedPrivate != null)) {
System.err.print("Can only specify the whole key with --key/--named-key or pubkey and privkey with --public/--named-public and --private/--named-private.");
return false;
}
if (optBits < 0) {
System.err.println("Bit-size must not be negative.");
return false;
}
if (optBits == 0 && !optAll) {
System.err.println("You must specify either bit-size with -b or all bit-sizes with -a.");
return false;
}
if (optKey != null && optNamedKey != null || optPublic != null && optNamedPublic != null || optPrivate != null && optNamedPrivate != null) {
System.err.println("You cannot specify both a named key and a key file.");
return false;
}
if (cli.hasOption("export")) {
if (optPrimeField == optBinaryField) {
System.err.print("Need to specify field with -fp or -f2m. (not both)");
return false;
}
if (optAnyKeypart) {
System.err.println("Keys should not be specified when exporting curve params.");
return false;
}
if (optNamedCurve != null || optCustomCurve || optCurveFile != null) {
System.err.println("Specifying a curve for curve export makes no sense.");
return false;
}
if (optOutput == null) {
System.err.println("You have to specify an output file for curve parameter export.");
return false;
}
if (optAll) {
System.err.println("You have to specify curve bit-size with -b");
return false;
}
} else if (cli.hasOption("generate")) {
if (optPrimeField == optBinaryField) {
System.err.print("Need to specify field with -fp or -f2m. (not both)");
return false;
}
if (optAnyKeypart) {
System.err.println("Keys should not be specified when generating keys.");
return false;
}
if (optOutput == null) {
System.err.println("You have to specify an output file for the key generation process.");
return false;
}
if (optAll) {
System.err.println("You have to specify curve bit-size with -b");
return false;
}
optGenerateAmount = Integer.parseInt(cli.getOptionValue("generate", "0"));
if (optGenerateAmount < 0) {
System.err.println("Amount of keys generated cant be negative.");
return false;
}
} else if (cli.hasOption("test")) {
if (!optBinaryField && !optPrimeField) {
optBinaryField = true;
optPrimeField = true;
}
optTestSuite = cli.getOptionValue("test", "default").toLowerCase();
String[] tests = new String[]{"default", "nonprime", "invalid", "test-vectors", "wrong"};
List<String> testsList = Arrays.asList(tests);
if (!testsList.contains(optTestSuite)) {
System.err.println("Unknown test case. Should be one of: " + Arrays.toString(tests));
return false;
}
} else if (cli.hasOption("ecdh") || cli.hasOption("ecdhc")) {
if (optPrimeField == optBinaryField) {
System.err.print("Need to specify field with -fp or -f2m. (not both)");
return false;
}
if (optAll) {
System.err.println("You have to specify curve bit-size with -b");
return false;
}
if (cli.hasOption("ecdh")) {
optECDHCount = Integer.parseInt(cli.getOptionValue("ecdh", "1"));
optECDHKA = EC_Consts.KA_ECDH;
} else if (cli.hasOption("ecdhc")) {
optECDHCount = Integer.parseInt(cli.getOptionValue("ecdhc", "1"));
optECDHKA = EC_Consts.KA_ECDHC;
}
if (optECDHCount <= 0) {
System.err.println("ECDH count cannot be <= 0.");
return false;
}
} else if (cli.hasOption("ecdsa")) {
if (optPrimeField == optBinaryField) {
System.err.print("Need to specify field with -fp or -f2m. (but not both)");
return false;
}
if (optAll) {
System.err.println("You have to specify curve bit-size with -b");
return false;
}
if ((optAnyPublic) != (optAnyPrivate) && !optAnyKey) {
System.err.println("You cannot only specify a part of a keypair.");
return false;
}
optECDSACount = Integer.parseInt(cli.getOptionValue("ecdsa", "1"));
if (optECDSACount <= 0) {
System.err.println("ECDSA count cannot be <= 0.");
return false;
}
}
return true;
}
/**
* List categories and named curves.
*/
private void list() {
Map<String, EC_Category> categories = dataStore.getCategories();
if (optListNamed == null) {
// print all categories, briefly
for (EC_Category cat : categories.values()) {
System.out.println("\t- " + cat.getName() + ": " + (cat.getDesc() == null ? "" : cat.getDesc()));
Map<String, EC_Curve> curves = cat.getObjects(EC_Curve.class);
int size = curves.size();
if (size > 0) {
System.out.print("\t\tCurves: ");
for (Map.Entry<String, EC_Curve> curve : curves.entrySet()) {
System.out.print(curve.getKey());
size--;
if (size > 0)
System.out.print(", ");
}
System.out.println();
}
Map<String, EC_Key> keys = cat.getObjects(EC_Key.class);
size = keys.size();
if (size > 0) {
System.out.print("\t\tKeys: ");
for (Map.Entry<String, EC_Key> key : keys.entrySet()) {
System.out.print(key.getKey());
size--;
if (size > 0)
System.out.print(", ");
}
System.out.println();
}
Map<String, EC_Keypair> keypairs = cat.getObjects(EC_Keypair.class);
size = keypairs.size();
if (size > 0) {
System.out.print("\t\tKeypairs: ");
for (Map.Entry<String, EC_Keypair> key : keypairs.entrySet()) {
System.out.print(key.getKey());
size--;
if (size > 0)
System.out.print(", ");
}
System.out.println();
}
Map<String, EC_KAResult> results = cat.getObjects(EC_KAResult.class);
size = results.size();
if (size > 0) {
System.out.print("\t\tResults: ");
for (Map.Entry<String, EC_KAResult> result : results.entrySet()) {
System.out.print(result.getKey());
size--;
if (size > 0)
System.out.print(", ");
}
System.out.println();
}
System.out.println();
}
} else if (categories.containsKey(optListNamed)) {
// print given category
//TODO
} else {
// print given object
EC_Data object = dataStore.getObject(EC_Data.class, optListNamed);
if (object != null) {
System.out.println(object);
}
}
}
/**
* Prints help.
*/
private void help() {
HelpFormatter help = new HelpFormatter();
help.setOptionComparator(null);
help.printHelp("ECTester.jar", CLI_HEADER, opts, CLI_FOOTER, true);
}
/**
* Exports default card/simulation EC domain parameters to output file.
*
* @throws CardException if APDU transmission fails
* @throws IOException if an IO error occurs when writing to key file.
*/
private void export() throws CardException, IOException {
byte keyClass = optPrimeField ? KeyPair.ALG_EC_FP : KeyPair.ALG_EC_F2M;
List<Response> sent = new LinkedList<>();
sent.add(new Command.Allocate(cardManager, ECTesterApplet.KEYPAIR_LOCAL, (short) optBits, keyClass).send());
sent.add(new Command.Clear(cardManager, ECTesterApplet.KEYPAIR_LOCAL).send());
sent.add(new Command.Generate(cardManager, ECTesterApplet.KEYPAIR_LOCAL).send());
// Cofactor generally isn't set on the default curve parameters on cards,
// since its not necessary for ECDH, only ECDHC which not many cards implement
// TODO: check if its assumend to be == 1?
short domain_all = optPrimeField ? EC_Consts.PARAMETERS_DOMAIN_FP : EC_Consts.PARAMETERS_DOMAIN_F2M;
short domain = (short) (domain_all ^ EC_Consts.PARAMETER_K);
Response.Export export = new Command.Export(cardManager, ECTesterApplet.KEYPAIR_LOCAL, EC_Consts.KEY_PUBLIC, domain_all).send();
if (!export.successful()) {
export = new Command.Export(cardManager, ECTesterApplet.KEYPAIR_LOCAL, EC_Consts.KEY_PUBLIC, domain).send();
}
sent.add(export);
systemOutLogger.println(Response.toString(sent));
EC_Params exported = new EC_Params(domain, export.getParams());
FileOutputStream out = new FileOutputStream(optOutput);
exported.writeCSV(out);
out.close();
}
/**
* Generates EC keyPairs and outputs them to output file.
*
* @throws CardException if APDU transmission fails
* @throws IOException if an IO error occurs when writing to key file.
*/
private void generate() throws CardException, IOException {
byte keyClass = optPrimeField ? KeyPair.ALG_EC_FP : KeyPair.ALG_EC_F2M;
new Command.Allocate(cardManager, ECTesterApplet.KEYPAIR_LOCAL, (short) optBits, keyClass).send();
List<Command> curve = prepareCurve(ECTesterApplet.KEYPAIR_LOCAL, (short) optBits, keyClass);
FileWriter keysFile = new FileWriter(optOutput);
keysFile.write("index;time;pubW;privS\n");
int generated = 0;
int retry = 0;
while (generated < optGenerateAmount || optGenerateAmount == 0) {
if (optFresh || generated == 0) {
Command.sendAll(curve);
}
Command.Generate generate = new Command.Generate(cardManager, ECTesterApplet.KEYPAIR_LOCAL);
Response.Generate response = generate.send();
long elapsed = response.getDuration();
Response.Export export = new Command.Export(cardManager, ECTesterApplet.KEYPAIR_LOCAL, EC_Consts.KEY_BOTH, EC_Consts.PARAMETERS_KEYPAIR).send();
if (!response.successful() || !export.successful()) {
if (retry < 10) {
retry++;
continue;
} else {
System.err.println("Keys could not be generated.");
break;
}
}
systemOutLogger.println(response.toString());
String pub = Util.bytesToHex(export.getParameter(ECTesterApplet.KEYPAIR_LOCAL, EC_Consts.PARAMETER_W), false);
String priv = Util.bytesToHex(export.getParameter(ECTesterApplet.KEYPAIR_LOCAL, EC_Consts.PARAMETER_S), false);
String line = String.format("%d;%d;%s;%s\n", generated, elapsed / 1000000, pub, priv);
keysFile.write(line);
keysFile.flush();
generated++;
}
keysFile.close();
}
/**
* Tests Elliptic curve support for a given curve/curves.
*
* @throws CardException if APDU transmission fails
* @throws IOException if an IO error occurs when writing to key file.
*/
private void test() throws IOException, CardException {
List<Command> commands = new LinkedList<>();
if (optTestSuite.equals("default")) {
commands.add(new Command.Support(cardManager));
if (optNamedCurve != null) {
if (optPrimeField) {
commands.addAll(testCurves(optNamedCurve, KeyPair.ALG_EC_FP));
}
if (optBinaryField) {
commands.addAll(testCurves(optNamedCurve, KeyPair.ALG_EC_F2M));
}
} else {
if (optAll) {
if (optPrimeField) {
//iterate over prime curve sizes used: EC_Consts.FP_SIZES
for (short keyLength : EC_Consts.FP_SIZES) {
commands.add(new Command.Allocate(cardManager, ECTesterApplet.KEYPAIR_BOTH, keyLength, KeyPair.ALG_EC_FP));
commands.addAll(prepareCurve(ECTesterApplet.KEYPAIR_BOTH, keyLength, KeyPair.ALG_EC_FP));
commands.addAll(testCurve());
commands.add(new Command.Cleanup(cardManager));
}
}
if (optBinaryField) {
//iterate over binary curve sizes used: EC_Consts.F2M_SIZES
for (short keyLength : EC_Consts.F2M_SIZES) {
commands.add(new Command.Allocate(cardManager, ECTesterApplet.KEYPAIR_BOTH, keyLength, KeyPair.ALG_EC_F2M));
commands.addAll(prepareCurve(ECTesterApplet.KEYPAIR_BOTH, keyLength, KeyPair.ALG_EC_F2M));
commands.addAll(testCurve());
commands.add(new Command.Cleanup(cardManager));
}
}
} else {
if (optPrimeField) {
commands.add(new Command.Allocate(cardManager, ECTesterApplet.KEYPAIR_BOTH, (short) optBits, KeyPair.ALG_EC_FP));
commands.addAll(prepareCurve(ECTesterApplet.KEYPAIR_BOTH, (short) optBits, KeyPair.ALG_EC_FP));
commands.addAll(testCurve());
commands.add(new Command.Cleanup(cardManager));
}
if (optBinaryField) {
commands.add(new Command.Allocate(cardManager, ECTesterApplet.KEYPAIR_BOTH, (short) optBits, KeyPair.ALG_EC_F2M));
commands.addAll(prepareCurve(ECTesterApplet.KEYPAIR_BOTH, (short) optBits, KeyPair.ALG_EC_F2M));
commands.addAll(testCurve());
commands.add(new Command.Cleanup(cardManager));
}
}
}
} else if (optTestSuite.equals("test-vectors")) {
/* Set original curves (secg/nist/brainpool). Set keypairs from test vectors.
* Do ECDH both ways, export and verify that the result is correct.
*
*/
Map<String, EC_KAResult> results = dataStore.getObjects(EC_KAResult.class, "test");
for (EC_KAResult result : results.values()) {
EC_Curve curve = dataStore.getObject(EC_Curve.class, result.getCurve());
if (optNamedCurve != null && !(result.getCurve().startsWith(optNamedCurve) || result.getCurve().equals(optNamedCurve))) {
continue;
}
if (curve.getBits() != optBits && !optAll) {
continue;
}
EC_Params onekey = dataStore.getObject(EC_Keypair.class, result.getOneKey());
if (onekey == null) {
onekey = dataStore.getObject(EC_Key.Private.class, result.getOneKey());
}
EC_Params otherkey = dataStore.getObject(EC_Keypair.class, result.getOtherKey());
if (otherkey == null) {
otherkey = dataStore.getObject(EC_Key.Public.class, result.getOtherKey());
}
if (onekey == null || otherkey == null) {
throw new IOException("Test vector keys not located");
}
commands.add(new Command.Allocate(cardManager, ECTesterApplet.KEYPAIR_BOTH, curve.getBits(), curve.getField()));
commands.add(new Command.Set(cardManager, ECTesterApplet.KEYPAIR_BOTH, EC_Consts.CURVE_external, curve.getParams(), curve.flatten()));
commands.add(new Command.Generate(cardManager, ECTesterApplet.KEYPAIR_BOTH));
commands.add(new Command.Set(cardManager, ECTesterApplet.KEYPAIR_LOCAL, EC_Consts.CURVE_external, EC_Consts.PARAMETER_S, onekey.flatten(EC_Consts.PARAMETER_S)));
commands.add(new Command.Set(cardManager, ECTesterApplet.KEYPAIR_REMOTE, EC_Consts.CURVE_external, EC_Consts.PARAMETER_W, otherkey.flatten(EC_Consts.PARAMETER_W)));
commands.add(new Command.ECDH(cardManager, ECTesterApplet.KEYPAIR_REMOTE, ECTesterApplet.KEYPAIR_LOCAL, ECTesterApplet.EXPORT_TRUE, EC_Consts.CORRUPTION_NONE, result.getKA()));
//TODO add compare with result.getParam(0);
commands.add(new Command.Cleanup(cardManager));
}
} else {
// These tests are dangerous, prompt before them.
System.out.println("The test you selected (" + optTestSuite + ") is potentially dangerous.");
System.out.println("Some of these tests have caused temporary DoS of some cards.");
System.out.print("Do you want to proceed? (y/n):");
Scanner in = new Scanner(System.in);
String confirmation = in.nextLine();
if (!Arrays.asList("yes", "y", "Y").contains(confirmation)) {
return;
}
if (optTestSuite.equals("wrong")) {
/* Just do the default tests on the wrong curves.
* These should generally fail, the curves aren't safe.
*/
if (optPrimeField) {
commands.addAll(testCurves(optTestSuite, KeyPair.ALG_EC_FP));
}
if (optBinaryField) {
commands.addAll(testCurves(optTestSuite, KeyPair.ALG_EC_F2M));
}
} else if (optTestSuite.equals("nonprime")) {
/* Do the default tests with the public keys set to provided nonprime keys.
* These should fail, the curves aren't safe so that if the computation with
* a small order public key succeeds the private key modulo the public key order
* is revealed.
*/
Map<String, EC_Key> keys = dataStore.getObjects(EC_Key.class, "nonprime");
for (EC_Key key : keys.values()) {
EC_Curve curve = dataStore.getObject(EC_Curve.class, key.getCurve());
if ((curve.getBits() == optBits || optAll)) {
commands.add(new Command.Allocate(cardManager, ECTesterApplet.KEYPAIR_BOTH, curve.getBits(), curve.getField()));
commands.add(new Command.Generate(cardManager, ECTesterApplet.KEYPAIR_LOCAL));
commands.add(new Command.Set(cardManager, ECTesterApplet.KEYPAIR_BOTH, EC_Consts.CURVE_external, curve.getParams(), curve.flatten()));
commands.add(new Command.Set(cardManager, ECTesterApplet.KEYPAIR_REMOTE, EC_Consts.CURVE_external, key.getParams(), key.flatten()));
commands.add(new Command.ECDH(cardManager, ECTesterApplet.KEYPAIR_REMOTE, ECTesterApplet.KEYPAIR_LOCAL, ECTesterApplet.EXPORT_FALSE, EC_Consts.CORRUPTION_NONE, EC_Consts.KA_ECDH));
commands.add(new Command.Cleanup(cardManager));
}
}
} else if (optTestSuite.equals("invalid")) {
/* Set original curves (secg/nist/brainpool). Generate local.
* Try ECDH with invalid public keys of increasing (or decreasing) order.
*
*/
//TODO
System.err.println("Currently not yet implemented.");
}
}
List<Response> test = Command.sendAll(commands);
systemOutLogger.println(Response.toString(test, optTestSuite));
for (Response response : test) {
if (response instanceof Response.ECDH) {
Response.ECDH ecdh = (Response.ECDH) response;
if (ecdh.hasSecret()) {
System.out.println(Util.bytesToHex(ecdh.getSecret(), false));
}
}
}
}
/**
* Performs ECDH key exchange.
*
* @throws CardException if APDU transmission fails
* @throws IOException if an IO error occurs when writing to key file.
*/
private void ecdh() throws IOException, CardException {
byte keyClass = optPrimeField ? KeyPair.ALG_EC_FP : KeyPair.ALG_EC_F2M;
List<Response> prepare = new LinkedList<>();
prepare.add(new Command.Allocate(cardManager, ECTesterApplet.KEYPAIR_BOTH, (short) optBits, keyClass).send());
prepare.addAll(Command.sendAll(prepareCurve(ECTesterApplet.KEYPAIR_BOTH, (short) optBits, keyClass)));
systemOutLogger.println(Response.toString(prepare));
byte pubkey = (optAnyPublic || optAnyKey) ? ECTesterApplet.KEYPAIR_REMOTE : ECTesterApplet.KEYPAIR_LOCAL;
byte privkey = (optAnyPrivate || optAnyKey) ? ECTesterApplet.KEYPAIR_REMOTE : ECTesterApplet.KEYPAIR_LOCAL;
List<Command> generate = new LinkedList<>();
generate.add(new Command.Generate(cardManager, ECTesterApplet.KEYPAIR_BOTH));
if (optAnyPublic || optAnyPrivate || optAnyKey) {
generate.add(prepareKey(ECTesterApplet.KEYPAIR_REMOTE));
}
FileWriter out = null;
if (optOutput != null) {
out = new FileWriter(optOutput);
out.write("index;time;secret\n");
}
int retry = 0;
int done = 0;
while (done < optECDHCount) {
List<Response> ecdh = Command.sendAll(generate);
Response.ECDH perform = new Command.ECDH(cardManager, pubkey, privkey, ECTesterApplet.EXPORT_TRUE, EC_Consts.CORRUPTION_NONE, optECDHKA).send();
ecdh.add(perform);
systemOutLogger.println(Response.toString(ecdh));
if (!perform.successful() || !perform.hasSecret()) {
if (retry < 10) {
++retry;
continue;
} else {
System.err.println("Couldn't obtain ECDH secret from card response.");
break;
}
}
if (out != null) {
out.write(String.format("%d;%d;%s\n", done, perform.getDuration() / 1000000, Util.bytesToHex(perform.getSecret(), false)));
}
++done;
}
if (out != null)
out.close();
}
/**
* Performs ECDSA signature, on random or provided data.
*
* @throws CardException if APDU transmission fails
* @throws IOException if an IO error occurs when writing to key file.
*/
private void ecdsa() throws CardException, IOException {
//read file, if asked to sign
byte[] data = null;
if (optInput != null) {
File in = new File(optInput);
long len = in.length();
if (len == 0) {
throw new FileNotFoundException(optInput);
}
data = Files.readAllBytes(in.toPath());
}
Command generate;
if (optAnyKeypart) {
generate = prepareKey(ECTesterApplet.KEYPAIR_LOCAL);
} else {
generate = new Command.Generate(cardManager, ECTesterApplet.KEYPAIR_LOCAL);
}
byte keyClass = optPrimeField ? KeyPair.ALG_EC_FP : KeyPair.ALG_EC_F2M;
List<Response> prepare = new LinkedList<>();
prepare.add(new Command.Allocate(cardManager, ECTesterApplet.KEYPAIR_LOCAL, (short) optBits, keyClass).send());
prepare.addAll(Command.sendAll(prepareCurve(ECTesterApplet.KEYPAIR_LOCAL, (short) optBits, keyClass)));
systemOutLogger.println(Response.toString(prepare));
FileWriter out = null;
if (optOutput != null) {
out = new FileWriter(optOutput);
out.write("index;time;signature\n");
}
int retry = 0;
int done = 0;
while (done < optECDSACount) {
List<Response> ecdsa = new LinkedList<>();
ecdsa.add(generate.send());
Response.ECDSA perform = new Command.ECDSA(cardManager, ECTesterApplet.KEYPAIR_LOCAL, ECTesterApplet.EXPORT_TRUE, data).send();
ecdsa.add(perform);
systemOutLogger.println(Response.toString(ecdsa));
if (!perform.successful() || !perform.hasSignature()) {
if (retry < 10) {
++retry;
continue;
} else {
System.err.println("Couldn't obtain ECDSA signature from card response.");
break;
}
}
if (out != null) {
out.write(String.format("%d;%d;%s\n", done, perform.getDuration() / 1000000, Util.bytesToHex(perform.getSignature(), false)));
}
++done;
}
if (out != null)
out.close();
}
/**
* @param keyPair which keyPair/s (local/remote) to set curve domain parameters on
* @param keyLength key length to choose
* @param keyClass key class to choose
* @return a list of Commands to send in order to prepare the curve on the keypairs.
* @throws IOException if curve file cannot be found/opened
*/
private List<Command> prepareCurve(byte keyPair, short keyLength, byte keyClass) throws IOException {
List<Command> commands = new ArrayList<>();
if (optCustomCurve) {
// Set custom curve (one of the SECG curves embedded applet-side)
short domainParams = keyClass == KeyPair.ALG_EC_FP ? EC_Consts.PARAMETERS_DOMAIN_FP : EC_Consts.PARAMETERS_DOMAIN_F2M;
commands.add(new Command.Set(cardManager, keyPair, EC_Consts.getCurve(keyLength, keyClass), domainParams, null));
} else if (optNamedCurve != null) {
// Set a named curve.
// parse optNamedCurve -> cat / id | cat | id
EC_Curve curve = dataStore.getObject(EC_Curve.class, optNamedCurve);
if (curve == null) {
throw new IOException("Curve could no be found.");
}
if (curve.getBits() != keyLength) {
throw new IOException("Curve bits mismatch: " + curve.getBits() + " vs " + keyLength + " entered.");
}
byte[] external = curve.flatten();
if (external == null) {
throw new IOException("Couldn't read named curve data.");
}
commands.add(new Command.Set(cardManager, keyPair, EC_Consts.CURVE_external, curve.getParams(), external));
} else if (optCurveFile != null) {
// Set curve loaded from a file
EC_Curve curve = new EC_Curve(keyLength, keyClass);
FileInputStream in = new FileInputStream(optCurveFile);
curve.readCSV(in);
in.close();
byte[] external = curve.flatten();
if (external == null) {
throw new IOException("Couldn't read the curve file correctly.");
}
commands.add(new Command.Set(cardManager, keyPair, EC_Consts.CURVE_external, curve.getParams(), external));
} else {
// Set default curve
/* This command was generally causing problems for simulating on jcardsim.
* Since there, .clearKey() resets all the keys values, even the domain.
* This might break some other stuff.. But should not.
*/
//commands.add(new Command.Clear(cardManager, keyPair));
}
return commands;
}
/**
* @param keyPair which keyPair/s to set the key params on
* @return a CommandAPDU setting params loaded on the keyPair/s
* @throws IOException if any of the key files cannot be found/opened
*/
private Command prepareKey(byte keyPair) throws IOException {
short params = EC_Consts.PARAMETERS_NONE;
byte[] data = null;
if (optKey != null || optNamedKey != null) {
params |= EC_Consts.PARAMETERS_KEYPAIR;
EC_Params keypair;
if (optKey != null) {
keypair = new EC_Params(EC_Consts.PARAMETERS_KEYPAIR);
FileInputStream in = new FileInputStream(optKey);
keypair.readCSV(in);
in.close();
} else {
keypair = dataStore.getObject(EC_Keypair.class, optNamedKey);
}
data = keypair.flatten();
if (data == null) {
throw new IOException("Couldn't read the key file correctly.");
}
}
if (optPublic != null || optNamedPublic != null) {
params |= EC_Consts.PARAMETER_W;
EC_Params pub;
if (optPublic != null) {
pub = new EC_Params(EC_Consts.PARAMETER_W);
FileInputStream in = new FileInputStream(optPublic);
pub.readCSV(in);
in.close();
} else {
pub = dataStore.getObject(EC_Key.Public.class, optNamedPublic);
if (pub == null) {
pub = dataStore.getObject(EC_Keypair.class, optNamedPublic);
}
}
byte[] pubkey = pub.flatten(EC_Consts.PARAMETER_W);
if (pubkey == null) {
throw new IOException("Couldn't read the public key file correctly.");
}
data = pubkey;
}
if (optPrivate != null || optNamedPrivate != null) {
params |= EC_Consts.PARAMETER_S;
EC_Params priv;
if (optPrivate != null) {
priv = new EC_Params(EC_Consts.PARAMETER_S);
FileInputStream in = new FileInputStream(optPrivate);
priv.readCSV(in);
in.close();
} else {
priv = dataStore.getObject(EC_Key.Public.class, optNamedPrivate);
if (priv == null) {
priv = dataStore.getObject(EC_Keypair.class, optNamedPrivate);
}
}
byte[] privkey = priv.flatten(EC_Consts.PARAMETER_S);
if (privkey == null) {
throw new IOException("Couldn't read the private key file correctly.");
}
data = Util.concatenate(data, privkey);
}
return new Command.Set(cardManager, keyPair, EC_Consts.CURVE_external, params, data);
}
/**
*
* @return
* @throws IOException if an IO error occurs when writing to key file.
*/
private List<Command> testCurve() throws IOException {
List<Command> commands = new LinkedList<>();
commands.add(new Command.Generate(cardManager, ECTesterApplet.KEYPAIR_BOTH));
commands.add(new Command.ECDH(cardManager, ECTesterApplet.KEYPAIR_LOCAL, ECTesterApplet.KEYPAIR_REMOTE, ECTesterApplet.EXPORT_FALSE, EC_Consts.CORRUPTION_NONE, EC_Consts.KA_ECDH));
commands.add(new Command.ECDH(cardManager, ECTesterApplet.KEYPAIR_LOCAL, ECTesterApplet.KEYPAIR_REMOTE, ECTesterApplet.EXPORT_FALSE, EC_Consts.CORRUPTION_ONE, EC_Consts.KA_ECDH));
commands.add(new Command.ECDH(cardManager, ECTesterApplet.KEYPAIR_LOCAL, ECTesterApplet.KEYPAIR_REMOTE, ECTesterApplet.EXPORT_FALSE, EC_Consts.CORRUPTION_ZERO, EC_Consts.KA_ECDH));
commands.add(new Command.ECDH(cardManager, ECTesterApplet.KEYPAIR_LOCAL, ECTesterApplet.KEYPAIR_REMOTE, ECTesterApplet.EXPORT_FALSE, EC_Consts.CORRUPTION_MAX, EC_Consts.KA_ECDH));
commands.add(new Command.ECDH(cardManager, ECTesterApplet.KEYPAIR_LOCAL, ECTesterApplet.KEYPAIR_REMOTE, ECTesterApplet.EXPORT_FALSE, EC_Consts.CORRUPTION_FULLRANDOM, EC_Consts.KA_ECDH));
commands.add(new Command.ECDSA(cardManager, ECTesterApplet.KEYPAIR_LOCAL, ECTesterApplet.EXPORT_FALSE, null));
return commands;
}
/**
*
* @param category
* @param field
* @return
* @throws IOException if an IO error occurs when writing to key file.
*/
private List<Command> testCurves(String category, byte field) throws IOException {
List<Command> commands = new LinkedList<>();
Map<String, EC_Curve> curves = dataStore.getObjects(EC_Curve.class, category);
if (curves == null)
return commands;
for (Map.Entry<String, EC_Curve> entry : curves.entrySet()) {
EC_Curve curve = entry.getValue();
if (curve.getField() == field && (curve.getBits() == optBits || optAll)) {
commands.add(new Command.Allocate(cardManager, ECTesterApplet.KEYPAIR_BOTH, curve.getBits(), field));
commands.add(new Command.Set(cardManager, ECTesterApplet.KEYPAIR_BOTH, EC_Consts.CURVE_external, curve.getParams(), curve.flatten()));
commands.addAll(testCurve());
commands.add(new Command.Cleanup(cardManager));
}
}
return commands;
}
public static void main(String[] args) {
ECTester app = new ECTester();
app.run(args);
}
}
|