diff options
| author | J08nY | 2024-03-22 23:58:55 +0100 |
|---|---|---|
| committer | J08nY | 2024-03-25 14:52:43 +0100 |
| commit | 73af477a8774e1ede5dd8de6491eb353dc0b12bd (patch) | |
| tree | 2d4e3b19bc5fb55308b886032312be76341736d4 /src/cz/crcs/ectester/standalone/test | |
| parent | 64b95fa059295e1dc23371c849f2302c1c18f5b4 (diff) | |
| download | ECTester-73af477a8774e1ede5dd8de6491eb353dc0b12bd.tar.gz ECTester-73af477a8774e1ede5dd8de6491eb353dc0b12bd.tar.zst ECTester-73af477a8774e1ede5dd8de6491eb353dc0b12bd.zip | |
Basic Gradle setup.
Diffstat (limited to 'src/cz/crcs/ectester/standalone/test')
21 files changed, 0 insertions, 2586 deletions
diff --git a/src/cz/crcs/ectester/standalone/test/base/KeyAgreementTest.java b/src/cz/crcs/ectester/standalone/test/base/KeyAgreementTest.java deleted file mode 100644 index fd48212..0000000 --- a/src/cz/crcs/ectester/standalone/test/base/KeyAgreementTest.java +++ /dev/null @@ -1,59 +0,0 @@ -package cz.crcs.ectester.standalone.test.base; - -import cz.crcs.ectester.common.test.Result; -import cz.crcs.ectester.common.test.SimpleTest; -import cz.crcs.ectester.common.test.TestCallback; - -import java.util.Arrays; - -/** - * @author Jan Jancar johny@neuromancer.sk - */ -public class KeyAgreementTest extends SimpleTest<KeyAgreementTestable> { - private KeyAgreementTest(KeyAgreementTestable ka, TestCallback<KeyAgreementTestable> callback) { - super(ka, callback); - } - - public static KeyAgreementTest match(KeyAgreementTestable ka, byte[] expectedSecret) { - return new KeyAgreementTest(ka, new TestCallback<KeyAgreementTestable>() { - @Override - public Result apply(KeyAgreementTestable ka) { - if (Arrays.equals(ka.getSecret(), expectedSecret)) { - return new Result(Result.Value.SUCCESS, "The KeyAgreement result matched the expected derived secret."); - } else { - return new Result(Result.Value.FAILURE, "The KeyAgreement result did not match the expected derived secret."); - } - } - }); - } - - public static KeyAgreementTest expect(KeyAgreementTestable ka, Result.ExpectedValue expected) { - return new KeyAgreementTest(ka, new TestCallback<KeyAgreementTestable>() { - @Override - public Result apply(KeyAgreementTestable keyAgreementTestable) { - Result.Value value = Result.Value.fromExpected(expected, keyAgreementTestable.ok(), keyAgreementTestable.error()); - return new Result(value, value.description()); - } - }); - } - - public static KeyAgreementTest expectError(KeyAgreementTestable ka, Result.ExpectedValue expected) { - return new KeyAgreementTest(ka, new TestCallback<KeyAgreementTestable>() { - @Override - public Result apply(KeyAgreementTestable keyAgreementTestable) { - Result.Value value = Result.Value.fromExpected(expected, keyAgreementTestable.ok(), false); - return new Result(value, value.description()); - } - }); - } - - public static KeyAgreementTest function(KeyAgreementTestable ka, TestCallback<KeyAgreementTestable> callback) { - return new KeyAgreementTest(ka, callback); - } - - @Override - public String getDescription() { - String keyAlgo = testable.getKeyAlgorithm() == null ? "" : " (" + testable.getKeyAlgorithm() + ")"; - return "KeyAgreement " + testable.getKa().getAlgorithm() + keyAlgo; - } -} diff --git a/src/cz/crcs/ectester/standalone/test/base/KeyAgreementTestable.java b/src/cz/crcs/ectester/standalone/test/base/KeyAgreementTestable.java deleted file mode 100644 index 7fd1c5a..0000000 --- a/src/cz/crcs/ectester/standalone/test/base/KeyAgreementTestable.java +++ /dev/null @@ -1,179 +0,0 @@ -package cz.crcs.ectester.standalone.test.base; - -import javax.crypto.KeyAgreement; -import javax.crypto.SecretKey; -import java.security.InvalidAlgorithmParameterException; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.security.interfaces.ECPrivateKey; -import java.security.interfaces.ECPublicKey; -import java.security.spec.AlgorithmParameterSpec; -import java.security.spec.ECParameterSpec; - -/** - * @author Jan Jancar johny@neuromancer.sk - */ -public class KeyAgreementTestable extends StandaloneTestable<KeyAgreementTestable.KeyAgreementStage> { - private KeyAgreement ka; - private ECPrivateKey privateKey; - private ECPublicKey publicKey; - private KeyGeneratorTestable kgtPrivate; - private KeyGeneratorTestable kgtPublic; - private AlgorithmParameterSpec spec; - private String keyAlgo; - private byte[] secret; - private SecretKey derived; - - public KeyAgreementTestable(KeyAgreement ka, ECPrivateKey privateKey, ECPublicKey publicKey) { - this.ka = ka; - this.privateKey = privateKey; - this.publicKey = publicKey; - } - - public KeyAgreementTestable(KeyAgreement ka, ECPrivateKey privateKey, ECPublicKey publicKey, String keyAlgo) { - this(ka, privateKey, publicKey); - this.keyAlgo = keyAlgo; - } - - public KeyAgreementTestable(KeyAgreement ka, ECPrivateKey privateKey, ECPublicKey publicKey, ECParameterSpec spec) { - this(ka, privateKey, publicKey); - this.spec = spec; - } - - public KeyAgreementTestable(KeyAgreement ka, ECPrivateKey privateKey, ECPublicKey publicKey, ECParameterSpec spec, String keyAlgo) { - this(ka, privateKey, publicKey, spec); - this.keyAlgo = keyAlgo; - } - - public KeyAgreementTestable(KeyAgreement ka, KeyGeneratorTestable kgt, ECPrivateKey privateKey, ECParameterSpec spec) { - this(ka, privateKey, null, spec); - this.kgtPublic = kgt; - } - - public KeyAgreementTestable(KeyAgreement ka, KeyGeneratorTestable kgt, ECPrivateKey privateKey, ECParameterSpec spec, String keyAlgo) { - this(ka, kgt, privateKey, spec); - this.keyAlgo = keyAlgo; - } - - public KeyAgreementTestable(KeyAgreement ka, ECPublicKey publicKey, KeyGeneratorTestable kgt, ECParameterSpec spec) { - this(ka, null, publicKey, spec); - this.kgtPrivate = kgt; - } - - public KeyAgreementTestable(KeyAgreement ka, ECPublicKey publicKey, KeyGeneratorTestable kgt, ECParameterSpec spec, String keyAlgo) { - this(ka, publicKey, kgt, spec); - this.keyAlgo = keyAlgo; - } - - public KeyAgreementTestable(KeyAgreement ka, KeyGeneratorTestable privKgt, KeyGeneratorTestable pubKgt, ECParameterSpec spec) { - this(ka, (ECPrivateKey) null, null, spec); - this.kgtPrivate = privKgt; - this.kgtPublic = pubKgt; - } - - public KeyAgreementTestable(KeyAgreement ka, KeyGeneratorTestable privKgt, KeyGeneratorTestable pubKgt, ECParameterSpec spec, String keyAlgo) { - this(ka, privKgt, pubKgt, spec); - this.keyAlgo = keyAlgo; - } - - public String getKeyAlgorithm() { - return keyAlgo; - } - - public KeyAgreement getKa() { - return ka; - } - - public ECPublicKey getPublicKey() { - return publicKey; - } - - public ECPrivateKey getPrivateKey() { - return privateKey; - } - - public byte[] getSecret() { - if (!hasRun) { - return null; - } - return secret; - } - - public SecretKey getDerivedKey() { - if (!hasRun) { - return null; - } - return derived; - } - - @Override - public void run() { - try { - stage = KeyAgreementStage.GetPrivate; - if (kgtPrivate != null) { - privateKey = (ECPrivateKey) kgtPrivate.getKeyPair().getPrivate(); - } - - stage = KeyAgreementStage.GetPublic; - if (kgtPublic != null) { - publicKey = (ECPublicKey) kgtPublic.getKeyPair().getPublic(); - } - - stage = KeyAgreementStage.Init; - try { - if (spec != null) { - ka.init(privateKey, spec); - } else { - ka.init(privateKey); - } - } catch (InvalidKeyException | InvalidAlgorithmParameterException e) { - failOnException(e); - return; - } - - stage = KeyAgreementStage.DoPhase; - try { - ka.doPhase(publicKey, true); - } catch (IllegalStateException | InvalidKeyException e) { - failOnException(e); - return; - } - - stage = KeyAgreementStage.GenerateSecret; - try { - if (keyAlgo != null) { - derived = ka.generateSecret(keyAlgo); - secret = derived.getEncoded(); - } else { - secret = ka.generateSecret(); - } - } catch (IllegalStateException | UnsupportedOperationException e) { - failOnException(e); - return; - } - - ok = true; - } catch (Exception ex) { - ok = false; - error = true; - errorCause = ex; - } - hasRun = true; - } - - @Override - public void reset() { - super.reset(); - try { - ka = KeyAgreement.getInstance(ka.getAlgorithm(), ka.getProvider()); - } catch (NoSuchAlgorithmException e) { } - } - - public enum KeyAgreementStage { - GetPrivate, - GetPublic, - Init, - DoPhase, - GenerateSecret - } -} diff --git a/src/cz/crcs/ectester/standalone/test/base/KeyGeneratorTest.java b/src/cz/crcs/ectester/standalone/test/base/KeyGeneratorTest.java deleted file mode 100644 index 32f82cb..0000000 --- a/src/cz/crcs/ectester/standalone/test/base/KeyGeneratorTest.java +++ /dev/null @@ -1,43 +0,0 @@ -package cz.crcs.ectester.standalone.test.base; - -import cz.crcs.ectester.common.test.Result; -import cz.crcs.ectester.common.test.SimpleTest; -import cz.crcs.ectester.common.test.TestCallback; - -/** - * @author Jan Jancar johny@neuromancer.sk - */ -public class KeyGeneratorTest extends SimpleTest<KeyGeneratorTestable> { - private KeyGeneratorTest(KeyGeneratorTestable kg, TestCallback<KeyGeneratorTestable> callback) { - super(kg, callback); - } - - public static KeyGeneratorTest expect(KeyGeneratorTestable kg, Result.ExpectedValue expected) { - return new KeyGeneratorTest(kg, new TestCallback<KeyGeneratorTestable>() { - @Override - public Result apply(KeyGeneratorTestable keyGenerationTestable) { - Result.Value value = Result.Value.fromExpected(expected, keyGenerationTestable.ok(), keyGenerationTestable.error()); - return new Result(value, value.description()); - } - }); - } - - public static KeyGeneratorTest expectError(KeyGeneratorTestable kg, Result.ExpectedValue expected) { - return new KeyGeneratorTest(kg, new TestCallback<KeyGeneratorTestable>() { - @Override - public Result apply(KeyGeneratorTestable keyGenerationTestable) { - Result.Value value = Result.Value.fromExpected(expected, keyGenerationTestable.ok(), false); - return new Result(value, value.description()); - } - }); - } - - public static KeyGeneratorTest function(KeyGeneratorTestable ka, TestCallback<KeyGeneratorTestable> callback) { - return new KeyGeneratorTest(ka, callback); - } - - @Override - public String getDescription() { - return "KeyPairGenerator " + testable.getKpg().getAlgorithm(); - } -} diff --git a/src/cz/crcs/ectester/standalone/test/base/KeyGeneratorTestable.java b/src/cz/crcs/ectester/standalone/test/base/KeyGeneratorTestable.java deleted file mode 100644 index c05d6e3..0000000 --- a/src/cz/crcs/ectester/standalone/test/base/KeyGeneratorTestable.java +++ /dev/null @@ -1,70 +0,0 @@ -package cz.crcs.ectester.standalone.test.base; - -import java.security.InvalidAlgorithmParameterException; -import java.security.KeyPair; -import java.security.KeyPairGenerator; -import java.security.spec.ECParameterSpec; - -/** - * @author Jan Jancar johny@neuromancer.sk - */ -public class KeyGeneratorTestable extends StandaloneTestable<KeyGeneratorTestable.KeyGeneratorStage> { - private KeyPair kp; - private KeyPairGenerator kpg; - private int keysize = 0; - private ECParameterSpec spec = null; - - public KeyGeneratorTestable(KeyPairGenerator kpg) { - this.kpg = kpg; - } - - public KeyGeneratorTestable(KeyPairGenerator kpg, int keysize) { - this.kpg = kpg; - this.keysize = keysize; - } - - public KeyGeneratorTestable(KeyPairGenerator kpg, ECParameterSpec spec) { - this.kpg = kpg; - this.spec = spec; - } - - public KeyPairGenerator getKpg() { - return kpg; - } - - public KeyPair getKeyPair() { - return kp; - } - - @Override - public void run() { - try { - stage = KeyGeneratorStage.Init; - try { - if (spec != null) { - kpg.initialize(spec); - } else if (keysize != 0) { - kpg.initialize(keysize); - } - } catch (InvalidAlgorithmParameterException e) { - failOnException(e); - return; - } - - stage = KeyGeneratorStage.GenKeyPair; - kp = kpg.genKeyPair(); - - ok = true; - } catch (Exception ex) { - ok = false; - error = true; - errorCause = ex; - } - hasRun = true; - } - - public enum KeyGeneratorStage { - Init, - GenKeyPair - } -} diff --git a/src/cz/crcs/ectester/standalone/test/base/PerformanceTest.java b/src/cz/crcs/ectester/standalone/test/base/PerformanceTest.java deleted file mode 100644 index 258ca12..0000000 --- a/src/cz/crcs/ectester/standalone/test/base/PerformanceTest.java +++ /dev/null @@ -1,109 +0,0 @@ -package cz.crcs.ectester.standalone.test.base; - -import cz.crcs.ectester.common.test.BaseTestable; -import cz.crcs.ectester.common.test.Result; -import cz.crcs.ectester.common.test.SimpleTest; -import cz.crcs.ectester.common.test.TestCallback; - -import java.util.Arrays; - -/** - * @author David Hofman - */ -public class PerformanceTest extends SimpleTest<BaseTestable> { - private long[] times; - private long mean; - private long median; - private long mode; - private final int count; - private final String desc; - - private PerformanceTest(BaseTestable testable, int count, String desc) { - super(testable, new TestCallback<BaseTestable>() { - @Override - public Result apply(BaseTestable testable) { - return new Result(Result.Value.SUCCESS); - } - }); - this.count = count; - this.desc = desc; - } - - public static PerformanceTest repeat(BaseTestable testable, int count) { - return new PerformanceTest(testable, count, null); - } - - public static PerformanceTest repeat(BaseTestable testable, String desc, int count) { - return new PerformanceTest(testable, 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() { - - times = new long[count]; - for (int i = 0; i < count; ++i) { - times[i] = measureTime(); - } - - mean = Arrays.stream(times).sum() / count; - - long[] sorted = times.clone(); - Arrays.sort(sorted); - if (count % 2 == 0) { - median = (sorted[(count / 2) - 1] + sorted[count / 2]) / 2; - } else { - median = sorted[count / 2]; - } - - long max_occurrences = 0; - int i = 0; - while (i < count) { - long current_value = sorted[i]; - long current_occurrences = 0; - while (i < count && sorted[i] == current_value) { - i++; - current_occurrences++; - } - if (current_occurrences > max_occurrences) { - max_occurrences = current_occurrences; - mode = current_value; - } - } - result = callback.apply(testable); - } - - public long getCount() { - return count; - } - - public long[] getTimes() { - return times; - } - - public long getMean() { - return mean; - } - - public long getMedian() { - return median; - } - - public long getMode() { - return mode; - } - - private long measureTime() { - if(testable.hasRun()) { - testable.reset(); - } - long startTime = System.nanoTime(); - testable.run(); - return System.nanoTime() - startTime; - } -} diff --git a/src/cz/crcs/ectester/standalone/test/base/SignatureTest.java b/src/cz/crcs/ectester/standalone/test/base/SignatureTest.java deleted file mode 100644 index a817691..0000000 --- a/src/cz/crcs/ectester/standalone/test/base/SignatureTest.java +++ /dev/null @@ -1,43 +0,0 @@ -package cz.crcs.ectester.standalone.test.base; - -import cz.crcs.ectester.common.test.Result; -import cz.crcs.ectester.common.test.SimpleTest; -import cz.crcs.ectester.common.test.TestCallback; - -/** - * @author Jan Jancar johny@neuromancer.sk - */ -public class SignatureTest extends SimpleTest<SignatureTestable> { - private SignatureTest(SignatureTestable sig, TestCallback<SignatureTestable> callback) { - super(sig, callback); - } - - public static SignatureTest expect(SignatureTestable kg, Result.ExpectedValue expected) { - return new SignatureTest(kg, new TestCallback<SignatureTestable>() { - @Override - public Result apply(SignatureTestable signatureTestable) { - Result.Value value = Result.Value.fromExpected(expected, signatureTestable.ok(), signatureTestable.error()); - return new Result(value, value.description()); - } - }); - } - - public static SignatureTest expectError(SignatureTestable kg, Result.ExpectedValue expected) { - return new SignatureTest(kg, new TestCallback<SignatureTestable>() { - @Override - public Result apply(SignatureTestable signatureTestable) { - Result.Value value = Result.Value.fromExpected(expected, signatureTestable.ok(), false); - return new Result(value, value.description()); - } - }); - } - - public static SignatureTest function(SignatureTestable ka, TestCallback<SignatureTestable> callback) { - return new SignatureTest(ka, callback); - } - - @Override - public String getDescription() { - return "Signature " + testable.getSig().getAlgorithm(); - } -} diff --git a/src/cz/crcs/ectester/standalone/test/base/SignatureTestable.java b/src/cz/crcs/ectester/standalone/test/base/SignatureTestable.java deleted file mode 100644 index fe81b10..0000000 --- a/src/cz/crcs/ectester/standalone/test/base/SignatureTestable.java +++ /dev/null @@ -1,143 +0,0 @@ -package cz.crcs.ectester.standalone.test.base; - -import java.security.InvalidKeyException; -import java.security.SecureRandom; -import java.security.Signature; -import java.security.SignatureException; -import java.security.interfaces.ECPrivateKey; -import java.security.interfaces.ECPublicKey; - -/** - * @author Jan Jancar johny@neuromancer.sk - */ -public class SignatureTestable extends StandaloneTestable<SignatureTestable.SignatureStage> { - private Signature sig; - private ECPrivateKey signKey; - private ECPublicKey verifyKey; - private KeyGeneratorTestable kgt; - private byte[] data; - private byte[] signature; - private boolean verified; - - public SignatureTestable(Signature sig, ECPrivateKey signKey, ECPublicKey verifyKey, byte[] data) { - this.sig = sig; - this.signKey = signKey; - this.verifyKey = verifyKey; - this.data = data; - if (data == null) { - SecureRandom random = new SecureRandom(); - this.data = new byte[64]; - random.nextBytes(this.data); - } - } - - public SignatureTestable(Signature sig, ECPublicKey verifyKey, byte[] data, byte[] signature) { - this.sig = sig; - this.verifyKey = verifyKey; - this.data = data; - this.signature = signature; - } - - public SignatureTestable(Signature sig, KeyGeneratorTestable kgt, byte[] data) { - this(sig, (ECPrivateKey) null, null, data); - this.kgt = kgt; - } - - public Signature getSig() { - return sig; - } - - public byte[] getData() { - return data; - } - - public byte[] getSignature() { - return signature; - } - - public boolean getVerified() { - return verified; - } - - @Override - public void run() { - try { - stage = SignatureStage.GetKeys; - if (kgt != null) { - signKey = (ECPrivateKey) kgt.getKeyPair().getPrivate(); - verifyKey = (ECPublicKey) kgt.getKeyPair().getPublic(); - } - - if(signKey != null) { - stage = SignatureStage.InitSign; - try { - sig.initSign(signKey); - } catch (InvalidKeyException e) { - failOnException(e); - return; - } - - stage = SignatureStage.UpdateSign; - try { - sig.update(data); - } catch (SignatureException e) { - failOnException(e); - return; - } - - stage = SignatureStage.Sign; - try { - signature = sig.sign(); - } catch (SignatureException e) { - failOnException(e); - return; - } - - ok = true; - } - - if (verifyKey != null) { - stage = SignatureStage.InitVerify; - try { - sig.initVerify(verifyKey); - } catch (InvalidKeyException e) { - failOnException(e); - return; - } - - stage = SignatureStage.UpdateVerify; - try { - sig.update(data); - } catch (SignatureException e) { - failOnException(e); - return; - } - - stage = SignatureStage.Verify; - try { - verified = sig.verify(signature); - } catch (SignatureException e) { - failOnException(e); - return; - } - - ok = verified; - } - } catch (Exception ex) { - ok = false; - error = true; - errorCause = ex; - } - hasRun = true; - } - - public enum SignatureStage { - GetKeys, - InitSign, - UpdateSign, - Sign, - InitVerify, - UpdateVerify, - Verify - } -} diff --git a/src/cz/crcs/ectester/standalone/test/base/StandaloneTestable.java b/src/cz/crcs/ectester/standalone/test/base/StandaloneTestable.java deleted file mode 100644 index 47bffc1..0000000 --- a/src/cz/crcs/ectester/standalone/test/base/StandaloneTestable.java +++ /dev/null @@ -1,25 +0,0 @@ -package cz.crcs.ectester.standalone.test.base; - -import cz.crcs.ectester.common.test.BaseTestable; - -/** - * @author Jan Jancar johny@neuromancer.sk - */ -public abstract class StandaloneTestable<T extends Enum<T>> extends BaseTestable { - protected T stage; - protected Exception exception; - - public T getStage() { - return stage; - } - - public Exception getException() { - return exception; - } - - protected void failOnException(Exception ex) { - ok = false; - hasRun = true; - exception = ex; - } -} diff --git a/src/cz/crcs/ectester/standalone/test/suites/StandaloneCofactorSuite.java b/src/cz/crcs/ectester/standalone/test/suites/StandaloneCofactorSuite.java deleted file mode 100644 index 52b0fbf..0000000 --- a/src/cz/crcs/ectester/standalone/test/suites/StandaloneCofactorSuite.java +++ /dev/null @@ -1,111 +0,0 @@ -package cz.crcs.ectester.standalone.test.suites; - -import cz.crcs.ectester.common.cli.TreeCommandLine; -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.ECUtil; -import cz.crcs.ectester.data.EC_Store; -import cz.crcs.ectester.standalone.ECTesterStandalone; -import cz.crcs.ectester.standalone.consts.KeyAgreementIdent; -import cz.crcs.ectester.standalone.consts.KeyPairGeneratorIdent; -import cz.crcs.ectester.standalone.test.base.KeyAgreementTest; -import cz.crcs.ectester.standalone.test.base.KeyAgreementTestable; -import cz.crcs.ectester.standalone.test.base.KeyGeneratorTest; -import cz.crcs.ectester.standalone.test.base.KeyGeneratorTestable; - -import javax.crypto.KeyAgreement; -import java.security.KeyPair; -import java.security.KeyPairGenerator; -import java.security.interfaces.ECPrivateKey; -import java.security.interfaces.ECPublicKey; -import java.security.spec.ECParameterSpec; -import java.util.*; - -/** - * @author David Hofman - */ -public class StandaloneCofactorSuite extends StandaloneTestSuite { - public StandaloneCofactorSuite(TestWriter writer, ECTesterStandalone.Config cfg, TreeCommandLine cli) { - super(writer, cfg, cli, "cofactor", "The cofactor test suite tests whether the library correctly rejects points on the curve", - "but not in the subgroup generated by the generator (so of small order, dividing the cofactor) during ECDH.", - "Supports options:", "\t - gt/kpg-type", "\t - kt/ka-type (select multiple types by separating them with commas)"); - } - - @Override - protected void runTests() throws Exception { - String kpgAlgo = cli.getOptionValue("test.kpg-type"); - String kaAlgo = cli.getOptionValue("test.ka-type"); - List<String> kaTypes = kaAlgo != null ? Arrays.asList(kaAlgo.split(",")) : new ArrayList<>(); - - KeyPairGeneratorIdent kpgIdent; - if (kpgAlgo == null) { - // try EC, if not, fail with: need to specify kpg algo. - Optional<KeyPairGeneratorIdent> kpgIdentOpt = cfg.selected.getKPGs().stream() - .filter((ident) -> ident.contains("EC")) - .findFirst(); - if (kpgIdentOpt.isPresent()) { - kpgIdent = kpgIdentOpt.get(); - } else { - System.err.println("The default KeyPairGenerator algorithm type of \"EC\" was not found. Need to specify a type."); - return; - } - } else { - // try the specified, if not, fail with: wrong kpg algo/not found. - Optional<KeyPairGeneratorIdent> kpgIdentOpt = cfg.selected.getKPGs().stream() - .filter((ident) -> ident.contains(kpgAlgo)) - .findFirst(); - if (kpgIdentOpt.isPresent()) { - kpgIdent = kpgIdentOpt.get(); - } else { - System.err.println("The KeyPairGenerator algorithm type of \"" + kpgAlgo + "\" was not found."); - return; - } - } - - 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(); - - KeyPairGenerator kpg = kpgIdent.getInstance(cfg.selected.getProvider()); - ECParameterSpec spec = curve.toSpec(); - KeyGeneratorTestable kgt = new KeyGeneratorTestable(kpg, spec); - - Test generate = KeyGeneratorTest.expectError(kgt, Result.ExpectedValue.ANY); - runTest(generate); - KeyPair kp = kgt.getKeyPair(); - if(kp == null) { - Test generateFail = CompoundTest.all(Result.ExpectedValue.SUCCESS, "Generating KeyPair has failed on " + curve.getId() + ". " + "KeyAgreement tests will be skipped.", generate); - doTest(CompoundTest.all(Result.ExpectedValue.SUCCESS, "Cofactor test of " + curve.getId() + ".", generateFail)); - continue; - } - Test generateSuccess = CompoundTest.all(Result.ExpectedValue.SUCCESS, "Generate keypair.", generate); - ECPrivateKey ecpriv = (ECPrivateKey) kp.getPrivate(); - - List<Test> allKaTests = new LinkedList<>(); - for (KeyAgreementIdent kaIdent : cfg.selected.getKAs()) { - if (kaAlgo == null || kaIdent.containsAny(kaTypes)) { - List<Test> specificKaTests = new LinkedList<>(); - for (EC_Key.Public pub : keys) { - ECPublicKey ecpub = ECUtil.toPublicKey(pub); - KeyAgreement ka = kaIdent.getInstance(cfg.selected.getProvider()); - KeyAgreementTestable testable = new KeyAgreementTestable(ka, ecpriv, ecpub); - Test keyAgreement = KeyAgreementTest.expectError(testable, Result.ExpectedValue.FAILURE); - specificKaTests.add(CompoundTest.all(Result.ExpectedValue.SUCCESS, pub.getId() + " cofactor key test.", keyAgreement)); - } - allKaTests.add(CompoundTest.all(Result.ExpectedValue.SUCCESS, "Perform " + kaIdent.getName() + " with public points on non-generator subgroup.", specificKaTests.toArray(new Test[0]))); - } - } - if(allKaTests.isEmpty()) { - allKaTests.add(CompoundTest.all(Result.ExpectedValue.SUCCESS, "None of the specified key agreement types is supported by the library.")); - } - Test tests = CompoundTest.all(Result.ExpectedValue.SUCCESS, "Do tests.", allKaTests.toArray(new Test[0])); - doTest(CompoundTest.greedyAllTry(Result.ExpectedValue.SUCCESS, "Cofactor test of " + curve.getId() + ".", generateSuccess, tests)); - } - } -} diff --git a/src/cz/crcs/ectester/standalone/test/suites/StandaloneCompositeSuite.java b/src/cz/crcs/ectester/standalone/test/suites/StandaloneCompositeSuite.java deleted file mode 100644 index c59d864..0000000 --- a/src/cz/crcs/ectester/standalone/test/suites/StandaloneCompositeSuite.java +++ /dev/null @@ -1,210 +0,0 @@ -package cz.crcs.ectester.standalone.test.suites; - -import cz.crcs.ectester.common.cli.TreeCommandLine; -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.ECUtil; -import cz.crcs.ectester.data.EC_Store; -import cz.crcs.ectester.standalone.ECTesterStandalone; -import cz.crcs.ectester.standalone.consts.KeyAgreementIdent; -import cz.crcs.ectester.standalone.consts.KeyPairGeneratorIdent; -import cz.crcs.ectester.standalone.consts.SignatureIdent; -import cz.crcs.ectester.standalone.test.base.*; - -import javax.crypto.KeyAgreement; -import java.security.KeyPair; -import java.security.KeyPairGenerator; -import java.security.Signature; -import java.security.interfaces.ECPrivateKey; -import java.security.interfaces.ECPublicKey; -import java.security.spec.ECParameterSpec; -import java.util.*; - -/** - * @author David Hofman - */ -public class StandaloneCompositeSuite extends StandaloneTestSuite { - private String kpgAlgo; - private String kaAlgo; - private String sigAlgo; - private List<String> kaTypes; - private List<String> sigTypes; - - public StandaloneCompositeSuite(TestWriter writer, ECTesterStandalone.Config cfg, TreeCommandLine cli) { - super(writer, cfg, cli, "composite", "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.", - "Supports options:", - "\t - gt/kpg-type", - "\t - kt/ka-type (select multiple types by separating them with commas)", - "\t - st/sig-type (select multiple types by separating them with commas)"); - } - - @Override - protected void runTests() throws Exception { - kpgAlgo = cli.getOptionValue("test.kpg-type"); - kaAlgo = cli.getOptionValue("test.ka-type"); - sigAlgo = cli.getOptionValue("test.sig-type"); - kaTypes = kaAlgo != null ? Arrays.asList(kaAlgo.split(",")) : new ArrayList<>(); - sigTypes = sigAlgo != null ? Arrays.asList(sigAlgo.split(",")) : new ArrayList<>(); - - KeyPairGeneratorIdent kpgIdent; - if (kpgAlgo == null) { - // try EC, if not, fail with: need to specify kpg algo. - Optional<KeyPairGeneratorIdent> kpgIdentOpt = cfg.selected.getKPGs().stream() - .filter((ident) -> ident.contains("EC")) - .findFirst(); - if (kpgIdentOpt.isPresent()) { - kpgIdent = kpgIdentOpt.get(); - } else { - System.err.println("The default KeyPairGenerator algorithm type of \"EC\" was not found. Need to specify a type."); - return; - } - } else { - // try the specified, if not, fail with: wrong kpg algo/not found. - Optional<KeyPairGeneratorIdent> kpgIdentOpt = cfg.selected.getKPGs().stream() - .filter((ident) -> ident.contains(kpgAlgo)) - .findFirst(); - if (kpgIdentOpt.isPresent()) { - kpgIdent = kpgIdentOpt.get(); - } else { - System.err.println("The KeyPairGenerator algorithm type of \"" + kpgAlgo + "\" was not found."); - return; - } - } - KeyPairGenerator kpg = kpgIdent.getInstance(cfg.selected.getProvider()); - - Map<String, EC_Key.Public> keys = EC_Store.getInstance().getObjects(EC_Key.Public.class, "composite"); - Map<EC_Curve, List<EC_Key.Public>> mappedKeys = EC_Store.mapKeyToCurve(keys.values()); - for (Map.Entry<EC_Curve, List<EC_Key.Public>> curveKeys : mappedKeys.entrySet()) { - EC_Curve curve = curveKeys.getKey(); - ECParameterSpec spec = curve.toSpec(); - - //Generate KeyPair - KeyGeneratorTestable kgt = new KeyGeneratorTestable(kpg, spec); - Test generate = KeyGeneratorTest.expectError(kgt, Result.ExpectedValue.ANY); - runTest(generate); - KeyPair kp = kgt.getKeyPair(); - if(kp == null) { - Test generateFail = CompoundTest.all(Result.ExpectedValue.SUCCESS, "Generating KeyPair has failed on " + curve.getId() + ". " + "KeyAgreement tests will be skipped.", generate); - doTest(CompoundTest.all(Result.ExpectedValue.SUCCESS, "Composite test of " + curve.getId() + ".", generateFail)); - continue; - } - Test generateSuccess = CompoundTest.all(Result.ExpectedValue.SUCCESS, "Generate keypair.", generate); - ECPrivateKey ecpriv = (ECPrivateKey) kp.getPrivate(); - - //Perform KeyAgreement tests - List<Test> allKaTests = new LinkedList<>(); - for (KeyAgreementIdent kaIdent : cfg.selected.getKAs()) { - if (kaAlgo == null || kaIdent.containsAny(kaTypes)) { - List<Test> specificKaTests = new LinkedList<>(); - for (EC_Key.Public pub : curveKeys.getValue()) { - ECPublicKey ecpub = ECUtil.toPublicKey(pub); - KeyAgreement ka = kaIdent.getInstance(cfg.selected.getProvider()); - KeyAgreementTestable testable = new KeyAgreementTestable(ka, ecpriv ,ecpub); - Test keyAgreement = KeyAgreementTest.expectError(testable, Result.ExpectedValue.FAILURE); - specificKaTests.add(CompoundTest.all(Result.ExpectedValue.SUCCESS, "Composite test of " + curve.getId() + ", with generated private key, " + pub.getDesc(), keyAgreement)); - } - allKaTests.add(CompoundTest.all(Result.ExpectedValue.SUCCESS, "Perform " + kaIdent.getName() + " with various public points.", specificKaTests.toArray(new Test[0]))); - } - } - if(allKaTests.isEmpty()) { - allKaTests.add(CompoundTest.all(Result.ExpectedValue.SUCCESS, "None of the specified key agreement types is supported by the library.")); - } - Test tests = CompoundTest.all(Result.ExpectedValue.SUCCESS, "Do tests.", allKaTests.toArray(new Test[0])); - doTest(CompoundTest.greedyAllTry(Result.ExpectedValue.SUCCESS, "Composite test of " + curve.getId() + ".", generateSuccess, tests)); - } - - - 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 by the library(no small-order public points provided). - */ - List<EC_Curve> wholeCurves = groups.entrySet().stream().filter((e) -> e.getKey().equals("whole")).findFirst().get().getValue(); - testGroup(wholeCurves, kpg, "Composite generator order", Result.ExpectedValue.FAILURE); - - /* 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, kpg, "Small generator order", Result.ExpectedValue.FAILURE); - - /* Test increasingly larger prime R, to determine where/if the behavior changes. - */ - List<EC_Curve> varyingCurves = groups.entrySet().stream().filter((e) -> e.getKey().equals("varying")).findFirst().get().getValue(); - testGroup(varyingCurves, kpg, null, Result.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, kpg, null, Result.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, kpg, "Generator order = Carmichael pseudo-prime", Result.ExpectedValue.ANY); - - /* Also test rg0 curves. - */ - List<EC_Curve> rg0Curves = groups.entrySet().stream().filter((e) -> e.getKey().equals("rg0")).findFirst().get().getValue(); - testGroup(rg0Curves, kpg, null, Result.ExpectedValue.ANY); - } - - private void testGroup(List<EC_Curve> curves, KeyPairGenerator kpg, String testName, Result.ExpectedValue dhValue) throws Exception { - for (EC_Curve curve : curves) { - String description; - if (testName == null) { - description = curve.getDesc() + " test of " + curve.getId() + "."; - } else { - description = testName + " test of " + curve.getId() + "."; - } - - //generate KeyPair - KeyGeneratorTestable kgt = new KeyGeneratorTestable(kpg, curve.toSpec()); - Test generate = KeyGeneratorTest.expectError(kgt, Result.ExpectedValue.ANY); - runTest(generate); - KeyPair kp = kgt.getKeyPair(); - if(kp == null) { - Test generateFail = CompoundTest.all(Result.ExpectedValue.SUCCESS, "Generating KeyPair has failed on " + curve.getId() + - ". " + " Other tests will be skipped.", generate); - doTest(CompoundTest.all(Result.ExpectedValue.SUCCESS, description, generateFail)); - continue; - } - Test generateSuccess = CompoundTest.all(Result.ExpectedValue.SUCCESS, "Generate keypair.", generate); - ECPrivateKey ecpriv = (ECPrivateKey) kp.getPrivate(); - ECPublicKey ecpub = (ECPublicKey) kp.getPublic(); - - //perform KeyAgreement tests - List<Test> kaTests = new LinkedList<>(); - for (KeyAgreementIdent kaIdent : cfg.selected.getKAs()) { - if (kaAlgo == null || kaIdent.containsAny(kaTypes)) { - KeyAgreement ka = kaIdent.getInstance(cfg.selected.getProvider()); - KeyAgreementTestable testable = new KeyAgreementTestable(ka, ecpriv, ecpub); - kaTests.add(KeyAgreementTest.expectError(testable, dhValue)); - } - } - if(kaTests.isEmpty()) { - kaTests.add(CompoundTest.all(Result.ExpectedValue.SUCCESS, "None of the specified KeyAgreement types is supported by the library.")); - } - - //perform Signature tests - List<Test> sigTests = new LinkedList<>(); - for (SignatureIdent sigIdent : cfg.selected.getSigs()) { - if (sigAlgo == null || sigIdent.containsAny(sigTypes)) { - Signature sig = sigIdent.getInstance(cfg.selected.getProvider()); - SignatureTestable testable = new SignatureTestable(sig, ecpriv, ecpub, null); - sigTests.add(SignatureTest.expectError(testable, dhValue)); - } - } - if(sigTests.isEmpty()) { - sigTests.add(CompoundTest.all(Result.ExpectedValue.SUCCESS, "None of the specified Signature types is supported by the library.")); - } - - Test performKeyAgreements = CompoundTest.all(Result.ExpectedValue.SUCCESS, "Perform specified KeyAgreements.", kaTests.toArray(new Test[0])); - Test performSignatures = CompoundTest.all(Result.ExpectedValue.SUCCESS, "Perform specified Signatures.", sigTests.toArray(new Test[0])); - doTest(CompoundTest.all(Result.ExpectedValue.SUCCESS, description, generateSuccess, performKeyAgreements, performSignatures)); - } - } -} diff --git a/src/cz/crcs/ectester/standalone/test/suites/StandaloneDefaultSuite.java b/src/cz/crcs/ectester/standalone/test/suites/StandaloneDefaultSuite.java deleted file mode 100644 index 1c14ecc..0000000 --- a/src/cz/crcs/ectester/standalone/test/suites/StandaloneDefaultSuite.java +++ /dev/null @@ -1,108 +0,0 @@ -package cz.crcs.ectester.standalone.test.suites; - -import cz.crcs.ectester.common.cli.TreeCommandLine; -import cz.crcs.ectester.common.ec.EC_Curve; -import cz.crcs.ectester.common.output.TestWriter; -import cz.crcs.ectester.common.test.Result; -import cz.crcs.ectester.data.EC_Store; -import cz.crcs.ectester.standalone.ECTesterStandalone; -import cz.crcs.ectester.standalone.consts.KeyAgreementIdent; -import cz.crcs.ectester.standalone.consts.KeyPairGeneratorIdent; -import cz.crcs.ectester.standalone.consts.SignatureIdent; -import cz.crcs.ectester.standalone.test.base.*; - -import javax.crypto.KeyAgreement; -import java.security.KeyPairGenerator; -import java.security.Signature; -import java.security.spec.ECParameterSpec; -import java.util.Optional; - -/** - * @author Jan Jancar johny@neuromancer.sk - */ -public class StandaloneDefaultSuite extends StandaloneTestSuite { - - public StandaloneDefaultSuite(TestWriter writer, ECTesterStandalone.Config cfg, TreeCommandLine cli) { - super(writer, cfg, cli, "default", "The default test suite run basic support of ECDH and ECDSA.", "Supports options:", "\t - gt/kpg-type", "\t - kt/ka-type", "\t - st/sig-type", "\t - key-type"); - } - - @Override - protected void runTests() throws Exception { - String kpgAlgo = cli.getOptionValue("test.kpg-type"); - String kaAlgo = cli.getOptionValue("test.ka-type"); - String sigAlgo = cli.getOptionValue("test.sig-type"); - String keyAlgo = cli.getOptionValue("test.key-type", "AES"); - - - KeyPairGeneratorIdent kpgIdent; - if (kpgAlgo == null) { - // try EC, if not, fail with: need to specify kpg algo. - Optional<KeyPairGeneratorIdent> kpgIdentOpt = cfg.selected.getKPGs().stream() - .filter((ident) -> ident.contains("EC")) - .findFirst(); - if (kpgIdentOpt.isPresent()) { - kpgIdent = kpgIdentOpt.get(); - } else { - System.err.println("The default KeyPairGenerator algorithm type of \"EC\" was not found. Need to specify a type."); - return; - } - } else { - // try the specified, if not, fail with: wrong kpg algo/not found. - Optional<KeyPairGeneratorIdent> kpgIdentOpt = cfg.selected.getKPGs().stream() - .filter((ident) -> ident.contains(kpgAlgo)) - .findFirst(); - if (kpgIdentOpt.isPresent()) { - kpgIdent = kpgIdentOpt.get(); - } else { - System.err.println("The KeyPairGenerator algorithm type of \"" + kpgAlgo + "\" was not found."); - return; - } - } - - KeyPairGenerator kpg = kpgIdent.getInstance(cfg.selected.getProvider()); - - KeyGeneratorTestable kgtOne; - KeyGeneratorTestable kgtOther; - ECParameterSpec spec = null; - if (cli.hasOption("test.bits")) { - int bits = Integer.parseInt(cli.getOptionValue("test.bits")); - kgtOne = new KeyGeneratorTestable(kpg, bits); - kgtOther = new KeyGeneratorTestable(kpg, bits); - } else if (cli.hasOption("test.named-curve")) { - String curveName = cli.getOptionValue("test.named-curve"); - EC_Curve curve = EC_Store.getInstance().getObject(EC_Curve.class, curveName); - if (curve == null) { - System.err.println("Curve not found: " + curveName); - return; - } - spec = curve.toSpec(); - kgtOne = new KeyGeneratorTestable(kpg, spec); - kgtOther = new KeyGeneratorTestable(kpg, spec); - } else { - kgtOne = new KeyGeneratorTestable(kpg); - kgtOther = new KeyGeneratorTestable(kpg); - } - - doTest(KeyGeneratorTest.expect(kgtOne, Result.ExpectedValue.SUCCESS)); - doTest(KeyGeneratorTest.expect(kgtOther, Result.ExpectedValue.SUCCESS)); - - for (KeyAgreementIdent kaIdent : cfg.selected.getKAs()) { - if (kaAlgo == null || kaIdent.contains(kaAlgo)) { - KeyAgreement ka = kaIdent.getInstance(cfg.selected.getProvider()); - KeyAgreementTestable testable; - if (kaIdent.requiresKeyAlgo()) { - testable = new KeyAgreementTestable(ka, kgtOne, kgtOther, spec, keyAlgo); - } else { - testable = new KeyAgreementTestable(ka, kgtOne, kgtOther, spec); - } - doTest(KeyAgreementTest.expect(testable, Result.ExpectedValue.SUCCESS)); - } - } - for (SignatureIdent sigIdent : cfg.selected.getSigs()) { - if (sigAlgo == null || sigIdent.contains(sigAlgo)) { - Signature sig = sigIdent.getInstance(cfg.selected.getProvider()); - doTest(SignatureTest.expect(new SignatureTestable(sig, kgtOne, null), Result.ExpectedValue.SUCCESS)); - } - } - } -} diff --git a/src/cz/crcs/ectester/standalone/test/suites/StandaloneDegenerateSuite.java b/src/cz/crcs/ectester/standalone/test/suites/StandaloneDegenerateSuite.java deleted file mode 100644 index 9ab8a39..0000000 --- a/src/cz/crcs/ectester/standalone/test/suites/StandaloneDegenerateSuite.java +++ /dev/null @@ -1,121 +0,0 @@ -package cz.crcs.ectester.standalone.test.suites; - -import cz.crcs.ectester.common.cli.TreeCommandLine; -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.ECUtil; -import cz.crcs.ectester.data.EC_Store; -import cz.crcs.ectester.standalone.ECTesterStandalone; -import cz.crcs.ectester.standalone.consts.KeyAgreementIdent; -import cz.crcs.ectester.standalone.consts.KeyPairGeneratorIdent; -import cz.crcs.ectester.standalone.test.base.KeyAgreementTest; -import cz.crcs.ectester.standalone.test.base.KeyAgreementTestable; -import cz.crcs.ectester.standalone.test.base.KeyGeneratorTest; -import cz.crcs.ectester.standalone.test.base.KeyGeneratorTestable; - -import javax.crypto.KeyAgreement; -import java.security.KeyPair; -import java.security.KeyPairGenerator; -import java.security.interfaces.ECPrivateKey; -import java.security.interfaces.ECPublicKey; -import java.security.spec.ECParameterSpec; -import java.util.*; - -/** - * @author David Hofman - */ -public class StandaloneDegenerateSuite extends StandaloneTestSuite { - public StandaloneDegenerateSuite(TestWriter writer, ECTesterStandalone.Config cfg, TreeCommandLine cli) { - super(writer, cfg, cli, "degenerate", "The degenerate suite tests whether the library 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.", - "Supports options:", "\t - gt/kpg-type", "\t - kt/ka-type (select multiple types by separating them with commas)"); - } - - @Override - protected void runTests() throws Exception { - String kpgAlgo = cli.getOptionValue("test.kpg-type"); - String kaAlgo = cli.getOptionValue("test.ka-type"); - List<String> kaTypes = kaAlgo != null ? Arrays.asList(kaAlgo.split(",")) : new ArrayList<>(); - - KeyPairGeneratorIdent kpgIdent; - if (kpgAlgo == null) { - // try EC, if not, fail with: need to specify kpg algo. - Optional<KeyPairGeneratorIdent> kpgIdentOpt = cfg.selected.getKPGs().stream() - .filter((ident) -> ident.contains("EC")) - .findFirst(); - if (kpgIdentOpt.isPresent()) { - kpgIdent = kpgIdentOpt.get(); - } else { - System.err.println("The default KeyPairGenerator algorithm type of \"EC\" was not found. Need to specify a type."); - return; - } - } else { - // try the specified, if not, fail with: wrong kpg algo/not found. - Optional<KeyPairGeneratorIdent> kpgIdentOpt = cfg.selected.getKPGs().stream() - .filter((ident) -> ident.contains(kpgAlgo)) - .findFirst(); - if (kpgIdentOpt.isPresent()) { - kpgIdent = kpgIdentOpt.get(); - } else { - System.err.println("The KeyPairGenerator algorithm type of \"" + kpgAlgo + "\" was not found."); - return; - } - } - - 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(); - - KeyPairGenerator kpg = kpgIdent.getInstance(cfg.selected.getProvider()); - ECParameterSpec spec = curve.toSpec(); - KeyGeneratorTestable kgt = new KeyGeneratorTestable(kpg, spec); - - Test generateSuccess; - Test generate = KeyGeneratorTest.expectError(kgt, Result.ExpectedValue.ANY); - runTest(generate); - KeyPair kp = kgt.getKeyPair(); - if(kp != null) { - generateSuccess = CompoundTest.all(Result.ExpectedValue.SUCCESS, "Generate keypair.", generate); - } else { //If KeyPair generation fails, try generating it on a default curve instead. Use this key only if it has the same domain parameters as our public key. - KeyGeneratorTestable kgtOnDefaultCurve = new KeyGeneratorTestable(kpg, curve.getBits()); - Test generateOnDefaultCurve = KeyGeneratorTest.expectError(kgtOnDefaultCurve, Result.ExpectedValue.ANY); - runTest(generateOnDefaultCurve); - kp = kgtOnDefaultCurve.getKeyPair(); - if(kp != null && ECUtil.equalKeyPairParameters((ECPrivateKey) kp.getPrivate(), ECUtil.toPublicKey(keys.get(0)))) { - generateSuccess = CompoundTest.all(Result.ExpectedValue.SUCCESS, "Generate keypair.", generateOnDefaultCurve); - } else { - Test generateFail = CompoundTest.all(Result.ExpectedValue.SUCCESS, "Generating KeyPair has failed on " + curve.getId() + ". " + "KeyAgreement tests will be skipped.", generate); - doTest(CompoundTest.all(Result.ExpectedValue.SUCCESS, "Degenerate curve test of " + curve.getId() + ".", generateFail)); - continue; - } - } - ECPrivateKey ecpriv = (ECPrivateKey) kp.getPrivate(); - - List<Test> allKaTests = new LinkedList<>(); - for (KeyAgreementIdent kaIdent : cfg.selected.getKAs()) { - if (kaAlgo == null || kaIdent.containsAny(kaTypes)) { - List<Test> specificKaTests = new LinkedList<>(); - for (EC_Key.Public pub : keys) { - ECPublicKey ecpub = ECUtil.toPublicKey(pub); - KeyAgreement ka = kaIdent.getInstance(cfg.selected.getProvider()); - KeyAgreementTestable testable = new KeyAgreementTestable(ka, ecpriv, ecpub); - Test keyAgreement = KeyAgreementTest.expectError(testable, Result.ExpectedValue.FAILURE); - specificKaTests.add(CompoundTest.all(Result.ExpectedValue.SUCCESS, pub.getId() + " degenerate key test.", keyAgreement)); - } - allKaTests.add(CompoundTest.all(Result.ExpectedValue.SUCCESS, "Perform " + kaIdent.getName() + " with degenerate public points..", specificKaTests.toArray(new Test[0]))); - } - } - if(allKaTests.isEmpty()) { - allKaTests.add(CompoundTest.all(Result.ExpectedValue.SUCCESS, "None of the specified key agreement types is supported by the library.")); - } - Test tests = CompoundTest.all(Result.ExpectedValue.SUCCESS, "Do tests.", allKaTests.toArray(new Test[0])); - doTest(CompoundTest.greedyAllTry(Result.ExpectedValue.SUCCESS, "Degenerate curve test of " + curve.getId() + ".", generateSuccess, tests)); - } - } -} diff --git a/src/cz/crcs/ectester/standalone/test/suites/StandaloneEdgeCasesSuite.java b/src/cz/crcs/ectester/standalone/test/suites/StandaloneEdgeCasesSuite.java deleted file mode 100644 index 3624aaa..0000000 --- a/src/cz/crcs/ectester/standalone/test/suites/StandaloneEdgeCasesSuite.java +++ /dev/null @@ -1,314 +0,0 @@ -package cz.crcs.ectester.standalone.test.suites; - -import cz.crcs.ectester.applet.EC_Consts; -import cz.crcs.ectester.common.cli.TreeCommandLine; -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.ECUtil; -import cz.crcs.ectester.data.EC_Store; -import cz.crcs.ectester.standalone.ECTesterStandalone; -import cz.crcs.ectester.standalone.consts.KeyAgreementIdent; -import cz.crcs.ectester.standalone.consts.KeyPairGeneratorIdent; -import cz.crcs.ectester.standalone.test.base.KeyAgreementTest; -import cz.crcs.ectester.standalone.test.base.KeyAgreementTestable; -import cz.crcs.ectester.standalone.test.base.KeyGeneratorTest; -import cz.crcs.ectester.standalone.test.base.KeyGeneratorTestable; - -import javax.crypto.KeyAgreement; -import java.math.BigDecimal; -import java.math.BigInteger; -import java.security.KeyPair; -import java.security.KeyPairGenerator; -import java.security.NoSuchAlgorithmException; -import java.security.interfaces.ECPrivateKey; -import java.security.interfaces.ECPublicKey; -import java.security.spec.ECParameterSpec; -import java.util.*; -import java.util.stream.Collectors; - -/** - * @author David Hofman - */ -public class StandaloneEdgeCasesSuite extends StandaloneTestSuite { - KeyAgreementIdent kaIdent; - - public StandaloneEdgeCasesSuite(TestWriter writer, ECTesterStandalone.Config cfg, TreeCommandLine cli) { - super(writer, cfg, cli, "edge-cases", "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.", - "Supports options:", - "\t - gt/kpg-type", - "\t - kt/ka-type"); - } - - @Override - protected void runTests() throws Exception { - String kaAlgo = cli.getOptionValue("test.ka-type"); - String kpgAlgo = cli.getOptionValue("test.kpg-type"); - - if (kaAlgo == null) { - // try ECDH, if not, fail with: need to specify ka algo. - Optional<KeyAgreementIdent> kaIdentOpt = cfg.selected.getKAs().stream() - .filter((ident) -> ident.contains("ECDH")) - .findFirst(); - if (kaIdentOpt.isPresent()) { - kaIdent = kaIdentOpt.get(); - } else { - System.err.println("The default KeyAgreement algorithm type of \"ECDH\" was not found. Need to specify a type."); - return; - } - } else { - // try the specified, if not, fail with: wrong ka algo/not found. - Optional<KeyAgreementIdent> kaIdentOpt = cfg.selected.getKAs().stream() - .filter((ident) -> ident.contains(kaAlgo)) - .findFirst(); - if (kaIdentOpt.isPresent()) { - kaIdent = kaIdentOpt.get(); - } else { - System.err.println("The KeyAgreement algorithm type of \"" + kaAlgo + "\" was not found."); - return; - } - } - - KeyPairGeneratorIdent kpgIdent; - if (kpgAlgo == null) { - // try EC, if not, fail with: need to specify kpg algo. - Optional<KeyPairGeneratorIdent> kpgIdentOpt = cfg.selected.getKPGs().stream() - .filter((ident) -> ident.contains("EC")) - .findFirst(); - if (kpgIdentOpt.isPresent()) { - kpgIdent = kpgIdentOpt.get(); - } else { - System.err.println("The default KeyPairGenerator algorithm type of \"EC\" was not found. Need to specify a type."); - return; - } - } else { - // try the specified, if not, fail with: wrong kpg algo/not found. - Optional<KeyPairGeneratorIdent> kpgIdentOpt = cfg.selected.getKPGs().stream() - .filter((ident) -> ident.contains(kpgAlgo)) - .findFirst(); - if (kpgIdentOpt.isPresent()) { - kpgIdent = kpgIdentOpt.get(); - } else { - System.err.println("The KeyPairGenerator algorithm type of \"" + kpgAlgo + "\" was not found."); - return; - } - } - KeyPairGenerator kpg = kpgIdent.getInstance(cfg.selected.getProvider()); - - 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<>(); - List<EC_KAResult> values = c.getValue(); - for (EC_KAResult value : values) { - String id = value.getId(); - String privkeyId = value.getOneKey(); - String pubkeyId = value.getOtherKey(); - ECPrivateKey ecpriv = ECUtil.toPrivateKey(EC_Store.getInstance().getObject(EC_Key.Private.class, privkeyId)); - ECPublicKey ecpub = ECUtil.toPublicKey(EC_Store.getInstance().getObject(EC_Key.Public.class, pubkeyId)); - - KeyAgreement ka = kaIdent.getInstance(cfg.selected.getProvider()); - KeyAgreementTestable testable = new KeyAgreementTestable(ka, ecpriv, ecpub); - Test ecdh = KeyAgreementTest.match(testable, value.getData(0)); - Test one = CompoundTest.all(Result.ExpectedValue.SUCCESS, "Test " + id + ".", ecdh); - curveTests.add(one); - } - groupTests.add(CompoundTest.all(Result.ExpectedValue.SUCCESS, "Tests on " + curve.getId() + ".", curveTests.toArray(new Test[0]))); - } - 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"); - ECPrivateKey ecpriv = ECUtil.toPrivateKey(EC_Store.getInstance().getObject(EC_Key.Private.class, openssl_bug.getOtherKey())); - ECPublicKey ecpub = ECUtil.toPublicKey(EC_Store.getInstance().getObject(EC_Key.Public.class, openssl_bug.getOneKey())); - KeyAgreement ka = kaIdent.getInstance(cfg.selected.getProvider()); - KeyAgreementTestable testable = new KeyAgreementTestable(ka, ecpriv, ecpub); - Test ecdh = KeyAgreementTest.function(testable, new TestCallback<KeyAgreementTestable>() { - @Override - public Result apply(KeyAgreementTestable testable) { - if (!testable.ok()) { - return new Result(Result.Value.FAILURE, "ECDH was unsuccessful."); - } - if (ByteUtil.compareBytes(testable.getSecret(), 0, openssl_bug.getData(0), 0, testable.getSecret().length)) { - return new Result(Result.Value.FAILURE, "OpenSSL bug is present, derived secret matches example."); - } - return new Result(Result.Value.SUCCESS); - } - }); - - doTest(CompoundTest.all(Result.ExpectedValue.SUCCESS, "Test OpenSSL modular reduction bug.", 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() == javacard.security.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) { - ECParameterSpec spec = curve.toSpec(); - - //generate KeyPair - KeyGeneratorTestable kgt = new KeyGeneratorTestable(kpg, spec); - Test generate = KeyGeneratorTest.expectError(kgt, Result.ExpectedValue.ANY); - runTest(generate); - KeyPair kp = kgt.getKeyPair(); - if (kp == null) { - Test generateFail = CompoundTest.all(Result.ExpectedValue.SUCCESS, "Generating KeyPair has failed on " + curve.getId() + - ". " + " Other tests will be skipped.", generate); - doTest(CompoundTest.all(Result.ExpectedValue.SUCCESS, "Tests with edge-case private key values over" + curve.getId() + ".", generateFail)); - continue; - } - Test generateSuccess = CompoundTest.all(Result.ExpectedValue.SUCCESS, "Generate KeyPair.", generate); - ECPublicKey ecpub = (ECPublicKey) kp.getPublic(); - - //perform ECDH tests - Test zeroS = ecdhTest(ecpub, BigInteger.ZERO, spec, "ECDH with S = 0.", Result.ExpectedValue.FAILURE); - Test oneS = ecdhTest(ecpub, BigInteger.ONE, spec, "ECDH with S = 1.", 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); - BigInteger rm1 = R.subtract(BigInteger.ONE); - BigInteger rp1 = R.add(BigInteger.ONE); - - Test alternateS = ecdhTest(ecpub, alternate, spec, "ECDH with S = 101010101...01010.", Result.ExpectedValue.SUCCESS); - Test alternateOtherS = ecdhTest(ecpub, alternateOther, spec, "ECDH with S = 010101010...10101.", Result.ExpectedValue.SUCCESS); - Test fullS = ecdhTest(ecpub, full, spec, "ECDH with S = 111111111...11111 (but < r).", Result.ExpectedValue.SUCCESS); - Test smallerS = ecdhTest(ecpub, smaller, spec, "ECDH with S < r.", Result.ExpectedValue.SUCCESS); - Test exactS = ecdhTest(ecpub, R, spec, "ECDH with S = r.", Result.ExpectedValue.FAILURE); - Test largeS = ecdhTest(ecpub, larger, spec, "ECDH with S > r.", Result.ExpectedValue.ANY); - Test rm1S = ecdhTest(ecpub, rm1, spec, "ECDH with S = r - 1.", Result.ExpectedValue.SUCCESS); - Test rp1S = ecdhTest(ecpub, rp1, spec, "ECDH with S = r + 1.", 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; - - Test krS /*ONE!*/ = ecdhTest(ecpub, kr, spec, "ECDH with S = k * r.", Result.ExpectedValue.FAILURE); - Test krm1S = ecdhTest(ecpub, krm1, spec, "ECDH with S = (k * r) - 1.", kExpected); - Test krp1S = ecdhTest(ecpub, krp1, spec, "ECDH with S = (k * r) + 1.", Result.ExpectedValue.ANY); - - doTest(CompoundTest.all(Result.ExpectedValue.SUCCESS, "Tests with edge-case private key values over " + curve.getId() + ".", - generateSuccess, zeroS, oneS, alternateS, alternateOtherS, fullS, smallerS, exactS, largeS, rm1S, rp1S, krS, krm1S, krp1S)); - } - - EC_Curve secp160r1 = EC_Store.getInstance().getObject(EC_Curve.class, "secg/secp160r1"); - ECParameterSpec spec = secp160r1.toSpec(); - 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); - - //generate KeyPair - KeyGeneratorTestable kgt = new KeyGeneratorTestable(kpg, spec); - Test generate = KeyGeneratorTest.expectError(kgt, Result.ExpectedValue.ANY); - runTest(generate); - KeyPair kp = kgt.getKeyPair(); - if(kp == null) { - Test generateFail = CompoundTest.all(Result.ExpectedValue.SUCCESS, "Generating KeyPair has failed on " - + secp160r1.getBits() + "b secp160r1." + " Other tests will be skipped.", generate); - doTest(CompoundTest.all(Result.ExpectedValue.SUCCESS, "Test private key values near zero, near p and near/larger than the order on" + secp160r1.getId() + ".", generateFail)); - return; - } - Test generateSuccess = CompoundTest.all(Result.ExpectedValue.SUCCESS, "Generate KeyPair.", generate); - ECPublicKey ecpub = (ECPublicKey) kp.getPublic(); - - //perform ECDH tests - Test[] zeroTests = new Test[n]; - int i = 0; - for (BigInteger nearZero : zeros) { - zeroTests[i++] = ecdhTest(ecpub, nearZero, spec, nearZero.toString(16), Result.ExpectedValue.SUCCESS); - } - Test zeroTest = CompoundTest.all(Result.ExpectedValue.SUCCESS, "Near zero.", zeroTests); - - Test[] pTests = new Test[n]; - i = 0; - for (BigInteger nearP : ps) { - pTests[i++] = ecdhTest(ecpub, nearP, spec, nearP.toString(16) + (nearP.compareTo(p) > 0 ? " (>p)" : " (<=p)"), Result.ExpectedValue.SUCCESS); - } - Test pTest = CompoundTest.all(Result.ExpectedValue.SUCCESS, "Near p.", pTests); - - Test[] rTests = new Test[n]; - i = 0; - for (BigInteger nearR : rs) { - if (nearR.compareTo(r) >= 0) { - rTests[i++] = ecdhTest(ecpub, nearR, spec, nearR.toString(16) + " (>=r)", Result.ExpectedValue.FAILURE); - } else { - rTests[i++] = ecdhTest(ecpub, nearR, spec, nearR.toString(16) + " (<r)", 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.", generateSuccess, zeroTest, pTest, rTest)); - } - - private Test ecdhTest(ECPublicKey pub, BigInteger SParam, ECParameterSpec spec, String desc, Result.ExpectedValue expect) throws NoSuchAlgorithmException { - ECPrivateKey priv = new RawECPrivateKey(SParam, spec); - KeyAgreement ka = kaIdent.getInstance(cfg.selected.getProvider()); - KeyAgreementTestable testable = new KeyAgreementTestable(ka, priv, pub); - return CompoundTest.all(Result.ExpectedValue.SUCCESS, desc, KeyAgreementTest.expectError(testable, expect)); - } -} diff --git a/src/cz/crcs/ectester/standalone/test/suites/StandaloneInvalidSuite.java b/src/cz/crcs/ectester/standalone/test/suites/StandaloneInvalidSuite.java deleted file mode 100644 index ace8945..0000000 --- a/src/cz/crcs/ectester/standalone/test/suites/StandaloneInvalidSuite.java +++ /dev/null @@ -1,120 +0,0 @@ -package cz.crcs.ectester.standalone.test.suites; - -import cz.crcs.ectester.common.cli.TreeCommandLine; -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.ECUtil; -import cz.crcs.ectester.data.EC_Store; -import cz.crcs.ectester.standalone.ECTesterStandalone; -import cz.crcs.ectester.standalone.consts.KeyAgreementIdent; -import cz.crcs.ectester.standalone.consts.KeyPairGeneratorIdent; -import cz.crcs.ectester.standalone.test.base.KeyAgreementTest; -import cz.crcs.ectester.standalone.test.base.KeyAgreementTestable; -import cz.crcs.ectester.standalone.test.base.KeyGeneratorTest; -import cz.crcs.ectester.standalone.test.base.KeyGeneratorTestable; - -import javax.crypto.KeyAgreement; -import java.security.KeyPair; -import java.security.KeyPairGenerator; -import java.security.interfaces.ECPrivateKey; -import java.security.interfaces.ECPublicKey; -import java.security.spec.ECParameterSpec; -import java.util.*; - -/** - * @author David Hofman - */ -public class StandaloneInvalidSuite extends StandaloneTestSuite { - public StandaloneInvalidSuite(TestWriter writer, ECTesterStandalone.Config cfg, TreeCommandLine cli) { - super(writer, cfg, cli, "invalid", "The invalid curve suite tests whether the library rejects points outside of the curve during ECDH.", - "Supports options:", "\t - gt/kpg-type", "\t - kt/ka-type (select multiple types by separating them with commas)"); - } - - @Override - protected void runTests() throws Exception { - String kpgAlgo = cli.getOptionValue("test.kpg-type"); - String kaAlgo = cli.getOptionValue("test.ka-type"); - List<String> kaTypes = kaAlgo != null ? Arrays.asList(kaAlgo.split(",")) : new ArrayList<>(); - - KeyPairGeneratorIdent kpgIdent; - if (kpgAlgo == null) { - // try EC, if not, fail with: need to specify kpg algo. - Optional<KeyPairGeneratorIdent> kpgIdentOpt = cfg.selected.getKPGs().stream() - .filter((ident) -> ident.contains("EC")) - .findFirst(); - if (kpgIdentOpt.isPresent()) { - kpgIdent = kpgIdentOpt.get(); - } else { - System.err.println("The default KeyPairGenerator algorithm type of \"EC\" was not found. Need to specify a type."); - return; - } - } else { - // try the specified, if not, fail with: wrong kpg algo/not found. - Optional<KeyPairGeneratorIdent> kpgIdentOpt = cfg.selected.getKPGs().stream() - .filter((ident) -> ident.contains(kpgAlgo)) - .findFirst(); - if (kpgIdentOpt.isPresent()) { - kpgIdent = kpgIdentOpt.get(); - } else { - System.err.println("The KeyPairGenerator algorithm type of \"" + kpgAlgo + "\" was not found."); - return; - } - } - - 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(); - - KeyPairGenerator kpg = kpgIdent.getInstance(cfg.selected.getProvider()); - ECParameterSpec spec = curve.toSpec(); - KeyGeneratorTestable kgt = new KeyGeneratorTestable(kpg, spec); - - Test generateSuccess; - Test generate = KeyGeneratorTest.expectError(kgt, Result.ExpectedValue.ANY); - runTest(generate); - KeyPair kp = kgt.getKeyPair(); - if(kp != null) { - generateSuccess = CompoundTest.all(Result.ExpectedValue.SUCCESS, "Generate keypair.", generate); - } else { //If KeyPair generation fails, try generating it on a default curve instead. Use this key only if it has the same domain parameters as our public key. - KeyGeneratorTestable kgtOnDefaultCurve = new KeyGeneratorTestable(kpg, curve.getBits()); - Test generateOnDefaultCurve = KeyGeneratorTest.expectError(kgtOnDefaultCurve, Result.ExpectedValue.ANY); - runTest(generateOnDefaultCurve); - kp = kgtOnDefaultCurve.getKeyPair(); - if(kp != null && ECUtil.equalKeyPairParameters((ECPrivateKey) kp.getPrivate(), ECUtil.toPublicKey(keys.get(0)))) { - generateSuccess = CompoundTest.all(Result.ExpectedValue.SUCCESS, "Generate keypair.", generateOnDefaultCurve); - } else { - Test generateFail = CompoundTest.all(Result.ExpectedValue.SUCCESS, "Generating KeyPair has failed on " + curve.getId() + ". " + "KeyAgreement tests will be skipped.", generate); - doTest(CompoundTest.all(Result.ExpectedValue.SUCCESS, "Invalid curve test of " + curve.getId() + ".", generateFail)); - continue; - } - } - ECPrivateKey ecpriv = (ECPrivateKey) kp.getPrivate(); - - List<Test> allKaTests = new LinkedList<>(); - for (KeyAgreementIdent kaIdent : cfg.selected.getKAs()) { - if (kaAlgo == null || kaIdent.containsAny(kaTypes)) { - List<Test> specificKaTests = new LinkedList<>(); - for (EC_Key.Public pub : keys) { - ECPublicKey ecpub = ECUtil.toPublicKey(pub); - KeyAgreement ka = kaIdent.getInstance(cfg.selected.getProvider()); - KeyAgreementTestable testable = new KeyAgreementTestable(ka, ecpriv, ecpub); - Test keyAgreement = KeyAgreementTest.expectError(testable, Result.ExpectedValue.FAILURE); - specificKaTests.add(CompoundTest.all(Result.ExpectedValue.SUCCESS, pub.getId() + " invalid key test.", keyAgreement)); - } - allKaTests.add(CompoundTest.all(Result.ExpectedValue.SUCCESS, "Perform " + kaIdent.getName() + " with invalid public points.", specificKaTests.toArray(new Test[0]))); - } - } - if(allKaTests.isEmpty()) { - allKaTests.add(CompoundTest.all(Result.ExpectedValue.SUCCESS, "None of the specified key agreement types is supported by the library.")); - } - Test tests = CompoundTest.all(Result.ExpectedValue.SUCCESS, "Do tests.", allKaTests.toArray(new Test[0])); - doTest(CompoundTest.greedyAllTry(Result.ExpectedValue.SUCCESS, "Invalid curve test of " + curve.getId() + ".", generateSuccess, tests)); - } - } -} diff --git a/src/cz/crcs/ectester/standalone/test/suites/StandaloneMiscSuite.java b/src/cz/crcs/ectester/standalone/test/suites/StandaloneMiscSuite.java deleted file mode 100644 index f3a10eb..0000000 --- a/src/cz/crcs/ectester/standalone/test/suites/StandaloneMiscSuite.java +++ /dev/null @@ -1,150 +0,0 @@ -package cz.crcs.ectester.standalone.test.suites; - -import cz.crcs.ectester.common.cli.TreeCommandLine; -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.standalone.ECTesterStandalone; -import cz.crcs.ectester.standalone.consts.KeyAgreementIdent; -import cz.crcs.ectester.standalone.consts.KeyPairGeneratorIdent; -import cz.crcs.ectester.standalone.consts.SignatureIdent; -import cz.crcs.ectester.standalone.test.base.*; - -import javax.crypto.KeyAgreement; -import java.security.KeyPair; -import java.security.KeyPairGenerator; -import java.security.NoSuchAlgorithmException; -import java.security.Signature; -import java.security.interfaces.ECPrivateKey; -import java.security.interfaces.ECPublicKey; -import java.util.*; - -/** - * @author David Hofman - */ -public class StandaloneMiscSuite extends StandaloneTestSuite { - private String kpgAlgo; - private String kaAlgo; - private String sigAlgo; - private List<String> kaTypes; - private List<String> sigTypes; - - public StandaloneMiscSuite(TestWriter writer, ECTesterStandalone.Config cfg, TreeCommandLine cli) { - super(writer, cfg, cli, "miscellaneous", "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.", - "Supports options:", - "\t - gt/kpg-type", - "\t - kt/ka-type (select multiple types by separating them with commas)", - "\t - st/sig-type (select multiple types by separating them with commas)"); - } - - @Override - protected void runTests() throws Exception { - kpgAlgo = cli.getOptionValue("test.kpg-type"); - kaAlgo = cli.getOptionValue("test.ka-type"); - sigAlgo = cli.getOptionValue("test.sig-type"); - - kaTypes = kaAlgo != null ? Arrays.asList(kaAlgo.split(",")) : new ArrayList<>(); - sigTypes = sigAlgo != null ? Arrays.asList(sigAlgo.split(",")) : new ArrayList<>(); - - KeyPairGeneratorIdent kpgIdent; - if (kpgAlgo == null) { - // try EC, if not, fail with: need to specify kpg algo. - Optional<KeyPairGeneratorIdent> kpgIdentOpt = cfg.selected.getKPGs().stream() - .filter((ident) -> ident.contains("EC")) - .findFirst(); - if (kpgIdentOpt.isPresent()) { - kpgIdent = kpgIdentOpt.get(); - } else { - System.err.println("The default KeyPairGenerator algorithm type of \"EC\" was not found. Need to specify a type."); - return; - } - } else { - // try the specified, if not, fail with: wrong kpg algo/not found. - Optional<KeyPairGeneratorIdent> kpgIdentOpt = cfg.selected.getKPGs().stream() - .filter((ident) -> ident.contains(kpgAlgo)) - .findFirst(); - if (kpgIdentOpt.isPresent()) { - kpgIdent = kpgIdentOpt.get(); - } else { - System.err.println("The KeyPairGenerator algorithm type of \"" + kpgAlgo + "\" was not found."); - return; - } - } - KeyPairGenerator kpg = kpgIdent.getInstance(cfg.selected.getProvider()); - - 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", kpg, Result.ExpectedValue.FAILURE); - testCurves(ssCurves.values(), "supersingular", kpg, Result.ExpectedValue.FAILURE); - testCurves(bnCurves.values(), "Barreto-Naehrig", kpg, Result.ExpectedValue.SUCCESS); - testCurves(mntCurves.values(), "MNT", kpg, Result.ExpectedValue.SUCCESS); - testCurves(mCurves, "Montgomery", kpg, Result.ExpectedValue.SUCCESS); - testCurve(curve25519, "Montgomery", kpg, Result.ExpectedValue.SUCCESS); - } - - private void testCurve(EC_Curve curve, String catName, KeyPairGenerator kpg, Result.ExpectedValue expected) throws NoSuchAlgorithmException { - //generate KeyPair - KeyGeneratorTestable kgt = new KeyGeneratorTestable(kpg, curve.toSpec()); - Test generate = KeyGeneratorTest.expectError(kgt, Result.ExpectedValue.ANY); - runTest(generate); - KeyPair kp = kgt.getKeyPair(); - if(kp == null) { - Test generateFail = CompoundTest.all(Result.ExpectedValue.SUCCESS, "Generating KeyPair has failed on " + curve.getId() + - ". " + " Other tests will be skipped.", generate); - doTest(CompoundTest.all(Result.ExpectedValue.SUCCESS, "Tests over " + curve.getBits() + "b " + catName + " curve: " + curve.getId() + ".", generateFail)); - return; - } - Test generateSuccess = CompoundTest.all(Result.ExpectedValue.SUCCESS, "Generate keypair.", generate); - ECPrivateKey ecpriv = (ECPrivateKey) kp.getPrivate(); - ECPublicKey ecpub = (ECPublicKey) kp.getPublic(); - - //perform KeyAgreement tests - List<Test> kaTests = new LinkedList<>(); - for (KeyAgreementIdent kaIdent : cfg.selected.getKAs()) { - if (kaAlgo == null || kaIdent.containsAny(kaTypes)) { - KeyAgreement ka = kaIdent.getInstance(cfg.selected.getProvider()); - KeyAgreementTestable testable = new KeyAgreementTestable(ka, ecpriv, ecpub); - kaTests.add(KeyAgreementTest.expectError(testable, expected)); - } - } - if(kaTests.isEmpty()) { - kaTests.add(CompoundTest.all(Result.ExpectedValue.SUCCESS, "None of the specified KeyAgreement types is supported by the library.")); - } - - //perform Signature tests - List<Test> sigTests = new LinkedList<>(); - for (SignatureIdent sigIdent : cfg.selected.getSigs()) { - if (sigAlgo == null || sigIdent.containsAny(sigTypes)) { - Signature sig = sigIdent.getInstance(cfg.selected.getProvider()); - SignatureTestable testable = new SignatureTestable(sig, ecpriv, ecpub, null); - sigTests.add(SignatureTest.expectError(testable, expected)); - } - } - if(sigTests.isEmpty()) { - sigTests.add(CompoundTest.all(Result.ExpectedValue.SUCCESS, "None of the specified Signature types is supported by the library.")); - } - - Test performKeyAgreements = CompoundTest.all(Result.ExpectedValue.SUCCESS, "Perform specified KeyAgreements.", kaTests.toArray(new Test[0])); - Test performSignatures = CompoundTest.all(Result.ExpectedValue.SUCCESS, "Perform specified Signatures.", sigTests.toArray(new Test[0])); - doTest(CompoundTest.all(Result.ExpectedValue.SUCCESS, "Tests over " + curve.getBits() + "b " + catName + " curve: " + curve.getId() + ".", generateSuccess, performKeyAgreements, performSignatures)); - } - - private void testCurves(Collection<EC_Curve> curves, String catName, KeyPairGenerator kpg, Result.ExpectedValue expected) throws NoSuchAlgorithmException { - for (EC_Curve curve : curves) { - testCurve(curve, catName, kpg, expected); - } - } -} diff --git a/src/cz/crcs/ectester/standalone/test/suites/StandalonePerformanceSuite.java b/src/cz/crcs/ectester/standalone/test/suites/StandalonePerformanceSuite.java deleted file mode 100644 index dd50862..0000000 --- a/src/cz/crcs/ectester/standalone/test/suites/StandalonePerformanceSuite.java +++ /dev/null @@ -1,142 +0,0 @@ -package cz.crcs.ectester.standalone.test.suites; - -import cz.crcs.ectester.common.cli.TreeCommandLine; -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.standalone.ECTesterStandalone; -import cz.crcs.ectester.standalone.consts.KeyAgreementIdent; -import cz.crcs.ectester.standalone.consts.KeyPairGeneratorIdent; -import cz.crcs.ectester.standalone.consts.SignatureIdent; -import cz.crcs.ectester.standalone.test.base.*; - -import javax.crypto.KeyAgreement; -import java.security.KeyPairGenerator; -import java.security.Signature; -import java.security.interfaces.ECPrivateKey; -import java.security.spec.ECParameterSpec; -import java.util.*; -import java.util.stream.Collectors; - -/** - * @author David Hofman - */ -public class StandalonePerformanceSuite extends StandaloneTestSuite { - private final int count = 100; - - public StandalonePerformanceSuite(TestWriter writer, ECTesterStandalone.Config cfg, TreeCommandLine cli) { - super(writer, cfg, cli, "performance", "The performance test suite measures performance of KeyPair generation, KeyAgreement and Signature operations.", - "Supports options:", - "\t - gt/kpg-type (select multiple types by separating them with commas)", - "\t - kt/ka-type (select multiple types by separating them with commas)", - "\t - st/sig-type (select multiple types by separating them with commas)", - "\t - key-type"); - } - - @Override - protected void runTests() throws Exception { - String kpgAlgo = cli.getOptionValue("test.kpg-type"); - String kaAlgo = cli.getOptionValue("test.ka-type"); - String sigAlgo = cli.getOptionValue("test.sig-type"); - String keyAlgo = cli.getOptionValue("test.key-type", "AES"); - - List<String> kpgTypes = kpgAlgo != null ? Arrays.asList(kpgAlgo.split(",")) : new ArrayList<>(); - List<String> kaTypes = kaAlgo != null ? Arrays.asList(kaAlgo.split(",")) : new ArrayList<>(); - List<String> sigTypes = sigAlgo != null ? Arrays.asList(sigAlgo.split(",")) : new ArrayList<>(); - - List<KeyPairGeneratorIdent> kpgIdents = new LinkedList<>(); - if (kpgAlgo == null) { - // try EC, if not, fail with: need to specify kpg algo. - Optional<KeyPairGeneratorIdent> kpgIdentOpt = cfg.selected.getKPGs().stream() - .filter((ident) -> ident.contains("EC")) - .findFirst(); - if (kpgIdentOpt.isPresent()) { - kpgIdents.add(kpgIdentOpt.get()); - } else { - System.err.println("The default KeyPairGenerator algorithm type of \"EC\" was not found. Need to specify a type."); - return; - } - } else { - // try the specified, if not, fail with: wrong kpg algo/not found. - kpgIdents = cfg.selected.getKPGs().stream() - .filter((ident) -> ident.containsAny(kpgTypes)).collect(Collectors.toList()); - if (kpgIdents.isEmpty()) { - System.err.println("No KeyPairGenerator algorithms of specified types were found."); - return; - } - } - - KeyGeneratorTestable kgtOne = null; - KeyGeneratorTestable kgtOther = null; - ECParameterSpec spec = null; - List<Test> kpgTests = new LinkedList<>(); - for(KeyPairGeneratorIdent kpgIdent : kpgIdents) { - KeyPairGenerator kpg = kpgIdent.getInstance(cfg.selected.getProvider()); - if (cli.hasOption("test.bits")) { - int bits = Integer.parseInt(cli.getOptionValue("test.bits")); - kgtOne = new KeyGeneratorTestable(kpg, bits); - kgtOther = new KeyGeneratorTestable(kpg, bits); - } else if (cli.hasOption("test.named-curve")) { - String curveName = cli.getOptionValue("test.named-curve"); - EC_Curve curve = EC_Store.getInstance().getObject(EC_Curve.class, curveName); - if (curve == null) { - System.err.println("Curve not found: " + curveName); - return; - } - spec = curve.toSpec(); - kgtOne = new KeyGeneratorTestable(kpg, spec); - kgtOther = new KeyGeneratorTestable(kpg, spec); - } else { - kgtOne = new KeyGeneratorTestable(kpg); - kgtOther = new KeyGeneratorTestable(kpg); - } - kpgTests.add(PerformanceTest.repeat(kgtOne, kpgIdent.getName(), count)); - } - runTest(KeyGeneratorTest.expect(kgtOther, Result.ExpectedValue.SUCCESS)); - doTest(CompoundTest.all(Result.ExpectedValue.SUCCESS, "KeyPairGenerator performance tests", kpgTests.toArray(new Test[0]))); - - List<Test> kaTests = new LinkedList<>(); - for (KeyAgreementIdent kaIdent : cfg.selected.getKAs()) { - if (kaAlgo == null || kaIdent.containsAny(kaTypes)) { - KeyAgreement ka = kaIdent.getInstance(cfg.selected.getProvider()); - KeyAgreementTestable testable; - if (kaIdent.requiresKeyAlgo()) { - testable = new KeyAgreementTestable(ka, kgtOne, kgtOther, spec, keyAlgo); - } else { - testable = new KeyAgreementTestable(ka, kgtOne, kgtOther, spec); - } - kaTests.add(PerformanceTest.repeat(testable, kaIdent.getName(), count)); - } - } - if(kaTests.isEmpty()) { - kaTests.add(CompoundTest.all(Result.ExpectedValue.SUCCESS, "None of the specified KeyAgreement types is supported by the library.")); - } - doTest(CompoundTest.all(Result.ExpectedValue.SUCCESS, "KeyAgreement performance tests", kaTests.toArray(new Test[0]))); - - List<Test> sigTests = new LinkedList<>(); - List<Test> sigTestsNoVerification = new LinkedList<>(); - for (SignatureIdent sigIdent : cfg.selected.getSigs()) { - if (sigAlgo == null || sigIdent.containsAny(sigTypes)) { - Signature sig = sigIdent.getInstance(cfg.selected.getProvider()); - sigTests.add(PerformanceTest.repeat(new SignatureTestable(sig, kgtOne, null), sigIdent.getName(),count)); - if(kgtOne.getKeyPair() != null) { - ECPrivateKey signKey = (ECPrivateKey) kgtOne.getKeyPair().getPrivate(); - sigTestsNoVerification.add(PerformanceTest.repeat(new SignatureTestable(sig, signKey, null, null), sigIdent.getName(), count)); - } - } - } - if(sigTestsNoVerification.isEmpty() & !sigTests.isEmpty()) { - sigTestsNoVerification.add(CompoundTest.all(Result.ExpectedValue.SUCCESS, "Signature tests with no verification require a successfully generated private key.")); - } - if(sigTests.isEmpty()) { - sigTests.add(CompoundTest.all(Result.ExpectedValue.SUCCESS, "None of the specified Signature types is supported by the library.")); - sigTestsNoVerification.add(CompoundTest.all(Result.ExpectedValue.SUCCESS, "None of the specified Signature types is supported by the library.")); - } - Test signAndVerify = CompoundTest.all(Result.ExpectedValue.SUCCESS, "Sign and verify", sigTests.toArray(new Test[0])); - Test signOnly = CompoundTest.all(Result.ExpectedValue.SUCCESS, "Sign only, no verification", sigTestsNoVerification.toArray(new Test[0])); - doTest(CompoundTest.all(Result.ExpectedValue.SUCCESS, "Signature performance tests", signAndVerify, signOnly)); - } -} diff --git a/src/cz/crcs/ectester/standalone/test/suites/StandaloneSignatureSuite.java b/src/cz/crcs/ectester/standalone/test/suites/StandaloneSignatureSuite.java deleted file mode 100644 index 94e810e..0000000 --- a/src/cz/crcs/ectester/standalone/test/suites/StandaloneSignatureSuite.java +++ /dev/null @@ -1,87 +0,0 @@ -package cz.crcs.ectester.standalone.test.suites; - -import cz.crcs.ectester.common.cli.TreeCommandLine; -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.util.ECUtil; -import cz.crcs.ectester.data.EC_Store; -import cz.crcs.ectester.standalone.ECTesterStandalone; -import cz.crcs.ectester.standalone.consts.SignatureIdent; -import cz.crcs.ectester.standalone.test.base.SignatureTest; -import cz.crcs.ectester.standalone.test.base.SignatureTestable; - -import java.security.NoSuchAlgorithmException; -import java.security.Signature; -import java.security.interfaces.ECPublicKey; -import java.util.*; - -/** - * @author David Hofman - */ -public class StandaloneSignatureSuite extends StandaloneTestSuite { - public StandaloneSignatureSuite(TestWriter writer, ECTesterStandalone.Config cfg, TreeCommandLine cli) { - super(writer, cfg, cli, "signature", "The signature test suite tests verifying various malformed and well-formed but invalid ECDSA signatures.", - "Supports options:", "\t - st/sig-type"); - } - - @Override - protected void runTests() throws Exception { - String sigAlgo = cli.getOptionValue("test.sig-type"); - - SignatureIdent sigIdent; - if (sigAlgo == null) { - // try ECDSA, if not, fail with: need to specify sig algo. - Optional<SignatureIdent> sigIdentOpt = cfg.selected.getSigs().stream() - .filter((ident) -> ident.contains("ECDSA")) - .findFirst(); - if (sigIdentOpt.isPresent()) { - sigIdent = sigIdentOpt.get(); - } else { - System.err.println("The default Signature algorithm type of \"ECDSA\" was not found. Need to specify a type."); - return; - } - } else { - // try the specified, if not, fail with: wrong sig algo/not found. - Optional<SignatureIdent> sigIdentOpt = cfg.selected.getSigs().stream() - .filter((ident) -> ident.contains(sigAlgo)) - .findFirst(); - if (sigIdentOpt.isPresent()) { - sigIdent = sigIdentOpt.get(); - } else { - System.err.println("The Signature algorithm type of \"" + sigAlgo + "\" was not found."); - return; - } - } - - 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, sigIdent, 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, sigIdent, Result.ExpectedValue.SUCCESS, null); - } - } - - private void ecdsaTest(EC_SigResult sig, SignatureIdent sigIdent, Result.ExpectedValue expected, byte[] defaultData) throws NoSuchAlgorithmException { - ECPublicKey ecpub = ECUtil.toPublicKey(EC_Store.getInstance().getObject(EC_Key.Public.class, sig.getVerifyKey())); - - byte[] data = sig.getSigData(); - if (data == null) { - data = defaultData; - } - - Signature signature = sigIdent.getInstance(cfg.selected.getProvider()); - SignatureTestable testable = new SignatureTestable(signature, ecpub, data, sig.getData(0)); - doTest(CompoundTest.all(Result.ExpectedValue.SUCCESS, "ECDSA test of " + sig.getId() + ".", SignatureTest.expectError(testable, expected))); - } -} diff --git a/src/cz/crcs/ectester/standalone/test/suites/StandaloneTestSuite.java b/src/cz/crcs/ectester/standalone/test/suites/StandaloneTestSuite.java deleted file mode 100644 index e4e0013..0000000 --- a/src/cz/crcs/ectester/standalone/test/suites/StandaloneTestSuite.java +++ /dev/null @@ -1,25 +0,0 @@ -package cz.crcs.ectester.standalone.test.suites; - -import cz.crcs.ectester.common.cli.TreeCommandLine; -import cz.crcs.ectester.common.output.TestWriter; -import cz.crcs.ectester.common.test.TestSuite; -import cz.crcs.ectester.standalone.ECTesterStandalone; -import cz.crcs.ectester.standalone.libs.ProviderECLibrary; - -/** - * @author Jan Jancar johny@neuromancer.sk - */ -public abstract class StandaloneTestSuite extends TestSuite { - TreeCommandLine cli; - ECTesterStandalone.Config cfg; - - public StandaloneTestSuite(TestWriter writer, ECTesterStandalone.Config cfg, TreeCommandLine cli, String name, String... description) { - super(writer, name, description); - this.cfg = cfg; - this.cli = cli; - } - - public ProviderECLibrary getLibrary() { - return cfg.selected; - } -} diff --git a/src/cz/crcs/ectester/standalone/test/suites/StandaloneTestVectorSuite.java b/src/cz/crcs/ectester/standalone/test/suites/StandaloneTestVectorSuite.java deleted file mode 100644 index 1e1889c..0000000 --- a/src/cz/crcs/ectester/standalone/test/suites/StandaloneTestVectorSuite.java +++ /dev/null @@ -1,63 +0,0 @@ -package cz.crcs.ectester.standalone.test.suites; - -import cz.crcs.ectester.common.cli.TreeCommandLine; -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.util.ECUtil; -import cz.crcs.ectester.data.EC_Store; -import cz.crcs.ectester.standalone.ECTesterStandalone; -import cz.crcs.ectester.standalone.consts.KeyAgreementIdent; -import cz.crcs.ectester.standalone.test.base.KeyAgreementTest; -import cz.crcs.ectester.standalone.test.base.KeyAgreementTestable; - -import javax.crypto.KeyAgreement; -import java.io.IOException; -import java.security.interfaces.ECPrivateKey; -import java.security.interfaces.ECPublicKey; -import java.util.Map; - -/** - * @author David Hofman - */ -public class StandaloneTestVectorSuite extends StandaloneTestSuite { - - public StandaloneTestVectorSuite(TestWriter writer, ECTesterStandalone.Config cfg, TreeCommandLine cli) { - super(writer, cfg, cli, "test-vectors", "The test-vectors suite contains a collection of test vectors which test basic ECDH correctness."); - } - - @Override - protected void runTests() throws Exception { - Map<String, EC_KAResult> results = EC_Store.getInstance().getObjects(EC_KAResult.class, "test"); - for (EC_KAResult result : results.values()) { - if(!"DH_PLAIN".equals(result.getKA())) { - continue; - } - - 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."); - } - - ECPrivateKey privkey = onekey instanceof EC_Keypair ? - (ECPrivateKey) ECUtil.toKeyPair((EC_Keypair) onekey).getPrivate() : - ECUtil.toPrivateKey((EC_Key.Private) onekey); - ECPublicKey pubkey = otherkey instanceof EC_Keypair ? - (ECPublicKey) ECUtil.toKeyPair((EC_Keypair) otherkey).getPublic() : - ECUtil.toPublicKey((EC_Key.Public) otherkey); - - KeyAgreementIdent kaIdent = KeyAgreementIdent.get("ECDH"); - KeyAgreement ka = kaIdent.getInstance(cfg.selected.getProvider()); - KeyAgreementTestable testable = new KeyAgreementTestable(ka, privkey, pubkey); - doTest(CompoundTest.all(Result.ExpectedValue.SUCCESS, "Test vector " + result.getId(), KeyAgreementTest.match(testable, result.getData(0)))); - } - } -} diff --git a/src/cz/crcs/ectester/standalone/test/suites/StandaloneTwistSuite.java b/src/cz/crcs/ectester/standalone/test/suites/StandaloneTwistSuite.java deleted file mode 100644 index f182952..0000000 --- a/src/cz/crcs/ectester/standalone/test/suites/StandaloneTwistSuite.java +++ /dev/null @@ -1,120 +0,0 @@ -package cz.crcs.ectester.standalone.test.suites; - -import cz.crcs.ectester.common.cli.TreeCommandLine; -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.ECUtil; -import cz.crcs.ectester.data.EC_Store; -import cz.crcs.ectester.standalone.ECTesterStandalone; -import cz.crcs.ectester.standalone.consts.KeyAgreementIdent; -import cz.crcs.ectester.standalone.consts.KeyPairGeneratorIdent; -import cz.crcs.ectester.standalone.test.base.KeyAgreementTest; -import cz.crcs.ectester.standalone.test.base.KeyAgreementTestable; -import cz.crcs.ectester.standalone.test.base.KeyGeneratorTest; -import cz.crcs.ectester.standalone.test.base.KeyGeneratorTestable; - -import javax.crypto.KeyAgreement; -import java.security.KeyPair; -import java.security.KeyPairGenerator; -import java.security.interfaces.ECPrivateKey; -import java.security.interfaces.ECPublicKey; -import java.security.spec.ECParameterSpec; -import java.util.*; - -/** - * @author David Hofman - */ -public class StandaloneTwistSuite extends StandaloneTestSuite { - public StandaloneTwistSuite(TestWriter writer, ECTesterStandalone.Config cfg, TreeCommandLine cli) { - super(writer, cfg, cli, "twist", "The twist test suite tests whether the library correctly rejects points on the quadratic twist of the curve during ECDH.", - "Supports options:", "\t - gt/kpg-type", "\t - kt/ka-type (select multiple types by separating them with commas)"); - } - - @Override - protected void runTests() throws Exception { - String kpgAlgo = cli.getOptionValue("test.kpg-type"); - String kaAlgo = cli.getOptionValue("test.ka-type"); - List<String> kaTypes = kaAlgo != null ? Arrays.asList(kaAlgo.split(",")) : new ArrayList<>(); - - KeyPairGeneratorIdent kpgIdent; - if (kpgAlgo == null) { - // try EC, if not, fail with: need to specify kpg algo. - Optional<KeyPairGeneratorIdent> kpgIdentOpt = cfg.selected.getKPGs().stream() - .filter((ident) -> ident.contains("EC")) - .findFirst(); - if (kpgIdentOpt.isPresent()) { - kpgIdent = kpgIdentOpt.get(); - } else { - System.err.println("The default KeyPairGenerator algorithm type of \"EC\" was not found. Need to specify a type."); - return; - } - } else { - // try the specified, if not, fail with: wrong kpg algo/not found. - Optional<KeyPairGeneratorIdent> kpgIdentOpt = cfg.selected.getKPGs().stream() - .filter((ident) -> ident.contains(kpgAlgo)) - .findFirst(); - if (kpgIdentOpt.isPresent()) { - kpgIdent = kpgIdentOpt.get(); - } else { - System.err.println("The KeyPairGenerator algorithm type of \"" + kpgAlgo + "\" was not found."); - return; - } - } - - 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(); - - KeyPairGenerator kpg = kpgIdent.getInstance(cfg.selected.getProvider()); - ECParameterSpec spec = curve.toSpec(); - KeyGeneratorTestable kgt = new KeyGeneratorTestable(kpg, spec); - - Test generateSuccess; - Test generate = KeyGeneratorTest.expectError(kgt, Result.ExpectedValue.ANY); - runTest(generate); - KeyPair kp = kgt.getKeyPair(); - if(kp != null) { - generateSuccess = CompoundTest.all(Result.ExpectedValue.SUCCESS, "Generate keypair.", generate); - } else { //If KeyPair generation fails, try generating it on a default curve instead. Use this key only if it has the same domain parameters as our public key. - KeyGeneratorTestable kgtOnDefaultCurve = new KeyGeneratorTestable(kpg, curve.getBits()); - Test generateOnDefaultCurve = KeyGeneratorTest.expectError(kgtOnDefaultCurve, Result.ExpectedValue.ANY); - runTest(generateOnDefaultCurve); - kp = kgtOnDefaultCurve.getKeyPair(); - if(kp != null && ECUtil.equalKeyPairParameters((ECPrivateKey) kp.getPrivate(), ECUtil.toPublicKey(keys.get(0)))) { - generateSuccess = CompoundTest.all(Result.ExpectedValue.SUCCESS, "Generate keypair.", generateOnDefaultCurve); - } else { - Test generateFail = CompoundTest.all(Result.ExpectedValue.SUCCESS, "Generating KeyPair has failed on " + curve.getId() + ". " + "KeyAgreement tests will be skipped.", generate); - doTest(CompoundTest.all(Result.ExpectedValue.SUCCESS, "Twist test of " + curve.getId() + ".", generateFail)); - continue; - } - } - ECPrivateKey ecpriv = (ECPrivateKey) kp.getPrivate(); - - List<Test> allKaTests = new LinkedList<>(); - for (KeyAgreementIdent kaIdent : cfg.selected.getKAs()) { - if (kaAlgo == null || kaIdent.containsAny(kaTypes)) { - List<Test> specificKaTests = new LinkedList<>(); - for (EC_Key.Public pub : keys) { - ECPublicKey ecpub = ECUtil.toPublicKey(pub); - KeyAgreement ka = kaIdent.getInstance(cfg.selected.getProvider()); - KeyAgreementTestable testable = new KeyAgreementTestable(ka, ecpriv, ecpub); - Test keyAgreement = KeyAgreementTest.expectError(testable, Result.ExpectedValue.FAILURE); - specificKaTests.add(CompoundTest.all(Result.ExpectedValue.SUCCESS, pub.getId() + " twist key test.", keyAgreement)); - } - allKaTests.add(CompoundTest.all(Result.ExpectedValue.SUCCESS, "Perform " + kaIdent.getName() + " with public points on twist.", specificKaTests.toArray(new Test[0]))); - } - } - if(allKaTests.isEmpty()) { - allKaTests.add(CompoundTest.all(Result.ExpectedValue.SUCCESS, "None of the specified key agreement types is supported by the library.")); - } - Test tests = CompoundTest.all(Result.ExpectedValue.SUCCESS, "Do tests.", allKaTests.toArray(new Test[0])); - doTest(CompoundTest.greedyAllTry(Result.ExpectedValue.SUCCESS, "Twist test of " + curve.getId() + ".", generateSuccess, tests)); - } - } -} diff --git a/src/cz/crcs/ectester/standalone/test/suites/StandaloneWrongSuite.java b/src/cz/crcs/ectester/standalone/test/suites/StandaloneWrongSuite.java deleted file mode 100644 index 79b0b7d..0000000 --- a/src/cz/crcs/ectester/standalone/test/suites/StandaloneWrongSuite.java +++ /dev/null @@ -1,344 +0,0 @@ -package cz.crcs.ectester.standalone.test.suites; - -import cz.crcs.ectester.applet.EC_Consts; -import cz.crcs.ectester.common.cli.TreeCommandLine; -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.util.ByteUtil; -import cz.crcs.ectester.common.util.ECUtil; -import cz.crcs.ectester.data.EC_Store; -import cz.crcs.ectester.standalone.ECTesterStandalone; -import cz.crcs.ectester.standalone.consts.KeyAgreementIdent; -import cz.crcs.ectester.standalone.consts.KeyPairGeneratorIdent; -import cz.crcs.ectester.standalone.test.base.KeyAgreementTest; -import cz.crcs.ectester.standalone.test.base.KeyAgreementTestable; -import cz.crcs.ectester.standalone.test.base.KeyGeneratorTest; -import cz.crcs.ectester.standalone.test.base.KeyGeneratorTestable; - -import javax.crypto.KeyAgreement; -import java.math.BigInteger; -import java.security.KeyPair; -import java.security.KeyPairGenerator; -import java.security.NoSuchAlgorithmException; -import java.security.interfaces.ECPrivateKey; -import java.security.interfaces.ECPublicKey; -import java.security.spec.*; -import java.util.*; -import java.util.stream.Collectors; - -/** - * @author David Hofman - */ -public class StandaloneWrongSuite extends StandaloneTestSuite { - private KeyAgreementIdent kaIdent; - private KeyPairGenerator kpg; - - public StandaloneWrongSuite(TestWriter writer, ECTesterStandalone.Config cfg, TreeCommandLine cli) { - super(writer, cfg, cli, "wrong", "The wrong curve suite tests whether the library rejects domain parameters which are not curves.", - "Supports options:", - "\t - gt/kpg-type", - "\t - kt/ka-type", - "\t - skip (place this option before the library name to skip tests that can potentially cause a freeze)"); - } - - - @Override - protected void runTests() throws Exception { - String kpgAlgo = cli.getOptionValue("test.kpg-type"); - String kaAlgo = cli.getOptionValue("test.ka-type"); - boolean skip = cli.getArg(1).equalsIgnoreCase("-skip"); - - KeyPairGeneratorIdent kpgIdent; - if (kpgAlgo == null) { - // try EC, if not, fail with: need to specify kpg algo. - Optional<KeyPairGeneratorIdent> kpgIdentOpt = cfg.selected.getKPGs().stream() - .filter((ident) -> ident.contains("EC")) - .findFirst(); - if (kpgIdentOpt.isPresent()) { - kpgIdent = kpgIdentOpt.get(); - } else { - System.err.println("The default KeyPairGenerator algorithm type of \"EC\" was not found. Need to specify a type."); - return; - } - } else { - // try the specified, if not, fail with: wrong kpg algo/not found. - Optional<KeyPairGeneratorIdent> kpgIdentOpt = cfg.selected.getKPGs().stream() - .filter((ident) -> ident.contains(kpgAlgo)) - .findFirst(); - if (kpgIdentOpt.isPresent()) { - kpgIdent = kpgIdentOpt.get(); - } else { - System.err.println("The KeyPairGenerator algorithm type of \"" + kpgAlgo + "\" was not found."); - return; - } - } - kpg = kpgIdent.getInstance(cfg.selected.getProvider()); - - if (kaAlgo == null) { - // try ECDH, if not, fail with: need to specify ka algo. - Optional<KeyAgreementIdent> kaIdentOpt = cfg.selected.getKAs().stream() - .filter((ident) -> ident.contains("ECDH")) - .findFirst(); - if (kaIdentOpt.isPresent()) { - kaIdent = kaIdentOpt.get(); - } else { - System.err.println("The default KeyAgreement algorithm type of \"ECDH\" was not found. Need to specify a type."); - return; - } - } else { - // try the specified, if not, fail with: wrong ka algo/not found. - Optional<KeyAgreementIdent> kaIdentOpt = cfg.selected.getKAs().stream() - .filter((ident) -> ident.contains(kaAlgo)) - .findFirst(); - if (kaIdentOpt.isPresent()) { - kaIdent = kaIdentOpt.get(); - } else { - System.err.println("The KeyAgreement algorithm type of \"" + kaAlgo + "\" was not found."); - return; - } - } - - /* Just do the default run on the wrong curves. - * These should generally fail, the curves aren't curves. - */ - if(!skip) { - Map<String, EC_Curve> wrongCurves = EC_Store.getInstance().getObjects(EC_Curve.class, "wrong"); - for (Map.Entry<String, EC_Curve> e : wrongCurves.entrySet()) { - - EC_Curve curve = e.getValue(); - ECParameterSpec spec = curve.toSpec(); - String type = curve.getField() == javacard.security.KeyPair.ALG_EC_FP ? "FP" : "F2M"; - - //try generating a keypair - KeyGeneratorTestable kgt = new KeyGeneratorTestable(kpg, spec); - Test generate = KeyGeneratorTest.expectError(kgt, Result.ExpectedValue.ANY); - runTest(generate); - KeyPair kp = kgt.getKeyPair(); - if (kp == null) { - Test generateFail = CompoundTest.all(Result.ExpectedValue.SUCCESS, "Generating KeyPair has failed on " + curve.getId() + ".", generate); - doTest(CompoundTest.all(Result.ExpectedValue.SUCCESS, "Wrong curve test of " + curve.getBits() - + "b " + type + ". " + curve.getDesc(), generateFail)); - continue; - } - Test generateSuccess = CompoundTest.all(Result.ExpectedValue.SUCCESS, "Generate keypair.", generate); - ECPrivateKey ecpriv = (ECPrivateKey) kp.getPrivate(); - ECPublicKey ecpub = (ECPublicKey) kp.getPublic(); - - KeyAgreement ka = kaIdent.getInstance(cfg.selected.getProvider()); - KeyAgreementTestable testable = new KeyAgreementTestable(ka, ecpriv, ecpub); - Test ecdh = KeyAgreementTest.expectError(testable, Result.ExpectedValue.FAILURE); - doTest(CompoundTest.all(Result.ExpectedValue.SUCCESS, "Wrong curve test of " + curve.getBits() - + "b " + type + ". " + curve.getDesc(), generateSuccess, ecdh)); - } - } - - /* - * 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 - */ - 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() == javacard.security.KeyPair.ALG_EC_FP).map(Map.Entry::getValue).collect(Collectors.toList()); - Random r = new Random(); - for (EC_Curve curve : curves) { - short bits = curve.getBits(); - final byte[] originalp = curve.getParam(EC_Consts.PARAMETER_FP)[0]; - - curve.setParam(EC_Consts.PARAMETER_FP, new byte[][]{ ByteUtil.hexToBytes("0")}); - Test prime0 = ecdhTest(toCustomSpec(curve),"ECDH with p = 0."); - - curve.setParam(EC_Consts.PARAMETER_FP, new byte[][]{ ByteUtil.hexToBytes("1")}); - Test prime1 = ecdhTest(toCustomSpec(curve),"ECDH with p = 1."); - - short keyHalf = (short) (bits / 2); - BigInteger prime = new BigInteger(keyHalf, 50, r); - BigInteger primePow = prime.pow(2); - byte[] primePowBytes = ECUtil.toByteArray(primePow, bits); - curve.setParam(EC_Consts.PARAMETER_FP, new byte[][]{primePowBytes}); - - Test primePower = ecdhTest(toCustomSpec(curve), "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, bits); - curve.setParam(EC_Consts.PARAMETER_FP, new byte[][]{compositeBytes}); - - Test composite = ecdhTest(toCustomSpec(curve), "ECDH with p = q * s."); - - Test wrongPrime = CompoundTest.all(Result.ExpectedValue.SUCCESS, "Tests with corrupted prime parameter.", prime0 , prime1, primePower, composite ); - - curve.setParam(EC_Consts.PARAMETER_FP, new byte[][] {originalp}); - final byte[][] originalG = curve.getParam(EC_Consts.PARAMETER_G); - - byte[] Gx = new BigInteger(curve.getBits(), r).toByteArray(); - byte[] Gy = new BigInteger(curve.getBits(), r).toByteArray(); - curve.setParam(EC_Consts.PARAMETER_G, new byte[][] {Gx, Gy}); - Test fullRandomG = ecdhTest(toCustomSpec(curve), "ECDH with G = random data."); - - final BigInteger originalBigp = new BigInteger(1, originalp); - byte[] smallerGx = new BigInteger(curve.getBits(), r).mod(originalBigp).toByteArray(); - byte[] smallerGy = new BigInteger(curve.getBits(), r).mod(originalBigp).toByteArray(); - curve.setParam(EC_Consts.PARAMETER_G, new byte[][] {smallerGx, smallerGy}); - Test randomG = ecdhTest(toCustomSpec(curve), "ECDH with G = random data mod p."); - - curve.setParam(EC_Consts.PARAMETER_G, new byte[][] {ByteUtil.hexToBytes("0"), ByteUtil.hexToBytes("0")}); - Test zeroG = ecdhTest(toCustomSpec(curve), "ECDH with G = infinity."); - - Test wrongG = CompoundTest.all(Result.ExpectedValue.SUCCESS, "Tests with corrupted G parameter.", fullRandomG, randomG, zeroG); - - curve.setParam(EC_Consts.PARAMETER_G, originalG); - final byte[] originalR = curve.getParam(EC_Consts.PARAMETER_R)[0]; - final BigInteger originalBigR = new BigInteger(1, originalR); - - List<Test> allRTests = new LinkedList<>(); - if(!skip) { - byte[] RZero = new byte[]{(byte) 0}; - curve.setParam(EC_Consts.PARAMETER_R, new byte[][]{RZero}); - allRTests.add(ecdhTest(toCustomSpec(curve), "ECDH with R = 0.")); - - - byte[] ROne = new byte[]{(byte) 1}; - curve.setParam(EC_Consts.PARAMETER_R, new byte[][]{ROne}); - allRTests.add(ecdhTest(toCustomSpec(curve), "ECDH with R = 1.")); - } - - BigInteger prevPrimeR; - do { - prevPrimeR = BigInteger.probablePrime(originalBigR.bitLength() - 1, r); - } while (prevPrimeR.compareTo(originalBigR) >= 0); - byte[] prevRBytes = ECUtil.toByteArray(prevPrimeR, bits); - curve.setParam(EC_Consts.PARAMETER_R, new byte[][] {prevRBytes}); - allRTests.add(ecdhTest(toCustomSpec(curve), "ECDH with R = some prime (but [r]G != infinity) smaller than original R.")); - - BigInteger nextPrimeR = originalBigR.nextProbablePrime(); - byte[] nextRBytes = ECUtil.toByteArray(nextPrimeR, bits); - curve.setParam(EC_Consts.PARAMETER_R, new byte[][]{nextRBytes}); - allRTests.add(ecdhTest(toCustomSpec(curve), "ECDH with R = some prime (but [r]G != infinity) larger than original R.")); - - byte[] nonprimeRBytes = nextRBytes.clone(); - nonprimeRBytes[nonprimeRBytes.length - 1] ^= 1; - curve.setParam(EC_Consts.PARAMETER_R, new byte[][] {nonprimeRBytes} ); - allRTests.add(ecdhTest(toCustomSpec(curve), "ECDH with R = some composite (but [r]G != infinity).")); - - Test wrongR = CompoundTest.all(Result.ExpectedValue.SUCCESS, "Tests with corrupted R parameter.", allRTests.toArray(new Test[0])); - - curve.setParam(EC_Consts.PARAMETER_R, new byte[][] {originalR}); - - byte[] kRaw = new byte[]{(byte) 0xff}; - curve.setParam(EC_Consts.PARAMETER_K, new byte[][] {kRaw}); - Test bigK = ecdhTest(toCustomSpec(curve), "ECDH with big K."); - - byte[] kZero = new byte[]{(byte) 0}; - curve.setParam(EC_Consts.PARAMETER_K, new byte[][]{kZero}); - Test zeroK = ecdhTest(toCustomSpec(curve), "ECDH with K = 0."); - - Test wrongK = CompoundTest.all(Result.ExpectedValue.SUCCESS, "Tests with corrupted K parameter.", bigK, zeroK); - doTest(CompoundTest.all(Result.ExpectedValue.SUCCESS, "Tests of " + bits + "b " + "FP", wrongPrime, wrongG, wrongR , wrongK)); - } - - - /* - * For binary field: - * - e1 = e2 = e3 = 0 - * - e1, e2 or e3 is larger than m. - */ - curveMap = EC_Store.getInstance().getObjects(EC_Curve.class, "secg"); - curves = curveMap.entrySet().stream().filter((e) -> e.getKey().endsWith("r1") && - e.getValue().getField() == javacard.security.KeyPair.ALG_EC_F2M).map(Map.Entry::getValue).collect(Collectors.toList()); - for (EC_Curve curve : curves) { - short bits = curve.getBits(); - byte[][] coeffBytes; - - - coeffBytes = new byte[][]{ - ByteUtil.shortToBytes(bits), - ByteUtil.shortToBytes((short) 0), - ByteUtil.shortToBytes((short) 0), - ByteUtil.shortToBytes((short) 0)}; - curve.setParam(EC_Consts.PARAMETER_F2M, coeffBytes); - Test coeff0 = ecdhTest(toCustomSpec(curve), "ECDH with wrong field polynomial: x^"); - - short e1 = (short) (2 * bits); - short e2 = (short) (3 * bits); - short e3 = (short) (4 * bits); - coeffBytes = new byte[][]{ - ByteUtil.shortToBytes(bits), - ByteUtil.shortToBytes(e1), - ByteUtil.shortToBytes(e2), - ByteUtil.shortToBytes(e3)}; - curve.setParam(EC_Consts.PARAMETER_F2M, coeffBytes); - Test coeffLarger = ecdhTest(toCustomSpec(curve), "ECDH with wrong field poly, powers larger than " + bits); - - doTest(CompoundTest.all(Result.ExpectedValue.SUCCESS, "Tests with corrupted field polynomial parameter over " + curve.getBits() + "b F2M", coeff0, coeffLarger)); - } - } - - private Test ecdhTest(ECParameterSpec spec, String desc) throws NoSuchAlgorithmException { - //generate KeyPair - KeyGeneratorTestable kgt = new KeyGeneratorTestable(kpg, spec); - Test generate = KeyGeneratorTest.expectError(kgt, Result.ExpectedValue.FAILURE); - runTest(generate); - KeyPair kp = kgt.getKeyPair(); - if(kp == null) { - return CompoundTest.all(Result.ExpectedValue.SUCCESS, desc, generate); - } - ECPublicKey pub = (ECPublicKey) kp.getPublic(); - ECPrivateKey priv = (ECPrivateKey) kp.getPrivate(); - - //perform ECDH - KeyAgreement ka = kaIdent.getInstance(cfg.selected.getProvider()); - KeyAgreementTestable testable = new KeyAgreementTestable(ka, priv, pub); - Test ecdh = KeyAgreementTest.expect(testable, Result.ExpectedValue.FAILURE); - return CompoundTest.all(Result.ExpectedValue.SUCCESS, desc, generate, ecdh); - } - - //constructs EllipticCurve from EC_Curve even if the parameters of the curve are wrong - private EllipticCurve toCustomCurve(EC_Curve curve) { - ECField field; - if (curve.getField() == javacard.security.KeyPair.ALG_EC_FP) { - field = new CustomECFieldFp(new BigInteger(1, curve.getData(0))); - } else { - byte[][] fieldData = curve.getParam(EC_Consts.PARAMETER_F2M); - int m = ByteUtil.getShort(fieldData[0], 0); - int e1 = ByteUtil.getShort(fieldData[1], 0); - int e2 = ByteUtil.getShort(fieldData[2], 0); - int e3 = ByteUtil.getShort(fieldData[3], 0); - int[] powers; - if (e2 == 0 && e3 == 0) { - powers = new int[]{e1}; - } else { - powers = new int[]{e1, e2, e3}; - } - field = new CustomECFieldF2m(m, powers); - } - - BigInteger a = new BigInteger(1, curve.getParam(EC_Consts.PARAMETER_A)[0]); - BigInteger b = new BigInteger(1, curve.getParam(EC_Consts.PARAMETER_B)[0]); - - return new CustomEllipticCurve(field, a, b); - } - - //constructs ECParameterSpec from EC_Curve even if the parameters of the curve are wrong - private ECParameterSpec toCustomSpec(EC_Curve curve) { - EllipticCurve customCurve = toCustomCurve(curve); - - byte[][] G = curve.getParam(EC_Consts.PARAMETER_G); - BigInteger gx = new BigInteger(1, G[0]); - BigInteger gy = new BigInteger(1, G[1]); - ECPoint generator = new ECPoint(gx, gy); - - BigInteger n = new BigInteger(1, curve.getParam(EC_Consts.PARAMETER_R)[0]); - - int h = new BigInteger(1, curve.getParam(EC_Consts.PARAMETER_K)[0]).intValue(); - return new CustomECParameterSpec(customCurve, generator, n, h); - } -} |
