aboutsummaryrefslogtreecommitdiff
path: root/src/cz/crcs/ectester/reader/test
diff options
context:
space:
mode:
authorJ08nY2024-03-22 23:58:55 +0100
committerJ08nY2024-03-25 14:52:43 +0100
commit73af477a8774e1ede5dd8de6491eb353dc0b12bd (patch)
tree2d4e3b19bc5fb55308b886032312be76341736d4 /src/cz/crcs/ectester/reader/test
parent64b95fa059295e1dc23371c849f2302c1c18f5b4 (diff)
downloadECTester-73af477a8774e1ede5dd8de6491eb353dc0b12bd.tar.gz
ECTester-73af477a8774e1ede5dd8de6491eb353dc0b12bd.tar.zst
ECTester-73af477a8774e1ede5dd8de6491eb353dc0b12bd.zip
Basic Gradle setup.
Diffstat (limited to 'src/cz/crcs/ectester/reader/test')
-rw-r--r--src/cz/crcs/ectester/reader/test/CardCofactorSuite.java65
-rw-r--r--src/cz/crcs/ectester/reader/test/CardCompositeSuite.java122
-rw-r--r--src/cz/crcs/ectester/reader/test/CardCompressionSuite.java155
-rw-r--r--src/cz/crcs/ectester/reader/test/CardDefaultSuite.java141
-rw-r--r--src/cz/crcs/ectester/reader/test/CardDegenerateSuite.java69
-rw-r--r--src/cz/crcs/ectester/reader/test/CardEdgeCasesSuite.java336
-rw-r--r--src/cz/crcs/ectester/reader/test/CardInvalidSuite.java72
-rw-r--r--src/cz/crcs/ectester/reader/test/CardMiscSuite.java77
-rw-r--r--src/cz/crcs/ectester/reader/test/CardSignatureSuite.java68
-rw-r--r--src/cz/crcs/ectester/reader/test/CardTestSuite.java94
-rw-r--r--src/cz/crcs/ectester/reader/test/CardTestVectorSuite.java235
-rw-r--r--src/cz/crcs/ectester/reader/test/CardTwistSuite.java67
-rw-r--r--src/cz/crcs/ectester/reader/test/CardWrongSuite.java232
-rw-r--r--src/cz/crcs/ectester/reader/test/CommandTest.java85
-rw-r--r--src/cz/crcs/ectester/reader/test/CommandTestable.java44
-rw-r--r--src/cz/crcs/ectester/reader/test/PerformanceTest.java141
16 files changed, 0 insertions, 2003 deletions
diff --git a/src/cz/crcs/ectester/reader/test/CardCofactorSuite.java b/src/cz/crcs/ectester/reader/test/CardCofactorSuite.java
deleted file mode 100644
index d1eb2b1..0000000
--- a/src/cz/crcs/ectester/reader/test/CardCofactorSuite.java
+++ /dev/null
@@ -1,65 +0,0 @@
-package cz.crcs.ectester.reader.test;
-
-import cz.crcs.ectester.applet.ECTesterApplet;
-import cz.crcs.ectester.applet.EC_Consts;
-import cz.crcs.ectester.common.ec.EC_Curve;
-import cz.crcs.ectester.common.ec.EC_Key;
-import cz.crcs.ectester.common.output.TestWriter;
-import cz.crcs.ectester.common.test.CompoundTest;
-import cz.crcs.ectester.common.test.Result;
-import cz.crcs.ectester.common.test.Test;
-import cz.crcs.ectester.common.util.CardUtil;
-import cz.crcs.ectester.data.EC_Store;
-import cz.crcs.ectester.reader.CardMngr;
-import cz.crcs.ectester.reader.ECTesterReader;
-import cz.crcs.ectester.reader.command.Command;
-
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-
-import static cz.crcs.ectester.common.test.Result.ExpectedValue;
-
-/**
- * @author Jan Jancar johny@neuromancer.sk
- */
-public class CardCofactorSuite extends CardTestSuite {
- public CardCofactorSuite(TestWriter writer, ECTesterReader.Config cfg, CardMngr cardManager) {
- super(writer, cfg, cardManager, "cofactor", new String[]{"preset", "random"}, "The cofactor test suite tests whether the card correctly rejects points on the curve",
- "but not in the subgroup generated by the generator(so of small order, dividing the cofactor) during ECDH.");
- }
-
- @Override
- protected void runTests() throws Exception {
- Map<String, EC_Key.Public> pubkeys = EC_Store.getInstance().getObjects(EC_Key.Public.class, "cofactor");
- Map<EC_Curve, List<EC_Key.Public>> curveList = EC_Store.mapKeyToCurve(pubkeys.values());
- for (Map.Entry<EC_Curve, List<EC_Key.Public>> e : curveList.entrySet()) {
- EC_Curve curve = e.getKey();
- List<EC_Key.Public> keys = e.getValue();
-
- Test allocate = CommandTest.expect(new Command.Allocate(this.card, ECTesterApplet.KEYPAIR_BOTH, curve.getBits(), curve.getField()), ExpectedValue.SUCCESS);
- Test set = CommandTest.expect(new Command.Set(this.card, ECTesterApplet.KEYPAIR_BOTH, EC_Consts.CURVE_external, curve.getParams(), curve.flatten()), ExpectedValue.SUCCESS);
- Test generate = setupKeypairs(curve, ExpectedValue.SUCCESS, ECTesterApplet.KEYPAIR_LOCAL);
-
- Test prepare = CompoundTest.all(ExpectedValue.SUCCESS, "Prepare and generate keypair on " + curve.getId() + ".", allocate, set, generate);
-
- List<Test> ecdhTests = new LinkedList<>();
- for (EC_Key.Public pub : keys) {
- Test setPub = CommandTest.expect(new Command.Set(this.card, ECTesterApplet.KEYPAIR_REMOTE, EC_Consts.CURVE_external, pub.getParams(), pub.flatten()), Result.ExpectedValue.FAILURE);
- Test ecdh = CommandTest.expect(new Command.ECDH(this.card, ECTesterApplet.KEYPAIR_REMOTE, ECTesterApplet.KEYPAIR_LOCAL, ECTesterApplet.EXPORT_FALSE, EC_Consts.TRANSFORMATION_NONE, EC_Consts.KeyAgreement_ALG_EC_SVDP_DH), Result.ExpectedValue.FAILURE);
- Test objectEcdh = CompoundTest.any(Result.ExpectedValue.SUCCESS, CardUtil.getKATypeString(EC_Consts.KeyAgreement_ALG_EC_SVDP_DH) + " test with cofactor pubkey.", setPub, ecdh);
- Command ecdhCommand = new Command.ECDH_direct(this.card, ECTesterApplet.KEYPAIR_LOCAL, ECTesterApplet.EXPORT_FALSE, EC_Consts.TRANSFORMATION_NONE, EC_Consts.KeyAgreement_ALG_EC_SVDP_DH, pub.flatten());
- Test rawEcdh = CommandTest.expect(ecdhCommand, ExpectedValue.FAILURE, "Card correctly rejected point on non-generator subgroup.", "Card incorrectly accepted point on non-generator subgroup.");
- ecdhTests.add(CompoundTest.all(Result.ExpectedValue.SUCCESS, pub.getId() + " cofactor key test.", objectEcdh, rawEcdh));
- }
- Test ecdh = CompoundTest.all(ExpectedValue.SUCCESS, "Perform ECDH with public points on non-generator subgroup.", ecdhTests.toArray(new Test[0]));
-
- if (cfg.cleanup) {
- Test cleanup = CommandTest.expect(new Command.Cleanup(this.card), ExpectedValue.ANY);
- doTest(CompoundTest.greedyAllTry(ExpectedValue.SUCCESS, "Cofactor test of " + curve.getId() + ".", prepare, ecdh, cleanup));
- } else {
- doTest(CompoundTest.greedyAllTry(ExpectedValue.SUCCESS, "Cofactor test of " + curve.getId() + ".", prepare, ecdh));
- }
- }
- }
-}
diff --git a/src/cz/crcs/ectester/reader/test/CardCompositeSuite.java b/src/cz/crcs/ectester/reader/test/CardCompositeSuite.java
deleted file mode 100644
index babe732..0000000
--- a/src/cz/crcs/ectester/reader/test/CardCompositeSuite.java
+++ /dev/null
@@ -1,122 +0,0 @@
-package cz.crcs.ectester.reader.test;
-
-import cz.crcs.ectester.applet.ECTesterApplet;
-import cz.crcs.ectester.applet.EC_Consts;
-import cz.crcs.ectester.common.ec.EC_Curve;
-import cz.crcs.ectester.common.ec.EC_Key;
-import cz.crcs.ectester.common.output.TestWriter;
-import cz.crcs.ectester.common.test.CompoundTest;
-import cz.crcs.ectester.common.test.Test;
-import cz.crcs.ectester.common.util.CardUtil;
-import cz.crcs.ectester.data.EC_Store;
-import cz.crcs.ectester.reader.CardMngr;
-import cz.crcs.ectester.reader.ECTesterReader;
-import cz.crcs.ectester.reader.command.Command;
-
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-
-import static cz.crcs.ectester.common.test.Result.ExpectedValue;
-
-/**
- * @author Jan Jancar johny@neuromancer.sk
- */
-public class CardCompositeSuite extends CardTestSuite {
-
- public CardCompositeSuite(TestWriter writer, ECTesterReader.Config cfg, CardMngr cardManager) {
- super(writer, cfg, cardManager, "composite", new String[]{"preset", "random"}, "The composite suite runs ECDH over curves with composite order.",
- "Various types of compositeness is tested: smooth numbers, Carmichael pseudo-prime, prime square, product of two large primes.");
- }
-
- @Override
- protected void runTests() throws Exception {
- Map<String, EC_Key> keys = EC_Store.getInstance().getObjects(EC_Key.class, "composite");
- Map<EC_Curve, List<EC_Key>> mappedKeys = EC_Store.mapKeyToCurve(keys.values());
- for (Map.Entry<EC_Curve, List<EC_Key>> curveKeys : mappedKeys.entrySet()) {
- EC_Curve curve = curveKeys.getKey();
- List<Test> tests = new LinkedList<>();
- Test allocate = runTest(CommandTest.expect(new Command.Allocate(this.card, ECTesterApplet.KEYPAIR_LOCAL, curve.getBits(), curve.getField()), ExpectedValue.SUCCESS));
- if (!allocate.ok()) {
- doTest(CompoundTest.all(ExpectedValue.SUCCESS, "No support for " + curve.getBits() + "b " + CardUtil.getKeyTypeString(curve.getField()) + ".", allocate));
- continue;
- }
- tests.add(allocate);
- tests.add(CommandTest.expect(new Command.Set(this.card, ECTesterApplet.KEYPAIR_LOCAL, EC_Consts.CURVE_external, curve.getParams(), curve.flatten()), ExpectedValue.ANY));
-
- String name;
- if (cfg.testOptions.contains("preset")) {
- name = "preset semi-random private key";
- } else {
- name = "generated private key";
- }
- tests.add(setupKeypairs(curve, ExpectedValue.ANY, ECTesterApplet.KEYPAIR_LOCAL));
- for (EC_Key key : curveKeys.getValue()) {
- Command ecdhCommand = new Command.ECDH_direct(this.card, ECTesterApplet.KEYPAIR_LOCAL, ECTesterApplet.EXPORT_FALSE, EC_Consts.TRANSFORMATION_NONE, EC_Consts.KeyAgreement_ALG_EC_SVDP_DH, key.flatten());
- Test ecdh = CommandTest.expect(ecdhCommand, ExpectedValue.FAILURE, "Card correctly rejected to do ECDH over a composite order curve.", "Card incorrectly does ECDH over a composite order curve, leaks bits of private key.");
- tests.add(CompoundTest.greedyAllTry(ExpectedValue.SUCCESS, "Composite test of " + curve.getId() + ", with " + name + ", " + key.getDesc(), ecdh));
- }
- doTest(CompoundTest.all(ExpectedValue.SUCCESS, "Composite test of " + curve.getId() + ".", tests.toArray(new Test[0])));
- }
-
-
- Map<String, EC_Curve> results = EC_Store.getInstance().getObjects(EC_Curve.class, "composite");
- Map<String, List<EC_Curve>> groups = EC_Store.mapToPrefix(results.values());
- /* Test the whole curves with both keypairs generated on card(no small-order public points provided).
- */
- List<EC_Curve> wholeCurves = groups.entrySet().stream().filter((e) -> e.getKey().equals("whole")).findFirst().get().getValue();
- testGroup(wholeCurves, "Composite generator order", ExpectedValue.FAILURE, "Card rejected to do ECDH with composite order generator.", "Card did not reject to do ECDH with composite order generator.");
-
- /* Also test having a G of small order, so small R.
- */
- List<EC_Curve> smallRCurves = groups.entrySet().stream().filter((e) -> e.getKey().equals("small")).findFirst().get().getValue();
- testGroup(smallRCurves, "Small generator order", ExpectedValue.FAILURE, "Card correctly rejected to do ECDH over a small order generator.", "Card incorrectly does ECDH over a small order generator.");
-
- /* Test increasingly larger prime R, to determine where/if card behavior changes.
- */
- List<EC_Curve> varyingCurves = groups.entrySet().stream().filter((e) -> e.getKey().equals("varying")).findFirst().get().getValue();
- testGroup(varyingCurves, null, ExpectedValue.ANY, "", "");
-
- /* Also test having a G of large but composite order, R = p * q,
- */
- List<EC_Curve> pqCurves = groups.entrySet().stream().filter((e) -> e.getKey().equals("pq")).findFirst().get().getValue();
- testGroup(pqCurves, null, ExpectedValue.ANY, "", "");
-
- /* Also test having G or large order being a Carmichael pseudoprime, R = p * q * r,
- */
- List<EC_Curve> ppCurves = groups.entrySet().stream().filter((e) -> e.getKey().equals("pp")).findFirst().get().getValue();
- testGroup(ppCurves, "Generator order = Carmichael pseudo-prime", ExpectedValue.ANY, "", "");
-
- /* Also test rg0 curves.
- */
- List<EC_Curve> rg0Curves = groups.entrySet().stream().filter((e) -> e.getKey().equals("rg0")).findFirst().get().getValue();
- testGroup(rg0Curves, null, ExpectedValue.ANY, "", "");
- }
-
- private void testGroup(List<EC_Curve> curves, String testName, ExpectedValue dhValue, String ok, String nok) throws Exception {
- for (EC_Curve curve : curves) {
- Test allocate = CommandTest.expect(new Command.Allocate(this.card, ECTesterApplet.KEYPAIR_BOTH, curve.getBits(), curve.getField()), ExpectedValue.SUCCESS);
- Test set = CommandTest.expect(new Command.Set(this.card, ECTesterApplet.KEYPAIR_BOTH, EC_Consts.CURVE_external, curve.getParams(), curve.flatten()), ExpectedValue.ANY);
- Test generate = setupKeypairs(curve, ExpectedValue.ANY, ECTesterApplet.KEYPAIR_BOTH);
- Test ecdh = CommandTest.expect(new Command.ECDH(this.card, ECTesterApplet.KEYPAIR_REMOTE, ECTesterApplet.KEYPAIR_LOCAL, ECTesterApplet.EXPORT_FALSE, EC_Consts.TRANSFORMATION_NONE, EC_Consts.KeyAgreement_ALG_EC_SVDP_DH), dhValue, ok, nok);
- Test ecdsa = CommandTest.expect(new Command.ECDSA_sign(this.card, ECTesterApplet.KEYPAIR_LOCAL, EC_Consts.Signature_ALG_ECDSA_SHA, ECTesterApplet.EXPORT_FALSE, null), dhValue, ok, nok);
-
- String description;
- if (testName == null) {
- description = curve.getDesc() + " test of " + curve.getId() + ".";
- } else {
- description = testName + " test of " + curve.getId() + ".";
- }
-
- Test perform = CompoundTest.all(ExpectedValue.SUCCESS, "Perform ECDH and ECDSA.", ecdh, ecdsa);
-
- if (cfg.cleanup) {
- Test cleanup = CommandTest.expect(new Command.Cleanup(this.card), ExpectedValue.ANY);
- doTest(CompoundTest.greedyAllTry(ExpectedValue.SUCCESS, description, allocate, set, generate, perform, cleanup));
- } else {
- doTest(CompoundTest.greedyAllTry(ExpectedValue.SUCCESS, description, allocate, set, generate, perform));
- }
- }
-
- }
-}
diff --git a/src/cz/crcs/ectester/reader/test/CardCompressionSuite.java b/src/cz/crcs/ectester/reader/test/CardCompressionSuite.java
deleted file mode 100644
index 9eed814..0000000
--- a/src/cz/crcs/ectester/reader/test/CardCompressionSuite.java
+++ /dev/null
@@ -1,155 +0,0 @@
-package cz.crcs.ectester.reader.test;
-
-import cz.crcs.ectester.applet.ECTesterApplet;
-import cz.crcs.ectester.applet.EC_Consts;
-import cz.crcs.ectester.common.ec.EC_Curve;
-import cz.crcs.ectester.common.ec.EC_Key;
-import cz.crcs.ectester.common.output.TestWriter;
-import cz.crcs.ectester.common.test.CompoundTest;
-import cz.crcs.ectester.common.test.Result;
-import cz.crcs.ectester.common.test.Test;
-import cz.crcs.ectester.common.util.ByteUtil;
-import cz.crcs.ectester.common.util.CardUtil;
-import cz.crcs.ectester.common.util.ECUtil;
-import cz.crcs.ectester.data.EC_Store;
-import cz.crcs.ectester.reader.CardMngr;
-import cz.crcs.ectester.reader.ECTesterReader;
-import cz.crcs.ectester.reader.command.Command;
-import cz.crcs.ectester.reader.response.Response;
-import javacard.security.KeyPair;
-
-import java.security.spec.ECPoint;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-
-/**
- * @author Jan Jancar johny@neuromancer.sk
- */
-public class CardCompressionSuite extends CardTestSuite {
- public CardCompressionSuite(TestWriter writer, ECTesterReader.Config cfg, CardMngr cardManager) {
- super(writer, cfg, cardManager, "compression", null, "The compression test suite tests cards support for compressed points in ECDH (as per ANSI X9.62).",
- "It also tests for handling of bogus input in ECDH by using the point at infinity and a hybrid point with the y coordinate corrupted.",
- "It also tests handling of compressed point in ECDH, where the x coordinate is invalid and therefore",
- "a quadratic non-residue will be computed and (square root-ed) during decompression.");
- }
-
- @Override
- protected void runTests() throws Exception {
- //iterate over default curve sizes
- // for Fp
- // - allocate, set custom curve, generate keypairs, -> export generated.
- // - test ecdh with local and remote simply(no compression)
- // - test local privkey, remote pubkey (compressed)
- // - test local privkey, remote pubkey (hybrid)
- // - test local privkey, remote pubkey (hybrid with wrong y)
- // - test local privkey, remote pubkey (point at infinity)
- if (cfg.primeField) {
- runCompression(KeyPair.ALG_EC_FP);
- }
- // for F2m
- // - allocate, set custom curve, generate keypairs, -> export generated.
- // - test ecdh with local and remote simply(no compression)
- // - test local privkey, remote pubkey (compressed)
- // - test local privkey, remote pubkey (hybrid)
- // - test local privkey, remote pubkey (hybrid with wrong y)
- // - test local privkey, remote pubkey (point at infinity)
- if (cfg.binaryField) {
- runCompression(KeyPair.ALG_EC_F2M);
- }
-
- // Now, do ECDH over SECG curves and give the implementation a compressed key that is not a quadratic residue in
- // decompression.
- runNonResidue();
- }
-
- private void runCompression(byte field) throws Exception {
- short[] keySizes = field == KeyPair.ALG_EC_FP ? EC_Consts.FP_SIZES : EC_Consts.F2M_SIZES;
- short domain = field == KeyPair.ALG_EC_FP ? EC_Consts.PARAMETERS_DOMAIN_FP : EC_Consts.PARAMETERS_DOMAIN_F2M;
-
- for (short keyLength : keySizes) {
- String spec = keyLength + "b " + CardUtil.getKeyTypeString(field);
- byte curveId = EC_Consts.getCurve(keyLength, field);
-
- Test allocateFirst = runTest(CommandTest.expect(new Command.Allocate(this.card, ECTesterApplet.KEYPAIR_BOTH, keyLength, field), Result.ExpectedValue.SUCCESS));
- if (!allocateFirst.ok()) {
- doTest(CompoundTest.all(Result.ExpectedValue.SUCCESS, "No support for compression test on " + spec + ".", allocateFirst));
- continue;
- }
-
- List<Test> compressionTests = new LinkedList<>();
- compressionTests.add(allocateFirst);
- Test setCustom = runTest(CommandTest.expect(new Command.Set(this.card, ECTesterApplet.KEYPAIR_BOTH, curveId, domain, null), Result.ExpectedValue.SUCCESS));
- Test genCustom = runTest(CommandTest.expect(new Command.Generate(this.card, ECTesterApplet.KEYPAIR_BOTH), Result.ExpectedValue.SUCCESS));
- compressionTests.add(setCustom);
- compressionTests.add(genCustom);
-
- Response.Export key = new Command.Export(this.card, ECTesterApplet.KEYPAIR_REMOTE, EC_Consts.KEY_PUBLIC, EC_Consts.PARAMETER_W).send();
- byte[] pubkey = key.getParameter(ECTesterApplet.KEYPAIR_REMOTE, EC_Consts.KEY_PUBLIC);
- EC_Curve secgCurve = EC_Store.getInstance().getObject(EC_Curve.class, "secg", CardUtil.getCurveName(curveId));
- ECPoint pub;
- try {
- pub = ECUtil.fromX962(pubkey, secgCurve.toCurve());
- } catch (IllegalArgumentException iae) {
- doTest(CompoundTest.all(Result.ExpectedValue.SUCCESS, "", compressionTests.toArray(new Test[0])));
- continue;
- }
-
- List<Test> kaTests = new LinkedList<>();
- for (byte kaType : EC_Consts.KA_TYPES) {
- List<Test> thisTests = new LinkedList<>();
- Test allocate = runTest(CommandTest.expect(new Command.AllocateKeyAgreement(this.card, kaType), Result.ExpectedValue.SUCCESS));
- if (allocate.ok()) {
- Test ka = runTest(CommandTest.expect(new Command.ECDH(this.card, ECTesterApplet.KEYPAIR_LOCAL, ECTesterApplet.KEYPAIR_REMOTE, ECTesterApplet.EXPORT_FALSE, EC_Consts.TRANSFORMATION_NONE, kaType), Result.ExpectedValue.SUCCESS));
-
- thisTests.add(CompoundTest.all(Result.ExpectedValue.SUCCESS, "KeyAgreement setup and basic test.", allocate, ka));
- if (ka.ok()) {
- // tests of the good stuff
- Test kaCompressed = CommandTest.expect(new Command.ECDH(this.card, ECTesterApplet.KEYPAIR_LOCAL, ECTesterApplet.KEYPAIR_REMOTE, ECTesterApplet.EXPORT_FALSE, EC_Consts.TRANSFORMATION_COMPRESS, kaType), Result.ExpectedValue.SUCCESS);
- Test kaHybrid = CommandTest.expect(new Command.ECDH(this.card, ECTesterApplet.KEYPAIR_LOCAL, ECTesterApplet.KEYPAIR_REMOTE, ECTesterApplet.EXPORT_FALSE, EC_Consts.TRANSFORMATION_COMPRESS_HYBRID, kaType), Result.ExpectedValue.SUCCESS);
- thisTests.add(CompoundTest.any(Result.ExpectedValue.SUCCESS, "Tests of compressed and hybrid form.", kaCompressed, kaHybrid));
-
- // tests the bad stuff here
- byte[] pubHybrid = ECUtil.toX962Hybrid(pub, keyLength);
- pubHybrid[pubHybrid.length - 1] ^= 1;
- byte[] pubHybridEncoded = ByteUtil.prependLength(pubHybrid);
- Test kaBadHybrid = CommandTest.expect(new Command.ECDH_direct(this.card, ECTesterApplet.KEYPAIR_LOCAL, ECTesterApplet.EXPORT_FALSE, EC_Consts.TRANSFORMATION_NONE, kaType, pubHybridEncoded), Result.ExpectedValue.FAILURE);
-
- byte[] pubInfinityEncoded = {0x01, 0x00};
- Test kaBadInfinity = CommandTest.expect(new Command.ECDH_direct(this.card, ECTesterApplet.KEYPAIR_LOCAL, ECTesterApplet.EXPORT_FALSE, EC_Consts.TRANSFORMATION_NONE, kaType, pubInfinityEncoded), Result.ExpectedValue.FAILURE);
- thisTests.add(CompoundTest.all(Result.ExpectedValue.SUCCESS, "Tests of corrupted hybrid form and infinity.", kaBadHybrid, kaBadInfinity));
- }
- kaTests.add(CompoundTest.all(Result.ExpectedValue.SUCCESS, "KeyAgreement tests of " + CardUtil.getKATypeString(kaType) + ".", thisTests.toArray(new Test[0])));
- }
- }
- compressionTests.addAll(kaTests);
- if (cfg.cleanup) {
- compressionTests.add(CommandTest.expect(new Command.Cleanup(this.card), Result.ExpectedValue.ANY));
- }
-
- doTest(CompoundTest.all(Result.ExpectedValue.SUCCESS, "Compression test of " + spec + ".", compressionTests.toArray(new Test[0])));
- }
- }
-
- private void runNonResidue() {
- Map<String, EC_Key.Public> otherKeys = EC_Store.getInstance().getObjects(EC_Key.Public.class, "misc");
- List<EC_Key.Public> compressionKeys = EC_Store.mapToPrefix(otherKeys.values()).get("compression");
-
- for (EC_Key.Public key : compressionKeys) {
- EC_Curve curve = EC_Store.getInstance().getObject(EC_Curve.class, key.getCurve());
- List<Test> tests = new LinkedList<>();
- Test allocate = runTest(CommandTest.expect(new Command.Allocate(this.card, ECTesterApplet.KEYPAIR_LOCAL, curve.getBits(), curve.getField()), Result.ExpectedValue.SUCCESS));
- if (!allocate.ok()) {
- doTest(CompoundTest.all(Result.ExpectedValue.SUCCESS, "No support for non-residue test on " + curve.getBits() + "b " + curve.getId() + ".", allocate));
- continue;
- }
- tests.add(allocate);
- tests.add(CommandTest.expect(new Command.Set(this.card, ECTesterApplet.KEYPAIR_LOCAL, EC_Consts.CURVE_external, curve.getParams(), curve.flatten()), Result.ExpectedValue.SUCCESS));
- tests.add(CommandTest.expect(new Command.Generate(this.card, ECTesterApplet.KEYPAIR_LOCAL), Result.ExpectedValue.SUCCESS));
- byte[] pointData = ECUtil.toX962Compressed(key.getParam(EC_Consts.PARAMETER_W));
- byte[] pointDataEncoded = ByteUtil.prependLength(pointData);
- tests.add(CommandTest.expect(new Command.ECDH_direct(this.card, ECTesterApplet.KEYPAIR_LOCAL, ECTesterApplet.EXPORT_FALSE, EC_Consts.TRANSFORMATION_NONE, EC_Consts.KeyAgreement_ALG_EC_SVDP_DH, pointDataEncoded), Result.ExpectedValue.FAILURE));
- doTest(CompoundTest.greedyAll(Result.ExpectedValue.SUCCESS, "Non-residue test of " + curve.getId() + ".", tests.toArray(new Test[0])));
- }
- }
-}
diff --git a/src/cz/crcs/ectester/reader/test/CardDefaultSuite.java b/src/cz/crcs/ectester/reader/test/CardDefaultSuite.java
deleted file mode 100644
index 8814c37..0000000
--- a/src/cz/crcs/ectester/reader/test/CardDefaultSuite.java
+++ /dev/null
@@ -1,141 +0,0 @@
-package cz.crcs.ectester.reader.test;
-
-import cz.crcs.ectester.applet.ECTesterApplet;
-import cz.crcs.ectester.applet.EC_Consts;
-import cz.crcs.ectester.common.output.TestWriter;
-import cz.crcs.ectester.common.test.CompoundTest;
-import cz.crcs.ectester.common.test.Result;
-import cz.crcs.ectester.common.test.Test;
-import cz.crcs.ectester.common.util.CardUtil;
-import cz.crcs.ectester.reader.CardMngr;
-import cz.crcs.ectester.reader.ECTesterReader;
-import cz.crcs.ectester.reader.command.Command;
-import javacard.security.KeyPair;
-
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Random;
-import java.util.function.Function;
-import java.util.stream.Collectors;
-import java.util.stream.Stream;
-
-import static cz.crcs.ectester.common.test.Result.ExpectedValue;
-import static cz.crcs.ectester.common.test.Result.Value;
-
-/**
- * @author Jan Jancar johny@neuromancer.sk
- */
-public class CardDefaultSuite extends CardTestSuite {
-
- public CardDefaultSuite(TestWriter writer, ECTesterReader.Config cfg, CardMngr cardManager) {
- super(writer, cfg, cardManager, "default", null, "The default test suite tests basic support and performance of ECDH and ECDSA.");
- }
-
- @Override
- protected void runTests() throws Exception {
- if (cfg.primeField) {
- runDefault(KeyPair.ALG_EC_FP);
- }
- if (cfg.binaryField) {
- runDefault(KeyPair.ALG_EC_F2M);
- }
- }
-
- private void runDefault(byte field) throws Exception {
- short[] keySizes = field == KeyPair.ALG_EC_FP ? EC_Consts.FP_SIZES : EC_Consts.F2M_SIZES;
- short domain = field == KeyPair.ALG_EC_FP ? EC_Consts.PARAMETERS_DOMAIN_FP : EC_Consts.PARAMETERS_DOMAIN_F2M;
- for (short keyLength : keySizes) {
-
- List<Test> supportTests = new LinkedList<>();
- Test allocateFirst = runTest(CommandTest.expect(new Command.Allocate(this.card, ECTesterApplet.KEYPAIR_BOTH, keyLength, field), ExpectedValue.SUCCESS));
- if (!allocateFirst.ok()) {
- doTest(CompoundTest.all(ExpectedValue.SUCCESS, "No support for " + keyLength + "b " + CardUtil.getKeyTypeString(field) + ".", allocateFirst));
- continue;
- }
- supportTests.add(allocateFirst);
-
- Test genDefault = runTest(CommandTest.expect(new Command.Generate(this.card, ECTesterApplet.KEYPAIR_BOTH), ExpectedValue.SUCCESS));
- Test allocateSecond = runTest(CommandTest.expect(new Command.Allocate(this.card, ECTesterApplet.KEYPAIR_BOTH, keyLength, field), ExpectedValue.SUCCESS));
- Test setCustom = runTest(CommandTest.expect(new Command.Set(this.card, ECTesterApplet.KEYPAIR_BOTH, EC_Consts.getCurve(keyLength, field), domain, null), ExpectedValue.SUCCESS));
- Test genCustom = runTest(CommandTest.expect(new Command.Generate(this.card, ECTesterApplet.KEYPAIR_BOTH), ExpectedValue.SUCCESS));
- supportTests.add(genDefault);
- supportTests.add(allocateSecond);
- supportTests.add(setCustom);
- supportTests.add(genCustom);
-
- List<Test> kaTests = new LinkedList<>();
- for (byte kaType : EC_Consts.KA_TYPES) {
- Test allocate = runTest(CommandTest.expect(new Command.AllocateKeyAgreement(this.card, kaType), ExpectedValue.SUCCESS));
- if (allocate.ok()) {
- Command ecdh = new Command.ECDH(this.card, ECTesterApplet.KEYPAIR_LOCAL, ECTesterApplet.KEYPAIR_REMOTE, ECTesterApplet.EXPORT_FALSE, EC_Consts.TRANSFORMATION_NONE, kaType);
- Test ka = runTest(CommandTest.expect(ecdh, ExpectedValue.SUCCESS));
- Test kaCompressed = runTest(CommandTest.expect(new Command.ECDH(this.card, ECTesterApplet.KEYPAIR_LOCAL, ECTesterApplet.KEYPAIR_REMOTE, ECTesterApplet.EXPORT_FALSE, EC_Consts.TRANSFORMATION_COMPRESS, kaType), ExpectedValue.SUCCESS));
-
- String kaDesc = "Test of the " + CardUtil.getKATypeString(kaType) + " KeyAgreement.";
- Function<Test[], Result> kaCallback = (tests) -> {
- if (tests[1].ok() || tests[2].ok()) {
- return new Result(Value.SUCCESS, "Some ECDH is supported.");
- } else {
- return new Result(Value.FAILURE, "ECDH failed.");
- }
- };
-
- Test compound;
- if (ka.ok()) {
- Test perfTest = runTest(PerformanceTest.repeat(this.card, ecdh, 10));
- compound = runTest(CompoundTest.function(kaCallback, kaDesc, allocate, ka, kaCompressed, perfTest));
- } else {
- compound = runTest(CompoundTest.function(kaCallback, kaDesc, allocate, ka, kaCompressed));
- }
-
- kaTests.add(compound);
- } else {
- runTest(allocate);
- kaTests.add(allocate);
- }
- }
- Test kaTest = runTest(CompoundTest.any(ExpectedValue.SUCCESS, "KeyAgreement tests.", kaTests.toArray(new Test[0])));
- supportTests.add(kaTest);
-
- List<Test> signTests = new LinkedList<>();
- for (byte sigType : EC_Consts.SIG_TYPES) {
- Test allocate = runTest(CommandTest.expect(new Command.AllocateSignature(this.card, sigType), ExpectedValue.SUCCESS));
- if (allocate.ok()) {
- Command ecdsa = new Command.ECDSA(this.card, ECTesterApplet.KEYPAIR_LOCAL, sigType, ECTesterApplet.EXPORT_FALSE, null);
- Test expect = runTest(CommandTest.expect(ecdsa, ExpectedValue.SUCCESS));
-
- String signDesc = "Test of the " + CardUtil.getSigTypeString(sigType) + " signature.";
-
- Random rand = new Random();
- byte[] sigData = new byte[64];
- rand.nextBytes(sigData);
-
- Test compound;
- if (expect.ok()) {
- Command ecdsaSign = new Command.ECDSA_sign(this.card, ECTesterApplet.KEYPAIR_LOCAL, sigType, ECTesterApplet.EXPORT_TRUE, sigData);
- PerformanceTest signTest = runTest(PerformanceTest.repeat(this.card, "Sign", ecdsaSign, 10));
- byte[] signature = signTest.getResponses()[0].getParam(0);
- Command ecdsaVerify = new Command.ECDSA_verify(this.card, ECTesterApplet.KEYPAIR_LOCAL, sigType, sigData, signature);
- PerformanceTest verifyTest = runTest(PerformanceTest.repeat(this.card, "Verify", ecdsaVerify, 10));
- compound = runTest(CompoundTest.all(ExpectedValue.SUCCESS, signDesc, allocate, expect, signTest, verifyTest));
- } else {
- compound = runTest(CompoundTest.all(ExpectedValue.SUCCESS, signDesc, allocate, expect));
- }
- signTests.add(compound);
- } else {
- signTests.add(allocate);
- }
- }
- Test signTest = runTest(CompoundTest.any(ExpectedValue.SUCCESS, "Signature tests.", signTests.toArray(new Test[0])));
- supportTests.add(signTest);
- ExpectedValue[] testExpects = {ExpectedValue.SUCCESS, ExpectedValue.ANY, ExpectedValue.SUCCESS, ExpectedValue.SUCCESS, ExpectedValue.SUCCESS, ExpectedValue.SUCCESS, ExpectedValue.SUCCESS};
- List<ExpectedValue> expects = Stream.of(testExpects).collect(Collectors.toList());
- if (cfg.cleanup) {
- supportTests.add(CommandTest.expect(new Command.Cleanup(this.card), Result.ExpectedValue.ANY));
- expects.add(ExpectedValue.ANY);
- }
-
- doTest(CompoundTest.mask(expects.toArray(new ExpectedValue[0]), "Tests of " + keyLength + "b " + CardUtil.getKeyTypeString(field) + " support.", supportTests.toArray(new Test[0])));
- }
- }
-}
diff --git a/src/cz/crcs/ectester/reader/test/CardDegenerateSuite.java b/src/cz/crcs/ectester/reader/test/CardDegenerateSuite.java
deleted file mode 100644
index f2e73b6..0000000
--- a/src/cz/crcs/ectester/reader/test/CardDegenerateSuite.java
+++ /dev/null
@@ -1,69 +0,0 @@
-package cz.crcs.ectester.reader.test;
-
-import cz.crcs.ectester.applet.ECTesterApplet;
-import cz.crcs.ectester.applet.EC_Consts;
-import cz.crcs.ectester.common.ec.EC_Curve;
-import cz.crcs.ectester.common.ec.EC_Key;
-import cz.crcs.ectester.common.output.TestWriter;
-import cz.crcs.ectester.common.test.CompoundTest;
-import cz.crcs.ectester.common.test.Result;
-import cz.crcs.ectester.common.test.Test;
-import cz.crcs.ectester.common.util.CardUtil;
-import cz.crcs.ectester.data.EC_Store;
-import cz.crcs.ectester.reader.CardMngr;
-import cz.crcs.ectester.reader.ECTesterReader;
-import cz.crcs.ectester.reader.command.Command;
-
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-
-/**
- * @author Jan Jancar johny@neuromancer.sk
- */
-public class CardDegenerateSuite extends CardTestSuite {
-
- public CardDegenerateSuite(TestWriter writer, ECTesterReader.Config cfg, CardMngr cardManager) {
- super(writer, cfg, cardManager, "degenerate", null, "The degenerate suite tests whether the card rejects points outside of the curve during ECDH.",
- "The tested points lie on a part of the plane for which some Edwards, Hessian and Huff form addition formulas degenerate into exponentiation in the base finite field.");
- }
-
- @Override
- protected void runTests() throws Exception {
- Map<String, EC_Key.Public> pubkeys = EC_Store.getInstance().getObjects(EC_Key.Public.class, "degenerate");
- Map<EC_Curve, List<EC_Key.Public>> curveList = EC_Store.mapKeyToCurve(pubkeys.values());
- for (Map.Entry<EC_Curve, List<EC_Key.Public>> e : curveList.entrySet()) {
- EC_Curve curve = e.getKey();
- List<EC_Key.Public> keys = e.getValue();
-
- Test allocate = runTest(CommandTest.expect(new Command.Allocate(this.card, ECTesterApplet.KEYPAIR_BOTH, curve.getBits(), curve.getField()), Result.ExpectedValue.SUCCESS));
- if (!allocate.ok()) {
- doTest(CompoundTest.all(Result.ExpectedValue.SUCCESS, "No support for " + curve.getId() + ".", allocate));
- continue;
- }
- Test set = CommandTest.expect(new Command.Set(this.card, ECTesterApplet.KEYPAIR_BOTH, EC_Consts.CURVE_external, curve.getParams(), curve.flatten()), Result.ExpectedValue.SUCCESS);
- Test generate = CommandTest.expect(new Command.Generate(this.card, ECTesterApplet.KEYPAIR_LOCAL), Result.ExpectedValue.SUCCESS);
-
- Test prepare = CompoundTest.all(Result.ExpectedValue.SUCCESS, "Prepare and generate keypair on " + curve.getId() + ".", allocate, set, generate);
-
- List<Test> ecdhTests = new LinkedList<>();
- for (EC_Key.Public pub : keys) {
- Test setPub = CommandTest.expect(new Command.Set(this.card, ECTesterApplet.KEYPAIR_REMOTE, EC_Consts.CURVE_external, pub.getParams(), pub.flatten()), Result.ExpectedValue.FAILURE);
- Test ecdh = CommandTest.expect(new Command.ECDH(this.card, ECTesterApplet.KEYPAIR_REMOTE, ECTesterApplet.KEYPAIR_LOCAL, ECTesterApplet.EXPORT_FALSE, EC_Consts.TRANSFORMATION_NONE, EC_Consts.KeyAgreement_ALG_EC_SVDP_DH), Result.ExpectedValue.FAILURE, "Card correctly rejected point on degenerate curve.", "Card incorrectly accepted point on degenerate curve.");
- Test objectEcdh = CompoundTest.any(Result.ExpectedValue.SUCCESS, CardUtil.getKATypeString(EC_Consts.KeyAgreement_ALG_EC_SVDP_DH) + " test with degenerate pubkey.", setPub, ecdh);
- Command ecdhCommand = new Command.ECDH_direct(this.card, ECTesterApplet.KEYPAIR_LOCAL, ECTesterApplet.EXPORT_FALSE, EC_Consts.TRANSFORMATION_NONE, EC_Consts.KeyAgreement_ALG_EC_SVDP_DH, pub.flatten());
- Test rawEcdh = CommandTest.expect(ecdhCommand, Result.ExpectedValue.FAILURE, "Card correctly rejected point on degenerate curve.", "Card incorrectly accepted point on degenerate curve.");
- ecdhTests.add(CompoundTest.all(Result.ExpectedValue.SUCCESS, pub.getId() + " degenerate key test.", objectEcdh, rawEcdh));
- //TODO: actually get the result of ECDH here, as well as export privkey and compare to exponentiation in Fp^*.
- }
- Test ecdh = CompoundTest.all(Result.ExpectedValue.SUCCESS, "Perform ECDH with degenerate public points.", ecdhTests.toArray(new Test[0]));
- if (cfg.cleanup) {
- Test cleanup = CommandTest.expect(new Command.Cleanup(this.card), Result.ExpectedValue.ANY);
- doTest(CompoundTest.greedyAllTry(Result.ExpectedValue.SUCCESS, "Degenerate curve test of " + curve.getId() + ".", prepare, ecdh, cleanup));
- } else {
- doTest(CompoundTest.greedyAllTry(Result.ExpectedValue.SUCCESS, "Degenerate curve test of " + curve.getId() + ".", prepare, ecdh));
- }
-
- }
- }
-}
diff --git a/src/cz/crcs/ectester/reader/test/CardEdgeCasesSuite.java b/src/cz/crcs/ectester/reader/test/CardEdgeCasesSuite.java
deleted file mode 100644
index 9257b3d..0000000
--- a/src/cz/crcs/ectester/reader/test/CardEdgeCasesSuite.java
+++ /dev/null
@@ -1,336 +0,0 @@
-package cz.crcs.ectester.reader.test;
-
-import cz.crcs.ectester.applet.ECTesterApplet;
-import cz.crcs.ectester.applet.EC_Consts;
-import cz.crcs.ectester.common.ec.EC_Curve;
-import cz.crcs.ectester.common.ec.EC_KAResult;
-import cz.crcs.ectester.common.ec.EC_Key;
-import cz.crcs.ectester.common.ec.EC_Params;
-import cz.crcs.ectester.common.output.TestWriter;
-import cz.crcs.ectester.common.test.CompoundTest;
-import cz.crcs.ectester.common.test.Result;
-import cz.crcs.ectester.common.test.Test;
-import cz.crcs.ectester.common.test.TestCallback;
-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.reader.CardMngr;
-import cz.crcs.ectester.reader.ECTesterReader;
-import cz.crcs.ectester.reader.command.Command;
-import cz.crcs.ectester.reader.response.Response;
-import javacard.security.CryptoException;
-import javacard.security.KeyPair;
-
-import java.math.BigDecimal;
-import java.math.BigInteger;
-import java.util.*;
-import java.util.stream.Collectors;
-
-/**
- * @author Jan Jancar johny@neuromancer.sk
- */
-public class CardEdgeCasesSuite extends CardTestSuite {
- public CardEdgeCasesSuite(TestWriter writer, ECTesterReader.Config cfg, CardMngr cardManager) {
- super(writer, cfg, cardManager, "edge-cases", null, "The edge-cases test suite tests various inputs to ECDH which may cause an implementation to achieve a certain edge-case state during it.",
- "Some of the data is from the google/Wycheproof project. Tests include CVE-2017-10176 and CVE-2017-8932.",
- "Also tests values of the private key and public key that would trigger the OpenSSL modular multiplication bug on the P-256 curve.",
- "Various edge private key values are also tested.");
- }
-
- @Override
- protected void runTests() throws Exception {
- Map<String, EC_KAResult> results = EC_Store.getInstance().getObjects(EC_KAResult.class, "wycheproof");
- Map<String, List<EC_KAResult>> groups = EC_Store.mapToPrefix(results.values());
- for (Map.Entry<String, List<EC_KAResult>> e : groups.entrySet()) {
- String description = null;
- switch (e.getKey()) {
- case "addsub":
- description = "Tests for addition-subtraction chains.";
- break;
- case "cve_2017_10176":
- description = "Tests for CVE-2017-10176.";
- break;
- case "cve_2017_8932":
- description = "Tests for CVE-2017-8932.";
- break;
- }
-
- List<Test> groupTests = new LinkedList<>();
- Map<EC_Curve, List<EC_KAResult>> curveList = EC_Store.mapResultToCurve(e.getValue());
- for (Map.Entry<EC_Curve, List<EC_KAResult>> c : curveList.entrySet()) {
- EC_Curve curve = c.getKey();
-
- List<Test> curveTests = new LinkedList<>();
- Test allocate = CommandTest.expect(new Command.Allocate(this.card, ECTesterApplet.KEYPAIR_BOTH, curve.getBits(), curve.getField()), Result.ExpectedValue.SUCCESS);
- Test set = CommandTest.expect(new Command.Set(this.card, ECTesterApplet.KEYPAIR_BOTH, EC_Consts.CURVE_external, curve.getParams(), curve.flatten()), Result.ExpectedValue.SUCCESS);
- Test prepareCurve = CompoundTest.greedyAll(Result.ExpectedValue.SUCCESS, "Prepare curve", allocate, set);
-
- List<EC_KAResult> values = c.getValue();
- for (EC_KAResult value : values) {
- String id = value.getId();
- String privkeyId = value.getOneKey();
- String pubkeyId = value.getOtherKey();
-
- EC_Key.Private privkey = EC_Store.getInstance().getObject(EC_Key.Private.class, privkeyId);
- EC_Key.Public pubkey = EC_Store.getInstance().getObject(EC_Key.Public.class, pubkeyId);
-
- Test setPrivkey = CommandTest.expect(new Command.Set(this.card, ECTesterApplet.KEYPAIR_LOCAL, EC_Consts.CURVE_external, privkey.getParams(), privkey.flatten()), Result.ExpectedValue.SUCCESS);
- Test setPubkey = CommandTest.expect(new Command.Set(this.card, ECTesterApplet.KEYPAIR_REMOTE, EC_Consts.CURVE_external, pubkey.getParams(), pubkey.flatten()), Result.ExpectedValue.SUCCESS);
- Test ecdhPreTest = CommandTest.expect(new Command.ECDH(this.card, ECTesterApplet.KEYPAIR_REMOTE, ECTesterApplet.KEYPAIR_LOCAL, ECTesterApplet.EXPORT_FALSE, EC_Consts.TRANSFORMATION_NONE, EC_Consts.KeyAgreement_ALG_EC_SVDP_DH), Result.ExpectedValue.SUCCESS);
- Test ecdh = CommandTest.function(new Command.ECDH(this.card, ECTesterApplet.KEYPAIR_REMOTE, ECTesterApplet.KEYPAIR_LOCAL, ECTesterApplet.EXPORT_TRUE, EC_Consts.TRANSFORMATION_NONE, value.getJavaCardKA()), new TestCallback<CommandTestable>() {
- @Override
- public Result apply(CommandTestable testable) {
- Response.ECDH dh = (Response.ECDH) testable.getResponse();
- if (dh.getSW(0) == CryptoException.NO_SUCH_ALGORITHM) {
- return new Result(Result.Value.SUCCESS, "ECDH algorithm unsupported.");
- }
- if (!dh.successful())
- return new Result(Result.Value.FAILURE, "ECDH was unsuccessful.");
- if (!dh.hasSecret())
- return new Result(Result.Value.FAILURE, "ECDH response did not contain the derived secret.");
- if (!ByteUtil.compareBytes(dh.getSecret(), 0, value.getData(0), 0, dh.secretLength())) {
- int firstDiff = ByteUtil.diffBytes(dh.getSecret(), 0, value.getData(0), 0, dh.secretLength());
- System.err.println(ByteUtil.bytesToHex(dh.getSecret()));
- System.err.println(ByteUtil.bytesToHex(value.getData(0)));
- return new Result(Result.Value.FAILURE, "ECDH derived secret does not match the test-vector, first difference was at byte " + firstDiff + ".");
- }
- return new Result(Result.Value.SUCCESS);
- }
- });
-
- Test prepare = CompoundTest.greedyAll(Result.ExpectedValue.SUCCESS, "Prepare", setPrivkey, setPubkey);
- Test ka = CompoundTest.all(Result.ExpectedValue.SUCCESS, "Do", ecdhPreTest, ecdh);
-
- Test one = CompoundTest.greedyAllTry(Result.ExpectedValue.SUCCESS, "Test " + id + ".", prepare, ka);
- curveTests.add(one);
- }
-
- if (cfg.cleanup) {
- curveTests.add(CommandTest.expect(new Command.Cleanup(this.card), Result.ExpectedValue.ANY));
- }
-
- Test curveTest = CompoundTest.all(Result.ExpectedValue.SUCCESS, "Tests", curveTests.toArray(new Test[0]));
- groupTests.add(CompoundTest.greedyAllTry(Result.ExpectedValue.SUCCESS, "Tests on " + curve.getId() + ".", prepareCurve, curveTest));
- }
- doTest(CompoundTest.all(Result.ExpectedValue.SUCCESS, description, groupTests.toArray(new Test[0])));
- }
-
- {
- EC_KAResult openssl_bug = EC_Store.getInstance().getObject(EC_KAResult.class, "misc", "openssl-bug");
- EC_Curve curve = EC_Store.getInstance().getObject(EC_Curve.class, openssl_bug.getCurve());
- EC_Key.Private skey = EC_Store.getInstance().getObject(EC_Key.Private.class, openssl_bug.getOtherKey());
- EC_Key.Public pkey = EC_Store.getInstance().getObject(EC_Key.Public.class, openssl_bug.getOneKey());
- Test key = CommandTest.expect(new Command.Allocate(this.card, ECTesterApplet.KEYPAIR_BOTH, curve.getBits(), KeyPair.ALG_EC_FP), Result.ExpectedValue.SUCCESS);
- Test set = CommandTest.expect(new Command.Set(this.card, ECTesterApplet.KEYPAIR_BOTH, EC_Consts.CURVE_external, curve.getParams(), curve.flatten()), Result.ExpectedValue.SUCCESS);
- Test setPrivate = CommandTest.expect(new Command.Set(this.card, ECTesterApplet.KEYPAIR_LOCAL, EC_Consts.CURVE_external, EC_Consts.PARAMETER_S, skey.flatten(EC_Consts.PARAMETER_S)), Result.ExpectedValue.SUCCESS);
- Test setPublic = CommandTest.expect(new Command.Set(this.card, ECTesterApplet.KEYPAIR_REMOTE, EC_Consts.CURVE_external, EC_Consts.PARAMETER_W, pkey.flatten(EC_Consts.PARAMETER_W)), Result.ExpectedValue.SUCCESS);
- Test ecdh = CommandTest.function(new Command.ECDH(this.card, ECTesterApplet.KEYPAIR_REMOTE, ECTesterApplet.KEYPAIR_LOCAL, ECTesterApplet.EXPORT_TRUE, EC_Consts.TRANSFORMATION_NONE, openssl_bug.getJavaCardKA()), new TestCallback<CommandTestable>() {
- @Override
- public Result apply(CommandTestable testable) {
- Response.ECDH dh = (Response.ECDH) testable.getResponse();
- if (!dh.successful())
- return new Result(Result.Value.FAILURE, "ECDH was unsuccessful.");
- if (!dh.hasSecret())
- return new Result(Result.Value.FAILURE, "ECDH response did not contain the derived secret.");
- if (ByteUtil.compareBytes(dh.getSecret(), 0, openssl_bug.getData(0), 0, dh.secretLength())) {
- return new Result(Result.Value.FAILURE, "OpenSSL bug is present, derived secret matches example.");
- }
- return new Result(Result.Value.SUCCESS);
- }
- });
-
- doTest(CompoundTest.greedyAll(Result.ExpectedValue.SUCCESS, "Test OpenSSL modular reduction bug.", key, set, setPrivate, setPublic, ecdh));
- }
-
- Map<String, EC_Curve> curveMap = EC_Store.getInstance().getObjects(EC_Curve.class, "secg");
- List<EC_Curve> curves = curveMap.entrySet().stream().filter((e) -> e.getKey().endsWith("r1") && e.getValue().getField() == KeyPair.ALG_EC_FP).map(Map.Entry::getValue).collect(Collectors.toList());
- curves.add(EC_Store.getInstance().getObject(EC_Curve.class, "cofactor/cofactor128p2"));
- curves.add(EC_Store.getInstance().getObject(EC_Curve.class, "cofactor/cofactor160p4"));
- Random rand = new Random();
- for (EC_Curve curve : curves) {
- Test key = runTest(CommandTest.expect(new Command.Allocate(this.card, ECTesterApplet.KEYPAIR_BOTH, curve.getBits(), KeyPair.ALG_EC_FP), Result.ExpectedValue.SUCCESS));
- if (!key.ok()) {
- doTest(CompoundTest.all(Result.ExpectedValue.FAILURE, "No support for " + curve.getBits() + "b " + curve.getId() + ".", key));
- continue;
- }
- Test set = CommandTest.expect(new Command.Set(this.card, ECTesterApplet.KEYPAIR_BOTH, EC_Consts.CURVE_external, curve.getParams(), curve.flatten()), Result.ExpectedValue.SUCCESS);
- Test generate = CommandTest.expect(new Command.Generate(this.card, ECTesterApplet.KEYPAIR_LOCAL), Result.ExpectedValue.SUCCESS);
- CommandTest export = CommandTest.expect(new Command.Export(this.card, ECTesterApplet.KEYPAIR_LOCAL, EC_Consts.KEY_PUBLIC, EC_Consts.PARAMETER_W), Result.ExpectedValue.SUCCESS);
- Test setup = runTest(CompoundTest.all(Result.ExpectedValue.SUCCESS, "KeyPair setup.", key, set, generate, export));
-
- /*
- byte[] pParam = curve.getParam(EC_Consts.PARAMETER_FP)[0];
- BigInteger p = new BigInteger(1, pParam);
- byte[] wParam = ((Response.Export) export.getResponse()).getParameter(ECTesterApplet.KEYPAIR_LOCAL, EC_Consts.PARAMETER_W);
- byte[] xValue = new byte[(wParam.length - 1) / 2];
- byte[] yValue = new byte[(wParam.length - 1) / 2];
- System.arraycopy(wParam, 1, xValue, 0, xValue.length);
- System.arraycopy(wParam, (wParam.length / 2) + 1, yValue, 0, yValue.length);
- BigInteger y = new BigInteger(1, yValue);
- BigInteger negY = p.subtract(y);
- byte[] newY = ECUtil.toByteArray(negY, curve.getBits());
-
- EC_Params negYParams = new EC_Params(EC_Consts.PARAMETER_W, new byte[][]{xValue, newY});
- Test negYTest = ecdhTest(new Command.Set(this.card, ECTesterApplet.KEYPAIR_LOCAL, EC_Consts.CURVE_external, negYParams.getParams(), negYParams.flatten()), "ECDH with pubkey negated.", Result.ExpectedValue.FAILURE, Result.ExpectedValue.FAILURE);
- */
-
- Test zeroS = ecdhTest(new Command.Transform(this.card, ECTesterApplet.KEYPAIR_REMOTE, EC_Consts.CURVE_external, EC_Consts.PARAMETER_S, EC_Consts.TRANSFORMATION_ZERO), "ECDH with S = 0.", Result.ExpectedValue.FAILURE, Result.ExpectedValue.FAILURE);
- Test oneS = ecdhTest(new Command.Transform(this.card, ECTesterApplet.KEYPAIR_REMOTE, EC_Consts.CURVE_external, EC_Consts.PARAMETER_S, EC_Consts.TRANSFORMATION_ONE), "ECDH with S = 1.", Result.ExpectedValue.FAILURE, Result.ExpectedValue.FAILURE);
-
- byte[] rParam = curve.getParam(EC_Consts.PARAMETER_R)[0];
- BigInteger R = new BigInteger(1, rParam);
- BigInteger smaller = new BigInteger(curve.getBits(), rand).mod(R);
- BigInteger diff = R.divide(BigInteger.valueOf(10));
- BigInteger randDiff = new BigInteger(diff.bitLength(), rand).mod(diff);
- BigInteger larger = R.add(randDiff);
-
- BigInteger full = BigInteger.valueOf(1).shiftLeft(R.bitLength() - 1).subtract(BigInteger.ONE);
-
- BigInteger alternate = full;
- for (int i = 0; i < R.bitLength(); i += 2) {
- alternate = alternate.clearBit(i);
- }
-
- BigInteger alternateOther = alternate.xor(full);
-
- EC_Params alternateParams = makeParams(alternate);
- Test alternateS = ecdhTest(new Command.Set(this.card, ECTesterApplet.KEYPAIR_REMOTE, EC_Consts.CURVE_external, alternateParams.getParams(), alternateParams.flatten()), "ECDH with S = 101010101...01010.", Result.ExpectedValue.SUCCESS, Result.ExpectedValue.SUCCESS);
-
- EC_Params alternateOtherParams = makeParams(alternateOther);
- Test alternateOtherS = ecdhTest(new Command.Set(this.card, ECTesterApplet.KEYPAIR_REMOTE, EC_Consts.CURVE_external, alternateOtherParams.getParams(), alternateOtherParams.flatten()), "ECDH with S = 010101010...10101.", Result.ExpectedValue.SUCCESS, Result.ExpectedValue.SUCCESS);
-
- EC_Params fullParams = makeParams(full);
- Test fullS = ecdhTest(new Command.Set(this.card, ECTesterApplet.KEYPAIR_REMOTE, EC_Consts.CURVE_external, fullParams.getParams(), fullParams.flatten()), "ECDH with S = 111111111...11111 (but < r).", Result.ExpectedValue.SUCCESS, Result.ExpectedValue.SUCCESS);
-
- EC_Params smallerParams = makeParams(smaller);
- Test smallerS = ecdhTest(new Command.Set(this.card, ECTesterApplet.KEYPAIR_REMOTE, EC_Consts.CURVE_external, smallerParams.getParams(), smallerParams.flatten()), "ECDH with S < r.", Result.ExpectedValue.SUCCESS, Result.ExpectedValue.SUCCESS);
-
- EC_Params exactParams = makeParams(R);
- Test exactS = ecdhTest(new Command.Set(this.card, ECTesterApplet.KEYPAIR_REMOTE, EC_Consts.CURVE_external, exactParams.getParams(), exactParams.flatten()), "ECDH with S = r.", Result.ExpectedValue.FAILURE, Result.ExpectedValue.FAILURE);
-
- EC_Params largerParams = makeParams(larger);
- Test largerS = ecdhTest(new Command.Set(this.card, ECTesterApplet.KEYPAIR_REMOTE, EC_Consts.CURVE_external, largerParams.getParams(), largerParams.flatten()), "ECDH with S > r.", Result.ExpectedValue.ANY, Result.ExpectedValue.ANY);
-
- BigInteger rm1 = R.subtract(BigInteger.ONE);
- BigInteger rp1 = R.add(BigInteger.ONE);
-
- EC_Params rm1Params = makeParams(rm1);
- Test rm1S = ecdhTest(new Command.Set(this.card, ECTesterApplet.KEYPAIR_REMOTE, EC_Consts.CURVE_external, rm1Params.getParams(), rm1Params.flatten()), "ECDH with S = r - 1.", Result.ExpectedValue.SUCCESS, Result.ExpectedValue.SUCCESS);
-
- EC_Params rp1Params = makeParams(rp1);
- Test rp1S = ecdhTest(new Command.Set(this.card, ECTesterApplet.KEYPAIR_REMOTE, EC_Consts.CURVE_external, rp1Params.getParams(), rp1Params.flatten()), "ECDH with S = r + 1.", Result.ExpectedValue.ANY, Result.ExpectedValue.ANY);
-
- byte[] k = curve.getParam(EC_Consts.PARAMETER_K)[0];
- BigInteger K = new BigInteger(1, k);
- BigInteger kr = K.multiply(R);
- BigInteger krm1 = kr.subtract(BigInteger.ONE);
- BigInteger krp1 = kr.add(BigInteger.ONE);
-
- Result.ExpectedValue kExpected = K.equals(BigInteger.ONE) ? Result.ExpectedValue.SUCCESS : Result.ExpectedValue.FAILURE;
-
- EC_Params krParams = makeParams(kr);
- Test krS /*ONE!*/ = ecdhTest(new Command.Set(this.card, ECTesterApplet.KEYPAIR_REMOTE, EC_Consts.CURVE_external, krParams.getParams(), krParams.flatten()), "ECDH with S = k * r.", Result.ExpectedValue.FAILURE, Result.ExpectedValue.FAILURE);
-
- EC_Params krm1Params = makeParams(krm1);
- Test krm1S = ecdhTest(new Command.Set(this.card, ECTesterApplet.KEYPAIR_REMOTE, EC_Consts.CURVE_external, krm1Params.getParams(), krm1Params.flatten()), "ECDH with S = (k * r) - 1.", kExpected, kExpected);
-
- EC_Params krp1Params = makeParams(krp1);
- Test krp1S = ecdhTest(new Command.Set(this.card, ECTesterApplet.KEYPAIR_REMOTE, EC_Consts.CURVE_external, krp1Params.getParams(), krp1Params.flatten()), "ECDH with S = (k * r) + 1.", Result.ExpectedValue.ANY, Result.ExpectedValue.ANY);
-
- if (cfg.cleanup) {
- Test cleanup = CommandTest.expect(new Command.Cleanup(this.card), Result.ExpectedValue.ANY);
- doTest(CompoundTest.all(Result.ExpectedValue.SUCCESS, "Tests with edge-case private key values over " + curve.getId() + ".", setup, zeroS, oneS, alternateS, alternateOtherS, fullS, smallerS, exactS, largerS, rm1S, rp1S, krS, krm1S, krp1S, cleanup));
- } else {
- doTest(CompoundTest.all(Result.ExpectedValue.SUCCESS, "Tests with edge-case private key values over " + curve.getId() + ".", setup, zeroS, oneS, alternateS, alternateOtherS, fullS, smallerS, exactS, largerS, rm1S, rp1S, krS, krm1S, krp1S));
- }
- }
-
- EC_Curve secp160r1 = EC_Store.getInstance().getObject(EC_Curve.class, "secg/secp160r1");
- byte[] pData = secp160r1.getParam(EC_Consts.PARAMETER_FP)[0];
- BigInteger p = new BigInteger(1, pData);
- byte[] rData = secp160r1.getParam(EC_Consts.PARAMETER_R)[0];
- BigInteger r = new BigInteger(1, rData);
-
- BigInteger range = r.subtract(p);
- BigInteger deviation = range.divide(BigInteger.valueOf(5));
- BigDecimal dev = new BigDecimal(deviation);
- BigDecimal smallDev = new BigDecimal(10000);
- int n = 10;
- BigInteger[] rs = new BigInteger[n];
- BigInteger[] ps = new BigInteger[n];
- BigInteger[] zeros = new BigInteger[n];
- for (int i = 0; i < n; ++i) {
- double sample;
- do {
- sample = rand.nextGaussian();
- } while (sample >= -1 && sample <= 1);
- BigInteger where = dev.multiply(new BigDecimal(sample)).toBigInteger();
- rs[i] = where.add(r);
- ps[i] = where.add(p);
- zeros[i] = smallDev.multiply(new BigDecimal(sample)).toBigInteger().abs();
- }
- Arrays.sort(rs);
- Arrays.sort(ps);
- Arrays.sort(zeros);
-
- Test key = runTest(CommandTest.expect(new Command.Allocate(this.card, ECTesterApplet.KEYPAIR_BOTH, secp160r1.getBits(), KeyPair.ALG_EC_FP), Result.ExpectedValue.SUCCESS));
- if (!key.ok()) {
- doTest(CompoundTest.all(Result.ExpectedValue.FAILURE, "No support for " + secp160r1.getBits() + "b secp160r1.", key));
- return;
- }
- Test set = CommandTest.expect(new Command.Set(this.card, ECTesterApplet.KEYPAIR_BOTH, EC_Consts.CURVE_external, secp160r1.getParams(), secp160r1.flatten()), Result.ExpectedValue.SUCCESS);
- Test generate = CommandTest.expect(new Command.Generate(this.card, ECTesterApplet.KEYPAIR_LOCAL), Result.ExpectedValue.SUCCESS);
- Test setup = CompoundTest.all(Result.ExpectedValue.SUCCESS, "KeyPair setup.", key, set, generate);
-
- Test[] zeroTests = new Test[n];
- int i = 0;
- for (BigInteger nearZero : zeros) {
- EC_Params params = makeParams(nearZero);
- zeroTests[i++] = ecdhTestBoth(new Command.Set(this.card, ECTesterApplet.KEYPAIR_REMOTE, EC_Consts.CURVE_external, params.getParams(), params.flatten()), nearZero.toString(16), Result.ExpectedValue.SUCCESS, Result.ExpectedValue.SUCCESS);
- }
- Test zeroTest = CompoundTest.all(Result.ExpectedValue.SUCCESS, "Near zero.", zeroTests);
-
- Test[] pTests = new Test[n];
- i = 0;
- for (BigInteger nearP : ps) {
- EC_Params params = makeParams(nearP);
- pTests[i++] = ecdhTestBoth(new Command.Set(this.card, ECTesterApplet.KEYPAIR_REMOTE, EC_Consts.CURVE_external, params.getParams(), params.flatten()), nearP.toString(16) + (nearP.compareTo(p) > 0 ? " (>p)" : " (<=p)"), Result.ExpectedValue.SUCCESS, Result.ExpectedValue.SUCCESS);
- }
- Test pTest = CompoundTest.all(Result.ExpectedValue.SUCCESS, "Near p.", pTests);
-
- Test[] rTests = new Test[n];
- i = 0;
- for (BigInteger nearR : rs) {
- EC_Params params = makeParams(nearR);
- if (nearR.compareTo(r) >= 0) {
- rTests[i++] = ecdhTest(new Command.Set(this.card, ECTesterApplet.KEYPAIR_REMOTE, EC_Consts.CURVE_external, params.getParams(), params.flatten()), nearR.toString(16) + " (>=r)", Result.ExpectedValue.FAILURE, Result.ExpectedValue.FAILURE);
- } else {
- rTests[i++] = ecdhTestBoth(new Command.Set(this.card, ECTesterApplet.KEYPAIR_REMOTE, EC_Consts.CURVE_external, params.getParams(), params.flatten()), nearR.toString(16) + " (<r)", Result.ExpectedValue.SUCCESS, Result.ExpectedValue.SUCCESS);
- }
- }
- Test rTest = CompoundTest.all(Result.ExpectedValue.SUCCESS, "Near r.", rTests);
- doTest(CompoundTest.all(Result.ExpectedValue.SUCCESS, "Test private key values near zero, near p and near/larger than the order.", setup, zeroTest, pTest, rTest));
- }
-
- private Test ecdhTestBoth(Command setPriv, String desc, Result.ExpectedValue setExpect, Result.ExpectedValue ecdhExpect) {
- Test set = CommandTest.expect(setPriv, setExpect);
- Test ecdh = CommandTest.expect(new Command.ECDH(this.card, ECTesterApplet.KEYPAIR_LOCAL, ECTesterApplet.KEYPAIR_REMOTE, ECTesterApplet.EXPORT_TRUE, EC_Consts.TRANSFORMATION_NONE, EC_Consts.KeyAgreement_ALG_EC_SVDP_DH), ecdhExpect);
-
- return CompoundTest.all(Result.ExpectedValue.SUCCESS, desc, set, ecdh);
- }
-
- private Test ecdhTest(Command setPriv, String desc, Result.ExpectedValue setExpect, Result.ExpectedValue ecdhExpect) {
- Test set = CommandTest.expect(setPriv, setExpect);
- Test ecdh = CommandTest.expect(new Command.ECDH(this.card, ECTesterApplet.KEYPAIR_LOCAL, ECTesterApplet.KEYPAIR_REMOTE, ECTesterApplet.EXPORT_TRUE, EC_Consts.TRANSFORMATION_NONE, EC_Consts.KeyAgreement_ALG_EC_SVDP_DH), ecdhExpect);
-
- return CompoundTest.any(Result.ExpectedValue.SUCCESS, desc, set, ecdh);
- }
-
- private EC_Params makeParams(BigInteger s) {
- return makeParams(ECUtil.toByteArray(s, s.bitLength()));
- }
-
- private EC_Params makeParams(byte[] s) {
- return new EC_Params(EC_Consts.PARAMETER_S, new byte[][]{s});
- }
-}
diff --git a/src/cz/crcs/ectester/reader/test/CardInvalidSuite.java b/src/cz/crcs/ectester/reader/test/CardInvalidSuite.java
deleted file mode 100644
index 5df379e..0000000
--- a/src/cz/crcs/ectester/reader/test/CardInvalidSuite.java
+++ /dev/null
@@ -1,72 +0,0 @@
-package cz.crcs.ectester.reader.test;
-
-import cz.crcs.ectester.applet.ECTesterApplet;
-import cz.crcs.ectester.applet.EC_Consts;
-import cz.crcs.ectester.common.ec.EC_Curve;
-import cz.crcs.ectester.common.ec.EC_Key;
-import cz.crcs.ectester.common.output.TestWriter;
-import cz.crcs.ectester.common.test.CompoundTest;
-import cz.crcs.ectester.common.test.Result;
-import cz.crcs.ectester.common.test.Test;
-import cz.crcs.ectester.common.util.CardUtil;
-import cz.crcs.ectester.data.EC_Store;
-import cz.crcs.ectester.reader.CardMngr;
-import cz.crcs.ectester.reader.ECTesterReader;
-import cz.crcs.ectester.reader.command.Command;
-
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-
-import static cz.crcs.ectester.common.test.Result.ExpectedValue;
-
-/**
- * @author Jan Jancar johny@neuromancer.sk
- */
-public class CardInvalidSuite extends CardTestSuite {
-
- public CardInvalidSuite(TestWriter writer, ECTesterReader.Config cfg, CardMngr cardManager) {
- super(writer, cfg, cardManager, "invalid", null, "The invalid curve suite tests whether the card rejects points outside of the curve during ECDH.");
- }
-
- @Override
- protected void runTests() throws Exception {
- /* Set original curves (secg/nist/brainpool). Generate local.
- * Try ECDH with invalid public keys of increasing order.
- */
- Map<String, EC_Key.Public> pubkeys = EC_Store.getInstance().getObjects(EC_Key.Public.class, "invalid");
- Map<EC_Curve, List<EC_Key.Public>> curveList = EC_Store.mapKeyToCurve(pubkeys.values());
- for (Map.Entry<EC_Curve, List<EC_Key.Public>> e : curveList.entrySet()) {
- EC_Curve curve = e.getKey();
- List<EC_Key.Public> keys = e.getValue();
-
- Test allocate = runTest(CommandTest.expect(new Command.Allocate(this.card, ECTesterApplet.KEYPAIR_BOTH, curve.getBits(), curve.getField()), ExpectedValue.SUCCESS));
- if (!allocate.ok()) {
- doTest(CompoundTest.all(Result.ExpectedValue.SUCCESS, "No support for " + curve.getId() + ".", allocate));
- continue;
- }
- Test set = CommandTest.expect(new Command.Set(this.card, ECTesterApplet.KEYPAIR_BOTH, EC_Consts.CURVE_external, curve.getParams(), curve.flatten()), ExpectedValue.SUCCESS);
- Test generate = CommandTest.expect(new Command.Generate(this.card, ECTesterApplet.KEYPAIR_LOCAL), ExpectedValue.SUCCESS);
-
- Test prepare = CompoundTest.all(ExpectedValue.SUCCESS, "Prepare and generate keypair on " + curve.getId() + ".", allocate, set, generate);
-
- List<Test> ecdhTests = new LinkedList<>();
- for (EC_Key.Public pub : keys) {
- Test setPub = CommandTest.expect(new Command.Set(this.card, ECTesterApplet.KEYPAIR_REMOTE, EC_Consts.CURVE_external, pub.getParams(), pub.flatten()), Result.ExpectedValue.FAILURE);
- Test ecdh = CommandTest.expect(new Command.ECDH(this.card, ECTesterApplet.KEYPAIR_REMOTE, ECTesterApplet.KEYPAIR_LOCAL, ECTesterApplet.EXPORT_FALSE, EC_Consts.TRANSFORMATION_NONE, EC_Consts.KeyAgreement_ALG_EC_SVDP_DH), Result.ExpectedValue.FAILURE);
- Test objectEcdh = CompoundTest.any(Result.ExpectedValue.SUCCESS, CardUtil.getKATypeString(EC_Consts.KeyAgreement_ALG_EC_SVDP_DH) + " test with invalid pubkey.", setPub, ecdh);
- Command ecdhCommand = new Command.ECDH_direct(this.card, ECTesterApplet.KEYPAIR_LOCAL, ECTesterApplet.EXPORT_FALSE, EC_Consts.TRANSFORMATION_NONE, EC_Consts.KeyAgreement_ALG_EC_SVDP_DH, pub.flatten());
- Test rawEcdh = CommandTest.expect(ecdhCommand, ExpectedValue.FAILURE, "Card correctly rejected point on invalid curve.", "Card incorrectly accepted point on invalid curve.");
- ecdhTests.add(CompoundTest.all(Result.ExpectedValue.SUCCESS, pub.getId() + " invalid key test.", objectEcdh, rawEcdh));
- }
- Test ecdh = CompoundTest.all(ExpectedValue.SUCCESS, "Perform ECDH with invalid public points.", ecdhTests.toArray(new Test[0]));
-
- if (cfg.cleanup) {
- Test cleanup = CommandTest.expect(new Command.Cleanup(this.card), ExpectedValue.ANY);
- doTest(CompoundTest.greedyAllTry(ExpectedValue.SUCCESS, "Invalid curve test of " + curve.getId() + ".", prepare, ecdh, cleanup));
- } else {
- doTest(CompoundTest.greedyAllTry(ExpectedValue.SUCCESS, "Invalid curve test of " + curve.getId() + ".", prepare, ecdh));
- }
- }
- }
-}
diff --git a/src/cz/crcs/ectester/reader/test/CardMiscSuite.java b/src/cz/crcs/ectester/reader/test/CardMiscSuite.java
deleted file mode 100644
index dd49708..0000000
--- a/src/cz/crcs/ectester/reader/test/CardMiscSuite.java
+++ /dev/null
@@ -1,77 +0,0 @@
-package cz.crcs.ectester.reader.test;
-
-import cz.crcs.ectester.applet.ECTesterApplet;
-import cz.crcs.ectester.applet.EC_Consts;
-import cz.crcs.ectester.common.ec.EC_Curve;
-import cz.crcs.ectester.common.output.TestWriter;
-import cz.crcs.ectester.common.test.CompoundTest;
-import cz.crcs.ectester.common.test.Result;
-import cz.crcs.ectester.common.test.Test;
-import cz.crcs.ectester.data.EC_Store;
-import cz.crcs.ectester.reader.CardMngr;
-import cz.crcs.ectester.reader.ECTesterReader;
-import cz.crcs.ectester.reader.command.Command;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-import java.util.Map;
-
-/**
- * @author Jan Jancar johny@neuromancer.sk
- */
-public class CardMiscSuite extends CardTestSuite {
-
- public CardMiscSuite(TestWriter writer, ECTesterReader.Config cfg, CardMngr cardManager) {
- super(writer, cfg, cardManager, "miscellaneous", new String[]{"preset", "random"}, "Some miscellaneous tests, tries ECDH and ECDSA over supersingular curves, anomalous curves,",
- "Barreto-Naehrig curves with small embedding degree and CM discriminant, MNT curves,",
- "some Montgomery curves transformed to short Weierstrass form and Curve25519 transformed to short Weierstrass form.");
- }
-
- @Override
- protected void runTests() throws Exception {
- Map<String, EC_Curve> anCurves = EC_Store.getInstance().getObjects(EC_Curve.class, "anomalous");
- Map<String, EC_Curve> ssCurves = EC_Store.getInstance().getObjects(EC_Curve.class, "supersingular");
- Map<String, EC_Curve> bnCurves = EC_Store.getInstance().getObjects(EC_Curve.class, "Barreto-Naehrig");
- Map<String, EC_Curve> mntCurves = EC_Store.getInstance().getObjects(EC_Curve.class, "MNT");
- List<EC_Curve> mCurves = new ArrayList<>();
- mCurves.add(EC_Store.getInstance().getObject(EC_Curve.class, "other", "M-221"));
- mCurves.add(EC_Store.getInstance().getObject(EC_Curve.class, "other", "M-383"));
- mCurves.add(EC_Store.getInstance().getObject(EC_Curve.class, "other", "M-511"));
- EC_Curve curve25519 = EC_Store.getInstance().getObject(EC_Curve.class, "other", "Curve25519");
-
- testCurves(anCurves.values(), "anomalous", Result.ExpectedValue.FAILURE);
- testCurves(ssCurves.values(), "supersingular", Result.ExpectedValue.FAILURE);
- testCurves(bnCurves.values(), "Barreto-Naehrig", Result.ExpectedValue.SUCCESS);
- testCurves(mntCurves.values(), "MNT", Result.ExpectedValue.SUCCESS);
- testCurves(mCurves, "Montgomery", Result.ExpectedValue.SUCCESS);
- testCurve(curve25519, "Montgomery", Result.ExpectedValue.SUCCESS);
- }
-
- private void testCurve(EC_Curve curve, String catName, Result.ExpectedValue expected) {
- Test allocateFirst = runTest(CommandTest.expect(new Command.Allocate(this.card, ECTesterApplet.KEYPAIR_BOTH, curve.getBits(), curve.getField()), Result.ExpectedValue.SUCCESS));
- if (!allocateFirst.ok()) {
- doTest(CompoundTest.all(Result.ExpectedValue.SUCCESS, "No support for " + curve.getBits() + "b " + catName + " curve: " + curve.getId() + ".", allocateFirst));
- return;
- }
-
- Test set = CommandTest.expect(new Command.Set(this.card, ECTesterApplet.KEYPAIR_BOTH, EC_Consts.CURVE_external, curve.getParams(), curve.flatten()), Result.ExpectedValue.SUCCESS);
- Test generate = setupKeypairs(curve, Result.ExpectedValue.ANY, ECTesterApplet.KEYPAIR_BOTH);
- Test ka = CommandTest.expect(new Command.ECDH(this.card, ECTesterApplet.KEYPAIR_REMOTE, ECTesterApplet.KEYPAIR_LOCAL, ECTesterApplet.EXPORT_FALSE, EC_Consts.TRANSFORMATION_NONE, EC_Consts.KeyAgreement_ALG_EC_SVDP_DH), expected);
- Test sig = CommandTest.expect(new Command.ECDSA_sign(this.card, ECTesterApplet.KEYPAIR_LOCAL, EC_Consts.Signature_ALG_ECDSA_SHA, ECTesterApplet.EXPORT_FALSE, null), expected);
- Test perform = CompoundTest.all(Result.ExpectedValue.SUCCESS, "Perform ECDH and ECDSA.", ka, sig);
-
- if (cfg.cleanup) {
- Test cleanup = CommandTest.expect(new Command.Cleanup(this.card), Result.ExpectedValue.ANY);
- doTest(CompoundTest.greedyAll(Result.ExpectedValue.SUCCESS, "Tests over " + curve.getBits() + "b " + catName + " curve: " + curve.getId() + ".", allocateFirst, set, generate, perform, cleanup));
- } else {
- doTest(CompoundTest.greedyAll(Result.ExpectedValue.SUCCESS, "Tests over " + curve.getBits() + "b " + catName + " curve: " + curve.getId() + ".", allocateFirst, set, generate, perform));
- }
- }
-
- private void testCurves(Collection<EC_Curve> curves, String catName, Result.ExpectedValue expected) {
- for (EC_Curve curve : curves) {
- testCurve(curve, catName, expected);
- }
- }
-}
diff --git a/src/cz/crcs/ectester/reader/test/CardSignatureSuite.java b/src/cz/crcs/ectester/reader/test/CardSignatureSuite.java
deleted file mode 100644
index 0e4ca8e..0000000
--- a/src/cz/crcs/ectester/reader/test/CardSignatureSuite.java
+++ /dev/null
@@ -1,68 +0,0 @@
-package cz.crcs.ectester.reader.test;
-
-import cz.crcs.ectester.applet.ECTesterApplet;
-import cz.crcs.ectester.applet.EC_Consts;
-import cz.crcs.ectester.common.ec.EC_Curve;
-import cz.crcs.ectester.common.ec.EC_Key;
-import cz.crcs.ectester.common.ec.EC_SigResult;
-import cz.crcs.ectester.common.output.TestWriter;
-import cz.crcs.ectester.common.test.CompoundTest;
-import cz.crcs.ectester.common.test.Result;
-import cz.crcs.ectester.common.test.Test;
-import cz.crcs.ectester.data.EC_Store;
-import cz.crcs.ectester.reader.CardMngr;
-import cz.crcs.ectester.reader.ECTesterReader;
-import cz.crcs.ectester.reader.command.Command;
-
-import java.util.List;
-import java.util.Map;
-
-/**
- * @author Jan Jancar johny@neuromancer.sk
- */
-public class CardSignatureSuite extends CardTestSuite {
- public CardSignatureSuite(TestWriter writer, ECTesterReader.Config cfg, CardMngr cardManager) {
- super(writer, cfg, cardManager, "signature", null, "The signature test suite tests verifying various malformed and well-formed but invalid ECDSA signatures.");
- }
-
- @Override
- protected void runTests() throws Exception {
- Map<String, EC_SigResult> results = EC_Store.getInstance().getObjects(EC_SigResult.class, "wrong");
- Map<String, List<EC_SigResult>> groups = EC_Store.mapToPrefix(results.values());
-
- List<EC_SigResult> nok = groups.entrySet().stream().filter((e) -> e.getKey().equals("nok")).findFirst().get().getValue();
-
- byte[] data = "Some stuff that is not the actual data".getBytes();
- for (EC_SigResult sig : nok) {
- ecdsaTest(sig, Result.ExpectedValue.FAILURE, data);
- }
-
- List<EC_SigResult> ok = groups.entrySet().stream().filter((e) -> e.getKey().equals("ok")).findFirst().get().getValue();
- for (EC_SigResult sig : ok) {
- ecdsaTest(sig, Result.ExpectedValue.SUCCESS, null);
- }
- }
-
- private void ecdsaTest(EC_SigResult sig, Result.ExpectedValue expected, byte[] defaultData) {
- EC_Key.Public pubkey = EC_Store.getInstance().getObject(EC_Key.Public.class, sig.getVerifyKey());
-
- byte[] data = sig.getSigData();
- if (data == null) {
- data = defaultData;
- }
-
- EC_Curve curve = EC_Store.getInstance().getObject(EC_Curve.class, sig.getCurve());
- Test allocate = CommandTest.expect(new Command.Allocate(this.card, ECTesterApplet.KEYPAIR_LOCAL, curve.getBits(), curve.getField()), Result.ExpectedValue.SUCCESS);
- Test set = CommandTest.expect(new Command.Set(this.card, ECTesterApplet.KEYPAIR_LOCAL, EC_Consts.CURVE_external, curve.getParams(), curve.flatten()), Result.ExpectedValue.SUCCESS);
- Test setVerifyKey = CommandTest.expect(new Command.Set(this.card, ECTesterApplet.KEYPAIR_LOCAL, EC_Consts.CURVE_external, pubkey.getParams(), pubkey.flatten()), Result.ExpectedValue.SUCCESS);
- Test ecdsaVerify = CommandTest.expect(new Command.ECDSA_verify(this.card, ECTesterApplet.KEYPAIR_LOCAL, sig.getJavaCardSig(), data, sig.getData(0)), expected);
-
- if (cfg.cleanup) {
- Test cleanup = CommandTest.expect(new Command.Cleanup(this.card), Result.ExpectedValue.ANY);
- doTest(CompoundTest.all(Result.ExpectedValue.SUCCESS, "ECDSA test of " + sig.getId() + ".", allocate, set, setVerifyKey, ecdsaVerify, cleanup));
- } else {
- doTest(CompoundTest.all(Result.ExpectedValue.SUCCESS, "ECDSA test of " + sig.getId() + ".", allocate, set, setVerifyKey, ecdsaVerify));
- }
-
- }
-}
diff --git a/src/cz/crcs/ectester/reader/test/CardTestSuite.java b/src/cz/crcs/ectester/reader/test/CardTestSuite.java
deleted file mode 100644
index fc60ae5..0000000
--- a/src/cz/crcs/ectester/reader/test/CardTestSuite.java
+++ /dev/null
@@ -1,94 +0,0 @@
-package cz.crcs.ectester.reader.test;
-
-import cz.crcs.ectester.applet.ECTesterApplet;
-import cz.crcs.ectester.applet.EC_Consts;
-import cz.crcs.ectester.common.ec.EC_Curve;
-import cz.crcs.ectester.common.ec.EC_Params;
-import cz.crcs.ectester.common.output.TestWriter;
-import cz.crcs.ectester.common.test.CompoundTest;
-import cz.crcs.ectester.common.test.Result;
-import cz.crcs.ectester.common.test.Test;
-import cz.crcs.ectester.common.test.TestSuite;
-import cz.crcs.ectester.common.util.ECUtil;
-import cz.crcs.ectester.reader.CardMngr;
-import cz.crcs.ectester.reader.ECTesterReader;
-import cz.crcs.ectester.reader.command.Command;
-
-import java.util.Arrays;
-
-/**
- * @author Jan Jancar johny@neuromancer.sk
- */
-public abstract class CardTestSuite extends TestSuite {
- ECTesterReader.Config cfg;
- CardMngr card;
- String[] options;
-
- CardTestSuite(TestWriter writer, ECTesterReader.Config cfg, CardMngr cardManager, String name, String[] options, String... description) {
- super(writer, name, description);
- this.card = cardManager;
- this.cfg = cfg;
- this.options = options;
- }
-
- public CardMngr getCard() {
- return card;
- }
-
- public ECTesterReader.Config getCfg() {
- return cfg;
- }
-
- public String[] getOptions() {
- if (options != null) {
- return options.clone();
- } else {
- return options;
- }
- }
-
- public Test setupKeypairs(EC_Curve curve, Result.ExpectedValue expected, byte keyPair) {
- if ((Arrays.asList(options).contains("preset") && cfg.testOptions.contains("preset")) || (Arrays.asList(options).contains("random") && cfg.testOptions.contains("random"))) {
- Test setLocal = null;
- if ((keyPair & ECTesterApplet.KEYPAIR_LOCAL) != 0) {
- EC_Params priv;
- if (cfg.testOptions.contains("preset")) {
- priv = ECUtil.fixedRandomKey(curve);
- } else {
- priv = ECUtil.fullRandomKey(curve);
- }
- setLocal = CommandTest.expect(new Command.Set(this.card, ECTesterApplet.KEYPAIR_LOCAL, EC_Consts.CURVE_external, priv.getParams(), priv.flatten()), expected);
- }
- Test setRemote = null;
- if ((keyPair & ECTesterApplet.KEYPAIR_REMOTE) != 0) {
- EC_Params pub;
- if (cfg.testOptions.contains("preset")) {
- pub = ECUtil.fixedRandomPoint(curve);
- } else {
- pub = ECUtil.fullRandomPoint(curve);
- }
- if (pub == null) {
- setRemote = CommandTest.expect(new Command.Generate(this.card, ECTesterApplet.KEYPAIR_REMOTE), expected);
- } else {
- setRemote = CommandTest.expect(new Command.Set(this.card, ECTesterApplet.KEYPAIR_REMOTE, EC_Consts.CURVE_external, pub.getParams(), pub.flatten()), expected);
- }
- }
-
- if (keyPair == ECTesterApplet.KEYPAIR_LOCAL) {
- return setLocal;
- } else if (keyPair == ECTesterApplet.KEYPAIR_REMOTE) {
- return setRemote;
- } else {
- String desc;
- if (cfg.testOptions.contains("preset")) {
- desc = "Set semi-random parameters.";
- } else {
- desc = "Set fully-random parameters.";
- }
- return CompoundTest.all(expected, desc, setLocal, setRemote);
- }
- } else {
- return CommandTest.expect(new Command.Generate(this.card, keyPair), expected);
- }
- }
-}
diff --git a/src/cz/crcs/ectester/reader/test/CardTestVectorSuite.java b/src/cz/crcs/ectester/reader/test/CardTestVectorSuite.java
deleted file mode 100644
index d143852..0000000
--- a/src/cz/crcs/ectester/reader/test/CardTestVectorSuite.java
+++ /dev/null
@@ -1,235 +0,0 @@
-package cz.crcs.ectester.reader.test;
-
-import cz.crcs.ectester.applet.ECTesterApplet;
-import cz.crcs.ectester.applet.EC_Consts;
-import cz.crcs.ectester.common.ec.*;
-import cz.crcs.ectester.common.output.TestWriter;
-import cz.crcs.ectester.common.test.CompoundTest;
-import cz.crcs.ectester.common.test.Result;
-import cz.crcs.ectester.common.test.Test;
-import cz.crcs.ectester.common.test.TestCallback;
-import cz.crcs.ectester.common.util.ByteUtil;
-import cz.crcs.ectester.common.util.CardUtil;
-import cz.crcs.ectester.common.util.ECUtil;
-import cz.crcs.ectester.data.EC_Store;
-import cz.crcs.ectester.reader.CardMngr;
-import cz.crcs.ectester.reader.ECTesterReader;
-import cz.crcs.ectester.reader.command.Command;
-import cz.crcs.ectester.reader.response.Response;
-import javacard.security.KeyPair;
-
-import javax.crypto.KeyAgreement;
-import java.io.IOException;
-import java.math.BigInteger;
-import java.security.*;
-import java.security.spec.ECParameterSpec;
-import java.security.spec.ECPrivateKeySpec;
-import java.security.spec.ECPublicKeySpec;
-import java.security.spec.InvalidKeySpecException;
-import java.util.ArrayList;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.function.BiFunction;
-import java.util.stream.Collectors;
-
-import static cz.crcs.ectester.common.test.Result.ExpectedValue;
-import static cz.crcs.ectester.common.test.Result.Value;
-
-/**
- * @author Jan Jancar johny@neuromancer.sk
- */
-public class CardTestVectorSuite extends CardTestSuite {
-
- public CardTestVectorSuite(TestWriter writer, ECTesterReader.Config cfg, CardMngr cardManager) {
- super(writer, cfg, cardManager, "test-vectors", null, "The test-vectors suite contains a collection of test vectors which test basic ECDH correctness.");
- }
-
- @Override
- protected void runTests() throws Exception {
- /* 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 = EC_Store.getInstance().getObjects(EC_KAResult.class, "test");
- for (EC_KAResult result : results.values()) {
- EC_Curve curve = EC_Store.getInstance().getObject(EC_Curve.class, result.getCurve());
- EC_Params onekey = EC_Store.getInstance().getObject(EC_Keypair.class, result.getOneKey());
- if (onekey == null) {
- onekey = EC_Store.getInstance().getObject(EC_Key.Private.class, result.getOneKey());
- }
- EC_Params otherkey = EC_Store.getInstance().getObject(EC_Keypair.class, result.getOtherKey());
- if (otherkey == null) {
- otherkey = EC_Store.getInstance().getObject(EC_Key.Public.class, result.getOtherKey());
- }
- if (onekey == null || otherkey == null) {
- throw new IOException("Test vector keys couldn't be located.");
- }
- List<Test> testVector = new LinkedList<>();
- Test allocate = runTest(CommandTest.expect(new Command.Allocate(this.card, ECTesterApplet.KEYPAIR_BOTH, curve.getBits(), curve.getField()), ExpectedValue.SUCCESS));
- if (!allocate.ok()) {
- doTest(CompoundTest.all(ExpectedValue.SUCCESS, "No support for " + curve.getBits() + "b " + CardUtil.getKeyTypeString(curve.getField()) + ".", allocate));
- continue;
- }
-
- testVector.add(allocate);
- testVector.add(CommandTest.expect(new Command.Set(this.card, ECTesterApplet.KEYPAIR_BOTH, EC_Consts.CURVE_external, curve.getParams(), curve.flatten()), ExpectedValue.SUCCESS));
- testVector.add(CommandTest.expect(new Command.Set(this.card, ECTesterApplet.KEYPAIR_LOCAL, EC_Consts.CURVE_external, EC_Consts.PARAMETER_S, onekey.flatten(EC_Consts.PARAMETER_S)), ExpectedValue.SUCCESS));
- testVector.add(CommandTest.expect(new Command.Set(this.card, ECTesterApplet.KEYPAIR_REMOTE, EC_Consts.CURVE_external, EC_Consts.PARAMETER_W, otherkey.flatten(EC_Consts.PARAMETER_W)), ExpectedValue.SUCCESS));
- testVector.add(CommandTest.function(new Command.ECDH(this.card, ECTesterApplet.KEYPAIR_REMOTE, ECTesterApplet.KEYPAIR_LOCAL, ECTesterApplet.EXPORT_TRUE, EC_Consts.TRANSFORMATION_NONE, result.getJavaCardKA()), new TestCallback<CommandTestable>() {
- @Override
- public Result apply(CommandTestable testable) {
- Response.ECDH dh = (Response.ECDH) testable.getResponse();
- if (!dh.successful())
- return new Result(Value.FAILURE, "ECDH was unsuccessful.");
- if (!dh.hasSecret())
- return new Result(Value.FAILURE, "ECDH response did not contain the derived secret.");
- if (!ByteUtil.compareBytes(dh.getSecret(), 0, result.getData(0), 0, dh.secretLength())) {
- int firstDiff = ByteUtil.diffBytes(dh.getSecret(), 0, result.getData(0), 0, dh.secretLength());
- return new Result(Value.FAILURE, "ECDH derived secret does not match the test-vector, first difference was at byte " + firstDiff + ".");
- }
- return new Result(Value.SUCCESS);
- }
- }));
- if (cfg.cleanup) {
- testVector.add(CommandTest.expect(new Command.Cleanup(this.card), ExpectedValue.ANY));
- }
- doTest(CompoundTest.greedyAll(ExpectedValue.SUCCESS, "Test vector " + result.getId() + ".", testVector.toArray(new Test[0])));
- }
-
- KeyAgreement ka;
- Signature sig;
- KeyFactory kf;
- MessageDigest md;
- try {
- ka = KeyAgreement.getInstance("ECDH", "BC");
- sig = Signature.getInstance("ECDSAwithSHA1", "BC");
- kf = KeyFactory.getInstance("ECDH", "BC");
- md = MessageDigest.getInstance("SHA1", "BC");
- } catch (NoSuchAlgorithmException | NoSuchProviderException ex) {
- return;
- }
-
- List<EC_Curve> testCurves = new ArrayList<>();
- testCurves.addAll(EC_Store.getInstance().getObjects(EC_Curve.class, "secg").values().stream().filter((curve) -> curve.getField() == KeyPair.ALG_EC_FP).collect(Collectors.toList()));
- testCurves.addAll(EC_Store.getInstance().getObjects(EC_Curve.class, "brainpool").values().stream().filter((curve) -> curve.getField() == KeyPair.ALG_EC_FP).collect(Collectors.toList()));
- for (EC_Curve curve : testCurves) {
- List<Test> testVector = new LinkedList<>();
- Test allocate = runTest(CommandTest.expect(new Command.Allocate(this.card, ECTesterApplet.KEYPAIR_BOTH, curve.getBits(), curve.getField()), ExpectedValue.SUCCESS));
- if (!allocate.ok()) {
- doTest(CompoundTest.all(ExpectedValue.SUCCESS, "No support for " + curve.getBits() + "b " + CardUtil.getKeyTypeString(curve.getField()) + ".", allocate));
- continue;
- }
- testVector.add(allocate);
- testVector.add(CommandTest.expect(new Command.Set(this.card, ECTesterApplet.KEYPAIR_BOTH, EC_Consts.CURVE_external, curve.getParams(), curve.flatten()), ExpectedValue.SUCCESS));
- testVector.add(CommandTest.expect(new Command.Generate(this.card, ECTesterApplet.KEYPAIR_BOTH), ExpectedValue.SUCCESS));
- CommandTest exportLocal = CommandTest.expect(new Command.Export(this.card, ECTesterApplet.KEYPAIR_LOCAL, EC_Consts.KEY_PUBLIC, EC_Consts.PARAMETER_W), ExpectedValue.ANY);
- CommandTest exportRemote = CommandTest.expect(new Command.Export(this.card, ECTesterApplet.KEYPAIR_REMOTE, EC_Consts.KEY_PRIVATE, EC_Consts.PARAMETER_S), ExpectedValue.ANY);
- testVector.add(exportLocal);
- testVector.add(exportRemote);
- BiFunction<Response.Export, Response.Export, Key[]> getKeys = (localData, remoteData) -> {
- byte[] pkey = localData.getParameter(ECTesterApplet.KEYPAIR_LOCAL, EC_Consts.PARAMETER_W);
- byte[] skey = remoteData.getParameter(ECTesterApplet.KEYPAIR_REMOTE, EC_Consts.PARAMETER_S);
- ECParameterSpec spec = curve.toSpec();
- ECPrivateKeySpec privKeySpec = new ECPrivateKeySpec(new BigInteger(1, skey), spec);
- ECPublicKeySpec pubKeySpec = new ECPublicKeySpec(ECUtil.fromX962(pkey, curve.toCurve()), spec);
- PrivateKey privKey;
- PublicKey pubKey;
- try {
- privKey = kf.generatePrivate(privKeySpec);
- pubKey = kf.generatePublic(pubKeySpec);
- } catch (InvalidKeySpecException ex) {
- return null;
- }
- return new Key[]{privKey, pubKey};
- };
- TestCallback<CommandTestable> kaCallback = new TestCallback<CommandTestable>() {
- @Override
- public Result apply(CommandTestable testable) {
- Response.ECDH ecdhData = (Response.ECDH) testable.getResponse();
- if (!ecdhData.successful())
- return new Result(Value.FAILURE, "ECDH was unsuccessful.");
- if (!ecdhData.hasSecret()) {
- return new Result(Value.FAILURE, "ECDH response did not contain the derived secret.");
- }
- byte[] secret = ecdhData.getSecret();
- Response.Export localData = (Response.Export) exportLocal.getResponse();
- Response.Export remoteData = (Response.Export) exportRemote.getResponse();
- Key[] keys = getKeys.apply(localData, remoteData);
- if (keys == null) {
- return new Result(Value.SUCCESS, "Result could not be verified. keyData unavailable.");
- }
- PrivateKey privKey = (PrivateKey) keys[0];
- PublicKey pubKey = (PublicKey) keys[1];
- try {
- ka.init(privKey);
- ka.doPhase(pubKey, true);
- byte[] derived = ka.generateSecret();
- int fieldSize = (curve.getBits() + 7) / 8;
- if (derived.length < fieldSize) {
- byte[] padded = new byte[fieldSize];
- System.arraycopy(derived, 0, padded, fieldSize - derived.length, derived.length);
- derived = padded;
- }
- if (ecdhData.getType() == EC_Consts.KeyAgreement_ALG_EC_SVDP_DH || ecdhData.getType() == EC_Consts.KeyAgreement_ALG_EC_SVDP_DHC) {
- derived = md.digest(derived);
- }
- if (secret.length != derived.length) {
- if (secret.length < derived.length) {
- return new Result(Value.FAILURE, String.format("Derived secret was shorter than expected: %d vs %d (expected).", secret.length, derived.length));
- } else {
- return new Result(Value.FAILURE, String.format("Derived secret was longer than expected: %d vs %d (expected).", secret.length, derived.length));
- }
- }
- int diff = ByteUtil.diffBytes(derived, 0, secret, 0, secret.length);
- if (diff == secret.length) {
- return new Result(Value.SUCCESS, "Derived secret matched expected value.");
- } else {
- return new Result(Value.FAILURE, "Derived secret does not match expected value, first difference was at byte " + diff + ".");
- }
- } catch (InvalidKeyException ex) {
- return new Result(Value.SUCCESS, "Result could not be verified. " + ex.getMessage());
- }
- }
- };
- Test ecdhTest = CommandTest.function(new Command.ECDH(this.card, ECTesterApplet.KEYPAIR_LOCAL, ECTesterApplet.KEYPAIR_REMOTE, ECTesterApplet.EXPORT_TRUE, EC_Consts.TRANSFORMATION_NONE, EC_Consts.KeyAgreement_ALG_EC_SVDP_DH), kaCallback);
- Test ecdhRawTest = CommandTest.function(new Command.ECDH(this.card, ECTesterApplet.KEYPAIR_LOCAL, ECTesterApplet.KEYPAIR_REMOTE, ECTesterApplet.EXPORT_TRUE, EC_Consts.TRANSFORMATION_NONE, EC_Consts.KeyAgreement_ALG_EC_SVDP_DH_PLAIN), kaCallback);
- byte[] data = new byte[32];
- TestCallback<CommandTestable> sigCallback = new TestCallback<CommandTestable>() {
- @Override
- public Result apply(CommandTestable testable) {
- Response.ECDSA ecdsaData = (Response.ECDSA) testable.getResponse();
- if (!ecdsaData.successful())
- return new Result(Value.FAILURE, "ECDSA was unsuccessful.");
- if (!ecdsaData.hasSignature()) {
- return new Result(Value.FAILURE, "ECDSA response did not contain the signature.");
- }
- byte[] signature = ecdsaData.getSignature();
- Response.Export localData = (Response.Export) exportLocal.getResponse();
- Response.Export remoteData = (Response.Export) exportRemote.getResponse();
- Key[] keys = getKeys.apply(localData, remoteData);
- if (keys == null) {
- return new Result(Value.SUCCESS, "Result could not be verified. keyData unavailable.");
- }
- PublicKey pubKey = (PublicKey) keys[1];
- try {
- sig.initVerify(pubKey);
- sig.update(data);
- if (sig.verify(signature)) {
- return new Result(Value.SUCCESS, "Signature verified.");
- } else {
- return new Result(Value.FAILURE, "Signature failed to verify.");
- }
- } catch (InvalidKeyException | SignatureException ex) {
- return new Result(Value.SUCCESS, "Result could not be verified. " + ex.getMessage());
- }
- }
- };
- Test ecdsaTest = CommandTest.function(new Command.ECDSA_sign(this.card, ECTesterApplet.KEYPAIR_LOCAL, EC_Consts.Signature_ALG_ECDSA_SHA, ECTesterApplet.EXPORT_TRUE, data), sigCallback);
- testVector.add(CompoundTest.all(ExpectedValue.SUCCESS, "Test.", ecdhTest, ecdhRawTest, ecdsaTest));
- if (cfg.cleanup) {
- testVector.add(CommandTest.expect(new Command.Cleanup(this.card), ExpectedValue.ANY));
- }
- doTest(CompoundTest.greedyAll(ExpectedValue.SUCCESS, "Validation test on " + curve.getId() + ".", testVector.toArray(new Test[0])));
- }
- }
-}
diff --git a/src/cz/crcs/ectester/reader/test/CardTwistSuite.java b/src/cz/crcs/ectester/reader/test/CardTwistSuite.java
deleted file mode 100644
index a6bca6c..0000000
--- a/src/cz/crcs/ectester/reader/test/CardTwistSuite.java
+++ /dev/null
@@ -1,67 +0,0 @@
-package cz.crcs.ectester.reader.test;
-
-import cz.crcs.ectester.applet.ECTesterApplet;
-import cz.crcs.ectester.applet.EC_Consts;
-import cz.crcs.ectester.common.ec.EC_Curve;
-import cz.crcs.ectester.common.ec.EC_Key;
-import cz.crcs.ectester.common.output.TestWriter;
-import cz.crcs.ectester.common.test.CompoundTest;
-import cz.crcs.ectester.common.test.Result;
-import cz.crcs.ectester.common.test.Test;
-import cz.crcs.ectester.common.util.CardUtil;
-import cz.crcs.ectester.data.EC_Store;
-import cz.crcs.ectester.reader.CardMngr;
-import cz.crcs.ectester.reader.ECTesterReader;
-import cz.crcs.ectester.reader.command.Command;
-
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-
-/**
- * @author Jan Jancar johny@neuromancer.sk
- */
-public class CardTwistSuite extends CardTestSuite {
- public CardTwistSuite(TestWriter writer, ECTesterReader.Config cfg, CardMngr cardManager) {
- super(writer, cfg, cardManager, "twist", null, "The twist test suite tests whether the card correctly rejects points on the quadratic twist of the curve during ECDH.");
- }
-
- @Override
- protected void runTests() throws Exception {
- Map<String, EC_Key.Public> pubkeys = EC_Store.getInstance().getObjects(EC_Key.Public.class, "twist");
- Map<EC_Curve, List<EC_Key.Public>> curveList = EC_Store.mapKeyToCurve(pubkeys.values());
- for (Map.Entry<EC_Curve, List<EC_Key.Public>> e : curveList.entrySet()) {
- EC_Curve curve = e.getKey();
- List<EC_Key.Public> keys = e.getValue();
-
- Test allocate = runTest(CommandTest.expect(new Command.Allocate(this.card, ECTesterApplet.KEYPAIR_BOTH, curve.getBits(), curve.getField()), Result.ExpectedValue.SUCCESS));
- if (!allocate.ok()) {
- doTest(CompoundTest.all(Result.ExpectedValue.SUCCESS, "No support for " + curve.getId() + ".", allocate));
- continue;
- }
- Test set = CommandTest.expect(new Command.Set(this.card, ECTesterApplet.KEYPAIR_BOTH, EC_Consts.CURVE_external, curve.getParams(), curve.flatten()), Result.ExpectedValue.SUCCESS);
- Test generate = CommandTest.expect(new Command.Generate(this.card, ECTesterApplet.KEYPAIR_LOCAL), Result.ExpectedValue.SUCCESS);
-
- Test prepare = CompoundTest.all(Result.ExpectedValue.SUCCESS, "Prepare and generate keypair on " + curve.getId() + ".", allocate, set, generate);
-
- List<Test> ecdhTests = new LinkedList<>();
- for (EC_Key.Public pub : keys) {
- Test setPub = CommandTest.expect(new Command.Set(this.card, ECTesterApplet.KEYPAIR_REMOTE, EC_Consts.CURVE_external, pub.getParams(), pub.flatten()), Result.ExpectedValue.FAILURE);
- Test ecdh = CommandTest.expect(new Command.ECDH(this.card, ECTesterApplet.KEYPAIR_REMOTE, ECTesterApplet.KEYPAIR_LOCAL, ECTesterApplet.EXPORT_FALSE, EC_Consts.TRANSFORMATION_NONE, EC_Consts.KeyAgreement_ALG_EC_SVDP_DH), Result.ExpectedValue.FAILURE, "Card correctly rejected point on twist.", "Card incorrectly accepted point on twist.");
- Test objectEcdh = CompoundTest.any(Result.ExpectedValue.SUCCESS, CardUtil.getKATypeString(EC_Consts.KeyAgreement_ALG_EC_SVDP_DH) + " test with twist pubkey.", setPub, ecdh);
- Command ecdhCommand = new Command.ECDH_direct(this.card, ECTesterApplet.KEYPAIR_LOCAL, ECTesterApplet.EXPORT_FALSE, EC_Consts.TRANSFORMATION_NONE, EC_Consts.KeyAgreement_ALG_EC_SVDP_DH, pub.flatten());
- Test rawEcdh = CommandTest.expect(ecdhCommand, Result.ExpectedValue.FAILURE, "Card correctly rejected point on twist.", "Card incorrectly accepted point on twist.");
- ecdhTests.add(CompoundTest.all(Result.ExpectedValue.SUCCESS, pub.getId() + " twist key test.", objectEcdh, rawEcdh));
- }
- Test ecdh = CompoundTest.all(Result.ExpectedValue.SUCCESS, "Perform ECDH with public points on twist.", ecdhTests.toArray(new Test[0]));
-
- Test tests = CompoundTest.all(Result.ExpectedValue.SUCCESS, "Do tests.", ecdh);
- if (cfg.cleanup) {
- Test cleanup = CommandTest.expect(new Command.Cleanup(this.card), Result.ExpectedValue.ANY);
- doTest(CompoundTest.greedyAllTry(Result.ExpectedValue.SUCCESS, "Twist test of " + curve.getId() + ".", prepare, tests, cleanup));
- } else {
- doTest(CompoundTest.greedyAllTry(Result.ExpectedValue.SUCCESS, "Twist test of " + curve.getId() + ".", prepare, tests));
- }
- }
- }
-}
diff --git a/src/cz/crcs/ectester/reader/test/CardWrongSuite.java b/src/cz/crcs/ectester/reader/test/CardWrongSuite.java
deleted file mode 100644
index 13a3f8b..0000000
--- a/src/cz/crcs/ectester/reader/test/CardWrongSuite.java
+++ /dev/null
@@ -1,232 +0,0 @@
-package cz.crcs.ectester.reader.test;
-
-import cz.crcs.ectester.applet.ECTesterApplet;
-import cz.crcs.ectester.applet.EC_Consts;
-import cz.crcs.ectester.common.ec.EC_Curve;
-import cz.crcs.ectester.common.ec.EC_Params;
-import cz.crcs.ectester.common.output.TestWriter;
-import cz.crcs.ectester.common.test.CompoundTest;
-import cz.crcs.ectester.common.test.Result;
-import cz.crcs.ectester.common.test.Test;
-import cz.crcs.ectester.common.util.ByteUtil;
-import cz.crcs.ectester.common.util.CardUtil;
-import cz.crcs.ectester.common.util.ECUtil;
-import cz.crcs.ectester.data.EC_Store;
-import cz.crcs.ectester.reader.CardMngr;
-import cz.crcs.ectester.reader.ECTesterReader;
-import cz.crcs.ectester.reader.command.Command;
-import javacard.security.KeyPair;
-
-import java.math.BigInteger;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.Random;
-
-import static cz.crcs.ectester.common.test.Result.ExpectedValue;
-
-/**
- * @author Jan Jancar johny@neuromancer.sk
- */
-public class CardWrongSuite extends CardTestSuite {
-
- public CardWrongSuite(TestWriter writer, ECTesterReader.Config cfg, CardMngr cardManager) {
- super(writer, cfg, cardManager, "wrong", new String[]{"preset", "random"}, "The wrong curve suite tests whether the card rejects domain parameters which are not curves.");
- }
-
- @Override
- protected void runTests() throws Exception {
- /* Just do the default run on the wrong curves.
- * These should generally fail, the curves aren't curves.
- */
- Map<String, EC_Curve> curves = EC_Store.getInstance().getObjects(EC_Curve.class, "wrong");
- for (Map.Entry<String, EC_Curve> e : curves.entrySet()) {
- EC_Curve curve = e.getValue();
- List<Test> tests = new LinkedList<>();
- Test key = runTest(CommandTest.expect(new Command.Allocate(this.card, ECTesterApplet.KEYPAIR_BOTH, curve.getBits(), curve.getField()), ExpectedValue.SUCCESS));
- if (!key.ok()) {
- doTest(CompoundTest.all(ExpectedValue.FAILURE, "No support for " + curve.getBits() + "b " + CardUtil.getKeyTypeString(curve.getField()), key));
- continue;
- }
- tests.add(key);
- Test set = runTest(CommandTest.expect(new Command.Set(this.card, ECTesterApplet.KEYPAIR_BOTH, EC_Consts.CURVE_external, curve.getParams(), curve.flatten()), ExpectedValue.FAILURE));
- Test generate = runTest(setupKeypairs(curve, ExpectedValue.SUCCESS, ECTesterApplet.KEYPAIR_BOTH));
- Test setup = runTest(CompoundTest.any(ExpectedValue.SUCCESS, "Set wrong curve and generate keypairs.", set, generate));
- tests.add(setup);
-
- for (byte kaType : EC_Consts.KA_TYPES) {
- Test allocate = runTest(CommandTest.expect(new Command.AllocateKeyAgreement(this.card, kaType), ExpectedValue.SUCCESS));
- if (allocate.ok()) {
- Test ka = runTest(CommandTest.expect(new Command.ECDH(this.card, ECTesterApplet.KEYPAIR_REMOTE, ECTesterApplet.KEYPAIR_LOCAL, ECTesterApplet.EXPORT_FALSE, EC_Consts.TRANSFORMATION_NONE, kaType), ExpectedValue.FAILURE));
- Test kaTest = runTest(CompoundTest.all(ExpectedValue.SUCCESS, "Allocate and perform KA.", allocate, ka));
- tests.add(kaTest);
- }
- }
- doTest(CompoundTest.function((tsts) -> {
- for (int i = 0; i < tsts.length; ++i) {
- if (i != 1 && !tsts[i].ok()) {
- return new Result(Result.Value.FAILURE, "Some tests did not have the expected result.");
- }
- }
- return new Result(Result.Value.SUCCESS, "All tests had the expected result.");
- }, "Wrong curve test of " + curve.getBits() + "b " + CardUtil.getKeyTypeString(curve.getField()), tests.toArray(new Test[0])));
- }
- /*
- * Do some interesting tests with corrupting the custom curves.
- * For prime field:
- * - p = 0
- * - p = 1
- * - p is a square of a prime
- * - p is a composite q * s with q, s primes
- * - TODO: p divides discriminant
- */
- Random r = new Random();
- for (short keyLength : EC_Consts.FP_SIZES) {
- byte curve = EC_Consts.getCurve(keyLength, KeyPair.ALG_EC_FP);
- Test key = runTest(CommandTest.expect(new Command.Allocate(this.card, ECTesterApplet.KEYPAIR_BOTH, keyLength, KeyPair.ALG_EC_FP), ExpectedValue.SUCCESS));
- if (!key.ok()) {
- doTest(CompoundTest.all(ExpectedValue.FAILURE, "No support for " + keyLength + "b ALG_EC_FP.", key));
- continue;
- }
- Test set = CommandTest.expect(new Command.Set(this.card, ECTesterApplet.KEYPAIR_BOTH, curve, EC_Consts.PARAMETERS_DOMAIN_FP, null), ExpectedValue.SUCCESS);
- Test setup = CompoundTest.all(ExpectedValue.SUCCESS, "KeyPair setup.", key, set);
-
- Test prime0 = ecdhTest(new Command.Transform(this.card, ECTesterApplet.KEYPAIR_BOTH, EC_Consts.KEY_BOTH, EC_Consts.PARAMETER_FP, EC_Consts.TRANSFORMATION_ZERO), "Set p = 0.", "ECDH with p = 0.");
- Test prime1 = ecdhTest(new Command.Transform(this.card, ECTesterApplet.KEYPAIR_BOTH, EC_Consts.KEY_BOTH, EC_Consts.PARAMETER_FP, EC_Consts.TRANSFORMATION_ONE), "Set p = 1.", "ECDH with p = 1.");
-
- short keyHalf = (short) (keyLength / 2);
- BigInteger prime = new BigInteger(keyHalf, 50, r);
- BigInteger primePow = prime.pow(2);
- byte[] primePowBytes = ECUtil.toByteArray(primePow, keyLength);
- EC_Params primePowData = new EC_Params(EC_Consts.PARAMETER_FP, new byte[][]{primePowBytes});
- Test primePower = ecdhTest(new Command.Set(this.card, ECTesterApplet.KEYPAIR_BOTH, EC_Consts.CURVE_external, primePowData.getParams(), primePowData.flatten()), "Set p = square of a prime.", "ECDH with p = q^2.");
-
- BigInteger q = new BigInteger(keyHalf, r);
- BigInteger s = new BigInteger(keyHalf, r);
- BigInteger compositeValue = q.multiply(s);
- byte[] compositeBytes = ECUtil.toByteArray(compositeValue, keyLength);
- EC_Params compositeData = new EC_Params(EC_Consts.PARAMETER_FP, new byte[][]{compositeBytes});
- Test composite = ecdhTest(new Command.Set(this.card, ECTesterApplet.KEYPAIR_BOTH, EC_Consts.CURVE_external, compositeData.getParams(), compositeData.flatten()), "Set p = product of two primes.", "ECDH with p = q * s.");
-
- Test wrongPrime = CompoundTest.all(ExpectedValue.SUCCESS, "Tests with corrupted prime parameter.", prime0, prime1, primePower, composite);
-
- Test resetSetup = CompoundTest.all(ExpectedValue.SUCCESS, "Reset keypair.", set.clone());
-
- Test randomG = ecdhTest(new Command.Transform(this.card, ECTesterApplet.KEYPAIR_BOTH, EC_Consts.KEY_BOTH, EC_Consts.PARAMETER_G, (short) (EC_Consts.TRANSFORMATION_FULLRANDOM | EC_Consts.TRANSFORMATION_04_MASK)), "Set G = random non-point/point-like.", "ECDH with non-point G.");
- Test fullRandomG = ecdhTest(new Command.Transform(this.card, ECTesterApplet.KEYPAIR_BOTH, EC_Consts.KEY_BOTH, EC_Consts.PARAMETER_G, EC_Consts.TRANSFORMATION_FULLRANDOM), "Set G = random data.", "ECDH with G = random data.");
- Test zeroG = ecdhTest(new Command.Transform(this.card, ECTesterApplet.KEYPAIR_BOTH, EC_Consts.KEY_BOTH, EC_Consts.PARAMETER_G, EC_Consts.TRANSFORMATION_INFINITY), "Set G = inifnity.", "ECDH with G = infinity.");
- Test wrongG = CompoundTest.all(ExpectedValue.SUCCESS, "Tests with corrupted G parameter.", randomG, fullRandomG, zeroG);
-
- byte[] originalR = new byte[((keyLength + 7) / 8) + 1];
- short origRlen = EC_Consts.getCurveParameter(curve, EC_Consts.PARAMETER_R, originalR, (short) 0);
- if (origRlen != originalR.length) {
- byte[] copyR = new byte[origRlen];
- System.arraycopy(originalR, 0, copyR, 0, origRlen);
- originalR = copyR;
- }
- BigInteger originalBigR = new BigInteger(1, originalR);
-
- Test zeroR = ecdhTest(new Command.Transform(this.card, ECTesterApplet.KEYPAIR_BOTH, EC_Consts.CURVE_external, EC_Consts.PARAMETER_R, EC_Consts.TRANSFORMATION_ZERO), "Set R = 0.", "ECDH with R = 0.");
- Test oneR = ecdhTest(new Command.Transform(this.card, ECTesterApplet.KEYPAIR_BOTH, EC_Consts.CURVE_external, EC_Consts.PARAMETER_R, EC_Consts.TRANSFORMATION_ONE), "Set R = 1.", "ECDH with R = 1.");
-
- BigInteger prevPrimeR;
- do {
- prevPrimeR = BigInteger.probablePrime(originalBigR.bitLength() - 1, r);
- } while (prevPrimeR.compareTo(originalBigR) >= 0);
- byte[] prevRBytes = ECUtil.toByteArray(prevPrimeR, keyLength);
- EC_Params prevRData = new EC_Params(EC_Consts.PARAMETER_R, new byte[][]{prevRBytes});
- Test prevprimeWrongR = ecdhTest(new Command.Set(this.card, ECTesterApplet.KEYPAIR_BOTH, EC_Consts.CURVE_external, prevRData.getParams(), prevRData.flatten()), "Set R = some prime (but [r]G != infinity) smaller than original R.", "ECDH with wrong R, prevprime.");
-
- BigInteger nextPrimeR = originalBigR.nextProbablePrime();
- byte[] nextRBytes = ECUtil.toByteArray(nextPrimeR, keyLength);
- EC_Params nextRData = new EC_Params(EC_Consts.PARAMETER_R, new byte[][]{nextRBytes});
- Test nextprimeWrongR = ecdhTest(new Command.Set(this.card, ECTesterApplet.KEYPAIR_BOTH, EC_Consts.CURVE_external, nextRData.getParams(), nextRData.flatten()), "Set R = some prime (but [r]G != infinity) larger than original R.", "ECDH with wrong R, nextprime.");
-
- byte[] nonprimeRBytes = nextRBytes.clone();
- nonprimeRBytes[nonprimeRBytes.length - 1] ^= 1;
- EC_Params nonprimeWrongRData = new EC_Params(EC_Consts.PARAMETER_R, new byte[][]{nonprimeRBytes});
- Test nonprimeWrongR = ecdhTest(new Command.Set(this.card, ECTesterApplet.KEYPAIR_BOTH, EC_Consts.CURVE_external, nonprimeWrongRData.getParams(), nonprimeWrongRData.flatten()), "Set R = some composite (but [r]G != infinity).", "ECDH with wrong R, composite.");
-
- Test wrongR = CompoundTest.all(ExpectedValue.SUCCESS, "Tests with corrupted R parameter.", zeroR, oneR, prevprimeWrongR, nextprimeWrongR, nonprimeWrongR);
-
- byte[] kRaw = new byte[]{(byte) 0xff};
- EC_Params kData = new EC_Params(EC_Consts.PARAMETER_K, new byte[][]{kRaw});
- Test bigK = ecdhTest(new Command.Set(this.card, ECTesterApplet.KEYPAIR_BOTH, EC_Consts.CURVE_external, kData.getParams(), kData.flatten()), "", "");
-
- byte[] kZero = new byte[]{(byte) 0};
- EC_Params kZeroData = new EC_Params(EC_Consts.PARAMETER_K, new byte[][]{kZero});
- Test zeroK = ecdhTest(new Command.Set(this.card, ECTesterApplet.KEYPAIR_BOTH, EC_Consts.CURVE_external, kZeroData.getParams(), kZeroData.flatten()), "", "");
-
- Test wrongK = CompoundTest.all(ExpectedValue.SUCCESS, "Tests with corrupted K parameter.", bigK, zeroK);
-
- doTest(CompoundTest.all(ExpectedValue.SUCCESS, "Tests of " + keyLength + "b " + CardUtil.getKeyTypeString(KeyPair.ALG_EC_FP), setup, wrongPrime, resetSetup, wrongG, resetSetup.clone(), wrongR, resetSetup.clone(), wrongK, resetSetup.clone()));
- }
-
- /*
- * For binary field:
- * - e1, e2 or e3 is larger than m.
- * - e1 = e2 = e3 = 0
- */
- for (short keyLength : EC_Consts.F2M_SIZES) {
- byte curve = EC_Consts.getCurve(keyLength, KeyPair.ALG_EC_F2M);
- Test key = runTest(CommandTest.expect(new Command.Allocate(this.card, ECTesterApplet.KEYPAIR_BOTH, keyLength, KeyPair.ALG_EC_F2M), ExpectedValue.SUCCESS));
- if (!key.ok()) {
- doTest(CompoundTest.all(ExpectedValue.FAILURE, "No support for " + keyLength + "b ALG_EC_F2M.", key));
- continue;
- }
- Test set = CommandTest.expect(new Command.Set(this.card, ECTesterApplet.KEYPAIR_BOTH, curve, EC_Consts.PARAMETERS_DOMAIN_F2M, null), ExpectedValue.SUCCESS);
- Test setup = CompoundTest.all(ExpectedValue.SUCCESS, "KeyPair setup.", key, set);
-
- Test coeff0 = ecdhTest(new Command.Transform(this.card, ECTesterApplet.KEYPAIR_BOTH, EC_Consts.KEY_BOTH, EC_Consts.PARAMETER_F2M, EC_Consts.TRANSFORMATION_ZERO), "Set e1 = e2 = e3 = 0.", "ECDH with wrong field polynomial: x^" + keyLength);
-
- short e1 = (short) (2 * keyLength);
- short e2 = (short) (3 * keyLength);
- short e3 = (short) (4 * keyLength);
- byte[][] coeffBytes = new byte[][]{
- ByteUtil.shortToBytes(keyLength),
- ByteUtil.shortToBytes(e1),
- ByteUtil.shortToBytes(e2),
- ByteUtil.shortToBytes(e3)};
- EC_Params coeffParams = new EC_Params(EC_Consts.PARAMETER_F2M, coeffBytes);
- Test coeffLarger = ecdhTest(new Command.Set(this.card, ECTesterApplet.KEYPAIR_BOTH, EC_Consts.CURVE_external, coeffParams.getParams(), coeffParams.flatten()), "Set e1=" + e1 + ", e2=" + e2 + ", e3=" + e3, "ECDH with wrong field poly, powers larger than " + keyLength);
-
- Test wrong = CompoundTest.all(ExpectedValue.SUCCESS, "Tests with corrupted field polynomial parameter.", coeff0, coeffLarger);
- doTest(CompoundTest.all(ExpectedValue.SUCCESS, "Tests of " + keyLength + "b " + CardUtil.getKeyTypeString(KeyPair.ALG_EC_F2M), setup, wrong));
- }
-
- /*
- * TODO: tests for both Fp and F2m:
- * - generator not on curve,
- * - generator not on proper subgroup of curve(as specified by order/cofactor),
- * - wrong order,
- * - wrong cofactor.
- */
- }
-
- private Test ecdhTest(Command setupCmd, String prepareDesc, String fullDesc) {
- Test setup = CommandTest.expect(setupCmd, ExpectedValue.FAILURE);
- Test generate = CommandTest.expect(new Command.Generate(this.card, ECTesterApplet.KEYPAIR_BOTH), ExpectedValue.FAILURE);
- Test preparePhase = CompoundTest.any(ExpectedValue.SUCCESS, prepareDesc, setup, generate);
- Test allocateECDH = CommandTest.expect(new Command.AllocateKeyAgreement(this.card, EC_Consts.KeyAgreement_ALG_EC_SVDP_DH), ExpectedValue.SUCCESS);
- Test ecdh = CommandTest.expect(new Command.ECDH(this.card, ECTesterApplet.KEYPAIR_LOCAL, ECTesterApplet.KEYPAIR_REMOTE, ECTesterApplet.EXPORT_FALSE, EC_Consts.TRANSFORMATION_NONE, EC_Consts.KeyAgreement_ALG_EC_SVDP_DH), ExpectedValue.FAILURE);
-
-
- return CompoundTest.function((tests) -> {
- if (preparePhase.ok() | !allocateECDH.ok() | ecdh.ok()) {
- return new Result(Result.Value.SUCCESS, "All tests had the expected result.");
- } else {
- return new Result(Result.Value.FAILURE, "Some tests did not have the expected result.");
- }
- }, (tests) -> {
- preparePhase.run();
- if (preparePhase.ok()) {
- return;
- }
- allocateECDH.run();
- if (!allocateECDH.ok()) {
- return;
- }
- ecdh.run();
- }, fullDesc, preparePhase, allocateECDH, ecdh);
- }
-}
diff --git a/src/cz/crcs/ectester/reader/test/CommandTest.java b/src/cz/crcs/ectester/reader/test/CommandTest.java
deleted file mode 100644
index b05d3e4..0000000
--- a/src/cz/crcs/ectester/reader/test/CommandTest.java
+++ /dev/null
@@ -1,85 +0,0 @@
-package cz.crcs.ectester.reader.test;
-
-import cz.crcs.ectester.common.test.Result;
-import cz.crcs.ectester.common.test.SimpleTest;
-import cz.crcs.ectester.common.test.TestCallback;
-import cz.crcs.ectester.reader.command.Command;
-import cz.crcs.ectester.reader.response.Response;
-
-import java.util.Arrays;
-
-/**
- * A simple test that runs one Command to get and evaluate one Response
- * to get a Result and compare it with the expected one.
- *
- * @author Jan Jancar johny@neuromancer.sk
- */
-public class CommandTest extends SimpleTest<CommandTestable> {
- private CommandTest(CommandTestable command, TestCallback<CommandTestable> callback) {
- super(command, callback);
- }
-
- public static CommandTest function(CommandTestable command, TestCallback<CommandTestable> callback) {
- return new CommandTest(command, callback);
- }
-
- public static CommandTest function(Command command, TestCallback<CommandTestable> callback) {
- return function(new CommandTestable(command), callback);
- }
-
- public static CommandTest expect(CommandTestable command, Result.ExpectedValue expected, String ok, String nok) {
- return new CommandTest(command, new TestCallback<CommandTestable>() {
- @Override
- public Result apply(CommandTestable commandTestable) {
- Result.Value resultValue = Result.Value.fromExpected(expected, commandTestable.ok(), commandTestable.error());
- return new Result(resultValue, commandTestable.error() ? commandTestable.errorCause() : (resultValue.ok() ? ok : nok));
- }
- });
- }
-
- public static CommandTest expect(Command command, Result.ExpectedValue expectedValue, String ok, String nok) {
- return expect(new CommandTestable(command), expectedValue, ok, nok);
- }
-
- public static CommandTest expect(CommandTestable command, Result.ExpectedValue expected) {
- return expect(command, expected, null, null);
- }
-
- public static CommandTest expect(Command command, Result.ExpectedValue expectedValue) {
- return expect(command, expectedValue, null, null);
- }
-
- public static CommandTest expectSW(CommandTestable command, short... expectedSWS) {
- return new CommandTest(command, new TestCallback<CommandTestable>() {
- @Override
- public Result apply(CommandTestable commandTestable) {
- if (Arrays.equals(commandTestable.getResponse().getSWs(), expectedSWS)) {
- return new Result(Result.Value.SUCCESS);
- } else {
- return new Result(Result.Value.FAILURE);
- }
- }
- });
- }
-
- public static CommandTest expectSW(Command command, short... expectedSWS) {
- return expectSW(new CommandTestable(command), expectedSWS);
- }
-
- public Command getCommand() {
- return testable.getCommand();
- }
-
- public Response getResponse() {
- return testable.getResponse();
- }
-
- @Override
- public String getDescription() {
- if (hasRun) {
- return testable.getResponse().getDescription();
- } else {
- return testable.getCommand().getDescription();
- }
- }
-}
diff --git a/src/cz/crcs/ectester/reader/test/CommandTestable.java b/src/cz/crcs/ectester/reader/test/CommandTestable.java
deleted file mode 100644
index f670534..0000000
--- a/src/cz/crcs/ectester/reader/test/CommandTestable.java
+++ /dev/null
@@ -1,44 +0,0 @@
-package cz.crcs.ectester.reader.test;
-
-import cz.crcs.ectester.common.test.BaseTestable;
-import cz.crcs.ectester.common.test.TestException;
-import cz.crcs.ectester.reader.command.Command;
-import cz.crcs.ectester.reader.response.Response;
-
-import javax.smartcardio.CardException;
-
-/**
- * @author Jan Jancar johny@neuromancer.sk
- */
-public class CommandTestable extends BaseTestable {
- private Command command;
- private Response response;
-
- public CommandTestable(Command command) {
- this.command = command;
- }
-
- public Command getCommand() {
- return command;
- }
-
- public Response getResponse() {
- return response;
- }
-
- @Override
- public void run() {
- try {
- response = command.send();
- } catch (CardException e) {
- throw new TestException(e);
- }
-
- hasRun = true;
- if (response.error()) {
- error = true;
- } else if (response.successful()) {
- ok = true;
- }
- }
-}
diff --git a/src/cz/crcs/ectester/reader/test/PerformanceTest.java b/src/cz/crcs/ectester/reader/test/PerformanceTest.java
deleted file mode 100644
index f9cba46..0000000
--- a/src/cz/crcs/ectester/reader/test/PerformanceTest.java
+++ /dev/null
@@ -1,141 +0,0 @@
-package cz.crcs.ectester.reader.test;
-
-import cz.crcs.ectester.applet.ECTesterApplet;
-import cz.crcs.ectester.common.test.Result;
-import cz.crcs.ectester.common.test.SimpleTest;
-import cz.crcs.ectester.common.test.TestCallback;
-import cz.crcs.ectester.common.test.TestException;
-import cz.crcs.ectester.reader.CardMngr;
-import cz.crcs.ectester.reader.command.Command;
-import cz.crcs.ectester.reader.response.Response;
-
-import javax.smartcardio.CardException;
-import java.util.Arrays;
-
-/**
- * @author Jan Jancar johny@neuromancer.sk
- */
-public class PerformanceTest extends SimpleTest<CommandTestable> {
- private CardMngr cardManager;
- private long[] times;
- private long[] reducedTimes;
- private Response[] responses;
- private long mean;
- private long median;
- private long mode;
- private int count;
- private String desc;
-
- private PerformanceTest(CardMngr cardManager, CommandTestable testable, int count, String desc) {
- super(testable, new TestCallback<CommandTestable>() {
- @Override
- public Result apply(CommandTestable testable) {
- return new Result(Result.Value.SUCCESS);
- }
- });
- this.cardManager = cardManager;
- this.count = count;
- this.desc = desc;
- }
-
- public static PerformanceTest repeat(CardMngr cardManager, Command cmd, int count) {
- return new PerformanceTest(cardManager, new CommandTestable(cmd), count, null);
- }
-
- public static PerformanceTest repeat(CardMngr cardManager, String desc, Command cmd, int count) {
- return new PerformanceTest(cardManager, new CommandTestable(cmd), count, desc);
- }
-
- @Override
- public String getDescription() {
- String rest = String.format("Mean = %d ns, Median = %d ns, Mode = %d ns", mean, median, mode);
- return (desc == null ? rest : desc + " (" + rest + ")");
- }
-
- @Override
- protected void runSelf() {
- long baseTime;
- try {
- new Command.SetDryRunMode(cardManager, ECTesterApplet.MODE_DRY_RUN).send();
- testable.run();
- baseTime = testable.getResponse().getDuration();
- testable.reset();
- testable.run();
- baseTime += testable.getResponse().getDuration();
- testable.reset();
- baseTime /= 2;
- new Command.SetDryRunMode(cardManager, ECTesterApplet.MODE_NORMAL).send();
- } catch (CardException ce) {
- throw new TestException(ce);
- }
-
- times = new long[count];
- reducedTimes = new long[count];
- responses = new Response[count];
- for (int i = 0; i < count; ++i) {
- testable.run();
- responses[i] = testable.getResponse();
- times[i] = responses[i].getDuration();
- reducedTimes[i] = times[i] - baseTime;
- testable.reset();
- }
-
- mean = Arrays.stream(reducedTimes).sum() / count;
-
- long[] sorted = reducedTimes.clone();
- Arrays.sort(sorted);
- if (count % 2 == 0) {
- median = (sorted[(count / 2) - 1] + sorted[count / 2]) / 2;
- } else {
- median = sorted[count / 2];
- }
-
- long max_occurences = 0;
- int i = 0;
- while (i < count) {
- long current_value = sorted[i];
- long current_occurences = 0;
- while (i < count && sorted[i] == current_value) {
- i++;
- current_occurences++;
- }
- if (current_occurences > max_occurences) {
- max_occurences = current_occurences;
- mode = current_value;
- }
- }
- result = callback.apply(testable);
- }
-
- public long getCount() {
- return count;
- }
-
- public Command getCommand() {
- return testable.getCommand();
- }
-
- public Response[] getResponses() {
- return responses;
- }
-
- public long[] getTimes() {
- return times;
- }
-
- public long[] getReducedTimes() {
- return reducedTimes;
- }
-
- public long getMean() {
- return mean;
- }
-
- public long getMedian() {
- return median;
- }
-
- public long getMode() {
- return mode;
- }
-}