From 9bce1e13ec136c06650868acf3438e789e366d5f Mon Sep 17 00:00:00 2001 From: J08nY Date: Mon, 27 Nov 2017 23:19:48 +0100 Subject: Add a basic NativeECLibrary interface. --- src/cz/crcs/ectester/standalone/libs/TomcryptLib.java | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 src/cz/crcs/ectester/standalone/libs/TomcryptLib.java (limited to 'src/cz/crcs/ectester/standalone/libs/TomcryptLib.java') diff --git a/src/cz/crcs/ectester/standalone/libs/TomcryptLib.java b/src/cz/crcs/ectester/standalone/libs/TomcryptLib.java new file mode 100644 index 0000000..31d6812 --- /dev/null +++ b/src/cz/crcs/ectester/standalone/libs/TomcryptLib.java @@ -0,0 +1,16 @@ +package cz.crcs.ectester.standalone.libs; + +import java.security.Provider; + +/** + * @author Jan Jancar johny@neuromancer.sk + */ +public class TomcryptLib extends NativeECLibrary { + + public TomcryptLib() { + super("tomcrypt", "libtomcrypt"); + } + + @Override + public native Provider getProvider(); +} -- cgit v1.2.3-70-g09d2 From e22139e18d28906f9533a1dc31e0622080b5f35c Mon Sep 17 00:00:00 2001 From: J08nY Date: Tue, 28 Nov 2017 00:25:54 +0100 Subject: Add ECDH testing to standalone part. --- .../ectester/standalone/ECTesterStandalone.java | 112 +++++++++++++++------ .../crcs/ectester/standalone/libs/ECLibrary.java | 4 +- .../ectester/standalone/libs/NativeECLibrary.java | 54 +--------- .../standalone/libs/ProviderECLibrary.java | 15 +-- .../crcs/ectester/standalone/libs/TomcryptLib.java | 2 +- 5 files changed, 100 insertions(+), 87 deletions(-) (limited to 'src/cz/crcs/ectester/standalone/libs/TomcryptLib.java') diff --git a/src/cz/crcs/ectester/standalone/ECTesterStandalone.java b/src/cz/crcs/ectester/standalone/ECTesterStandalone.java index e36ffcd..ec681c7 100644 --- a/src/cz/crcs/ectester/standalone/ECTesterStandalone.java +++ b/src/cz/crcs/ectester/standalone/ECTesterStandalone.java @@ -17,11 +17,9 @@ import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; +import javax.crypto.KeyAgreement; import java.io.IOException; -import java.security.InvalidAlgorithmParameterException; -import java.security.KeyPair; -import java.security.KeyPairGenerator; -import java.security.NoSuchAlgorithmException; +import java.security.*; import java.security.interfaces.ECPrivateKey; import java.security.interfaces.ECPublicKey; import java.security.spec.ECParameterSpec; @@ -87,9 +85,13 @@ public class ECTesterStandalone { export(); } - } catch (ParseException | NoSuchAlgorithmException | IOException ex) { + } catch (ParseException | IOException ex) { System.err.println(ex.getMessage()); } catch (InvalidAlgorithmParameterException e) { + System.err.println("Invalid algorithm parameter: " + e.getMessage()); + } catch (NoSuchAlgorithmException nsaex) { + System.err.println("Algorithm not supported by the selected library: " + nsaex.getMessage()); + } catch (InvalidKeyException e) { e.printStackTrace(); } } @@ -103,6 +105,9 @@ public class ECTesterStandalone { Options ecdhOpts = new Options(); ecdhOpts.addOption(Option.builder("t").longOpt("type").desc("Set KeyAgreement object [type].").hasArg().argName("type").optionalArg(false).build()); + ecdhOpts.addOption(Option.builder("n").longOpt("amount").hasArg().argName("amount").optionalArg(false).desc("Do ECDH [amount] times.").build()); + ecdhOpts.addOption(Option.builder("b").longOpt("bits").hasArg().argName("n").optionalArg(false).desc("What size of curve to use.").build()); + ecdhOpts.addOption(Option.builder("nc").longOpt("named-curve").desc("Use a named curve, from CurveDB: ").hasArg().argName("cat/id").build()); ParserOptions ecdh = new ParserOptions(new DefaultParser(), ecdhOpts); actions.put("ecdh", ecdh); @@ -156,11 +161,11 @@ public class ECTesterStandalone { if (!kpgs.isEmpty()) { System.out.println("\t\t- KeyPairGenerators: " + String.join(",", kpgs.stream().map(KeyPairGeneratorIdent::getName).collect(Collectors.toList()))); } - Set eckas = lib.getECKAs(); + Set eckas = lib.getKAs(); if (!eckas.isEmpty()) { System.out.println("\t\t- KeyAgreements: " + String.join(",", eckas.stream().map(KeyAgreementIdent::getName).collect(Collectors.toList()))); } - Set sigs = lib.getECSigs(); + Set sigs = lib.getSigs(); if (!eckas.isEmpty()) { System.out.println("\t\t- Signatures: " + String.join(",", sigs.stream().map(SignatureIdent::getName).collect(Collectors.toList()))); } @@ -171,8 +176,68 @@ public class ECTesterStandalone { /** * */ - private void ecdh() { + private void ecdh() throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException { + if (cfg.selected instanceof ProviderECLibrary) { + ProviderECLibrary lib = (ProviderECLibrary) cfg.selected; + + String algo = cli.getOptionValue("ecdh.type", "ECDH"); + KeyAgreementIdent kaIdent = null; + for (KeyAgreementIdent ident : lib.getKAs()) { + if (ident.contains(algo)) { + kaIdent = ident; + break; + } + } + + KeyPairGeneratorIdent kpIdent = null; + for (KeyPairGeneratorIdent ident : lib.getKPGs()) { + if (ident.contains("EC")) { + kpIdent = ident; + break; + } + } + + if (kaIdent == null || kpIdent == null) { + throw new NoSuchAlgorithmException(algo); + } else { + KeyAgreement ka = kaIdent.getInstance(lib.getProvider()); + KeyPairGenerator kpg = kpIdent.getInstance(lib.getProvider()); + if (cli.hasOption("ecdh.bits")) { + int bits = Integer.parseInt(cli.getOptionValue("ecdh.bits")); + kpg.initialize(bits); + } else if (cli.hasOption("ecdh.named-curve")) { + String curveName = cli.getOptionValue("ecdh.named-curve"); + EC_Curve curve = dataStore.getObject(EC_Curve.class, curveName); + if (curve == null) { + System.err.println("Curve not found: " + curveName); + return; + } + kpg.initialize(curve.toSpec()); + } + System.out.println("index;nanotime;pubW;privS;secret"); + + int amount = Integer.parseInt(cli.getOptionValue("ecdh.amount", "1")); + for (int i = 0; i < amount; ++i) { + KeyPair one = kpg.genKeyPair(); + KeyPair other = kpg.genKeyPair(); + + ECPrivateKey privkey = (ECPrivateKey) one.getPrivate(); + ECPublicKey pubkey = (ECPublicKey) other.getPublic(); + + long elapsed = -System.nanoTime(); + ka.init(privkey); + ka.doPhase(pubkey, true); + elapsed += System.nanoTime(); + byte[] result = ka.generateSecret(); + + String pub = ByteUtil.bytesToHex(ECUtil.toX962Uncompressed(pubkey.getW()), false); + String priv = ByteUtil.bytesToHex(privkey.getS().toByteArray(), false); + String dh = ByteUtil.bytesToHex(result, false); + System.out.println(String.format("%d;%d;%s;%s;%s", i, elapsed, pub, priv, dh)); + } + } + } } /** @@ -187,10 +252,10 @@ public class ECTesterStandalone { */ private void generate() throws NoSuchAlgorithmException, InvalidAlgorithmParameterException { if (cfg.selected instanceof ProviderECLibrary) { - ProviderECLibrary jlib = (ProviderECLibrary) cfg.selected; + ProviderECLibrary lib = (ProviderECLibrary) cfg.selected; KeyPairGeneratorIdent ident = null; String algo = cli.getOptionValue("generate.type", "EC"); - for (KeyPairGeneratorIdent kpIdent : jlib.getKPGs()) { + for (KeyPairGeneratorIdent kpIdent : lib.getKPGs()) { if (kpIdent.contains(algo)) { ident = kpIdent; break; @@ -199,7 +264,7 @@ public class ECTesterStandalone { if (ident == null) { throw new NoSuchAlgorithmException(algo); } else { - KeyPairGenerator kpg = ident.getInstance(jlib.getProvider()); + KeyPairGenerator kpg = ident.getInstance(lib.getProvider()); if (cli.hasOption("generate.bits")) { int bits = Integer.parseInt(cli.getOptionValue("generate.bits")); kpg.initialize(bits); @@ -212,7 +277,7 @@ public class ECTesterStandalone { } kpg.initialize(curve.toSpec()); } - System.out.println("index;time;pubW;privS"); + System.out.println("index;nanotime;pubW;privS"); int amount = Integer.parseInt(cli.getOptionValue("generate.amount", "1")); for (int i = 0; i < amount; ++i) { @@ -224,7 +289,7 @@ public class ECTesterStandalone { String pub = ByteUtil.bytesToHex(ECUtil.toX962Uncompressed(publicKey.getW()), false); String priv = ByteUtil.bytesToHex(privateKey.getS().toByteArray(), false); - System.out.println(String.format("%d;%d;%s;%s", i, elapsed / 1000000, pub, priv)); + System.out.println(String.format("%d;%d;%s;%s", i, elapsed, pub, priv)); } } } @@ -242,10 +307,10 @@ public class ECTesterStandalone { */ private void export() throws NoSuchAlgorithmException, IOException { if (cfg.selected instanceof ProviderECLibrary) { - ProviderECLibrary jlib = (ProviderECLibrary) cfg.selected; + ProviderECLibrary lib = (ProviderECLibrary) cfg.selected; KeyPairGeneratorIdent ident = null; String algo = cli.getOptionValue("export.type", "EC"); - for (KeyPairGeneratorIdent kpIdent : jlib.getKPGs()) { + for (KeyPairGeneratorIdent kpIdent : lib.getKPGs()) { if (kpIdent.contains(algo)) { ident = kpIdent; break; @@ -254,7 +319,7 @@ public class ECTesterStandalone { if (ident == null) { throw new NoSuchAlgorithmException(algo); } else { - KeyPairGenerator kpg = ident.getInstance(jlib.getProvider()); + KeyPairGenerator kpg = ident.getInstance(lib.getProvider()); if (cli.hasOption("export.bits")) { int bits = Integer.parseInt(cli.getOptionValue("export.bits")); kpg.initialize(bits); @@ -287,23 +352,14 @@ public class ECTesterStandalone { } boolean readOptions(TreeCommandLine cli) { - if (cli.isNext("generate")) { - if (!cli.hasArg(-1)) { - System.err.println("Missing library name argument."); - return false; - } - - if (cli.hasOption("generate.bits") && cli.hasOption("generate.named-curve")) { - System.err.println("You can only specify bitsize or a named curve, nor both."); - return false; - } - } else if (cli.isNext("export")) { + if (cli.isNext("generate") || cli.isNext("export") || cli.isNext("ecdh")) { if (!cli.hasArg(-1)) { System.err.println("Missing library name argument."); return false; } - if (cli.hasOption("export.bits") && cli.hasOption("export.named-curve")) { + String next = cli.getNextName(); + if (cli.hasOption(next + ".bits") && cli.hasOption(next + ".named-curve")) { System.err.println("You can only specify bitsize or a named curve, nor both."); return false; } diff --git a/src/cz/crcs/ectester/standalone/libs/ECLibrary.java b/src/cz/crcs/ectester/standalone/libs/ECLibrary.java index 7e26dbe..1e73e61 100644 --- a/src/cz/crcs/ectester/standalone/libs/ECLibrary.java +++ b/src/cz/crcs/ectester/standalone/libs/ECLibrary.java @@ -14,9 +14,9 @@ public interface ECLibrary { boolean isInitialized(); - Set getECKAs(); + Set getKAs(); - Set getECSigs(); + Set getSigs(); Set getKPGs(); diff --git a/src/cz/crcs/ectester/standalone/libs/NativeECLibrary.java b/src/cz/crcs/ectester/standalone/libs/NativeECLibrary.java index 40691e6..44fb47b 100644 --- a/src/cz/crcs/ectester/standalone/libs/NativeECLibrary.java +++ b/src/cz/crcs/ectester/standalone/libs/NativeECLibrary.java @@ -1,9 +1,5 @@ package cz.crcs.ectester.standalone.libs; -import cz.crcs.ectester.standalone.consts.KeyAgreementIdent; -import cz.crcs.ectester.standalone.consts.KeyPairGeneratorIdent; -import cz.crcs.ectester.standalone.consts.SignatureIdent; - import java.io.File; import java.io.IOException; import java.net.URL; @@ -13,14 +9,11 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.security.Provider; -import java.util.Collections; -import java.util.Set; /** * @author Jan Jancar johny@neuromancer.sk */ -public abstract class NativeECLibrary implements ECLibrary { - private ProviderECLibrary loaded; +public abstract class NativeECLibrary extends ProviderECLibrary { private String resource; private String libname; @@ -80,52 +73,13 @@ public abstract class NativeECLibrary implements ECLibrary { System.load(libPath.toString()); - loaded = new ProviderECLibrary(getProvider()); - return true; + provider = createProvider(); + return super.initialize(); } catch (IOException ignored) { } return false; } - public abstract Provider getProvider(); - - @Override - public boolean isInitialized() { - return loaded != null && loaded.isInitialized(); - } - - @Override - public Set getECKAs() { - if (!isInitialized()) { - return Collections.emptySet(); - } - return loaded.getECKAs(); - } - - @Override - public Set getECSigs() { - if (!isInitialized()) { - return Collections.emptySet(); - } - return loaded.getECSigs(); - } - - @Override - public Set getKPGs() { - if (!isInitialized()) { - return Collections.emptySet(); - } - return loaded.getKPGs(); - } - - @Override - public String name() { - return loaded.name(); - } - - @Override - public String toString() { - return name(); - } + abstract Provider createProvider(); } diff --git a/src/cz/crcs/ectester/standalone/libs/ProviderECLibrary.java b/src/cz/crcs/ectester/standalone/libs/ProviderECLibrary.java index 879cc16..9108eaf 100644 --- a/src/cz/crcs/ectester/standalone/libs/ProviderECLibrary.java +++ b/src/cz/crcs/ectester/standalone/libs/ProviderECLibrary.java @@ -14,13 +14,16 @@ import java.util.function.Function; /** * @author Jan Jancar johny@neuromancer.sk */ -public class ProviderECLibrary implements ECLibrary { - private Provider provider; - private boolean initialized; +public abstract class ProviderECLibrary implements ECLibrary { + Provider provider; + private boolean initialized = false; + + public ProviderECLibrary() { + + } public ProviderECLibrary(Provider provider) { this.provider = provider; - this.initialized = false; } @Override @@ -60,12 +63,12 @@ public class ProviderECLibrary implements ECLibrary { } @Override - public Set getECKAs() { + public Set getKAs() { return getIdents("KeyAgreement", KeyAgreementIdent::get); } @Override - public Set getECSigs() { + public Set getSigs() { return getIdents("Signature", SignatureIdent::get); } diff --git a/src/cz/crcs/ectester/standalone/libs/TomcryptLib.java b/src/cz/crcs/ectester/standalone/libs/TomcryptLib.java index 31d6812..fe4a79d 100644 --- a/src/cz/crcs/ectester/standalone/libs/TomcryptLib.java +++ b/src/cz/crcs/ectester/standalone/libs/TomcryptLib.java @@ -12,5 +12,5 @@ public class TomcryptLib extends NativeECLibrary { } @Override - public native Provider getProvider(); + native Provider createProvider(); } -- cgit v1.2.3-70-g09d2 From cd117b707bfae0271b86b5c647d2fbc72dd3676c Mon Sep 17 00:00:00 2001 From: J08nY Date: Tue, 28 Nov 2017 22:23:31 +0100 Subject: Implement a basic NativeProvider using libtomcrypt. --- .gitignore | 6 ++- build-standalone.xml | 3 +- nbproject/reader/project.properties | 2 +- nbproject/standalone/project.properties | 2 +- .../ectester/standalone/ECTesterStandalone.java | 11 ++--- .../ectester/standalone/libs/NativeECLibrary.java | 22 ++++++--- .../crcs/ectester/standalone/libs/TomcryptLib.java | 2 +- src/cz/crcs/ectester/standalone/libs/jni/Makefile | 48 +++++++++++++++++++ .../standalone/libs/jni/NativeProvider.java | 25 ++++++++++ .../standalone/libs/jni/TomCryptProvider.java | 11 +++++ src/cz/crcs/ectester/standalone/libs/jni/native.h | 54 ++++++++++++++++++++++ .../crcs/ectester/standalone/libs/jni/tomcrypt.c | 40 ++++++++++++++++ src/cz/crcs/ectester/standalone/libs/native.h | 21 --------- 13 files changed, 206 insertions(+), 41 deletions(-) create mode 100644 src/cz/crcs/ectester/standalone/libs/jni/Makefile create mode 100644 src/cz/crcs/ectester/standalone/libs/jni/NativeProvider.java create mode 100644 src/cz/crcs/ectester/standalone/libs/jni/TomCryptProvider.java create mode 100644 src/cz/crcs/ectester/standalone/libs/jni/native.h create mode 100644 src/cz/crcs/ectester/standalone/libs/jni/tomcrypt.c delete mode 100644 src/cz/crcs/ectester/standalone/libs/native.h (limited to 'src/cz/crcs/ectester/standalone/libs/TomcryptLib.java') diff --git a/.gitignore b/.gitignore index 4724134..8390d09 100644 --- a/.gitignore +++ b/.gitignore @@ -4,4 +4,8 @@ /dist/ectester-reader.sh /dist/ectester-reader.bat /dist/ECTesterStandalone.jar -/dist/ECTesterStandalone-dist.jar \ No newline at end of file +/dist/ECTesterStandalone-dist.jar + +/src/**/*.a +/src/**/*.o +/src/**/*.so diff --git a/build-standalone.xml b/build-standalone.xml index 05dc174..447b9b1 100644 --- a/build-standalone.xml +++ b/build-standalone.xml @@ -76,8 +76,9 @@ - + + diff --git a/nbproject/reader/project.properties b/nbproject/reader/project.properties index ac98170..d372fd5 100644 --- a/nbproject/reader/project.properties +++ b/nbproject/reader/project.properties @@ -6,7 +6,7 @@ annotation.processing.source.output=${build.generated.sources.dir}/ap-source-out application.title=ECTesterReader application.vendor=xsvenda build.classes.dir=${build.dir}/classes -build.classes.excludes=**/*.java,**/*.form,**/*.c,**/*.h +build.classes.excludes=**/*.java,**/*.form,**/*.c,**/*.h,**/*.a # This directory is removed when the project is cleaned: build.dir=build build.generated.dir=${build.dir}/generated diff --git a/nbproject/standalone/project.properties b/nbproject/standalone/project.properties index 868bcfa..7714914 100644 --- a/nbproject/standalone/project.properties +++ b/nbproject/standalone/project.properties @@ -6,7 +6,7 @@ annotation.processing.source.output=${build.generated.sources.dir}/ap-source-out application.title=ECTesterStandalone application.vendor=xsvenda build.classes.dir=${build.dir}/classes -build.classes.excludes=**/*.java,**/*.form,**/*.c,**/*.h +build.classes.excludes=**/*.java,**/*.form,**/*.c,**/*.h,**/*.a # This directory is removed when the project is cleaned: build.dir=build build.generated.dir=${build.dir}/generated diff --git a/src/cz/crcs/ectester/standalone/ECTesterStandalone.java b/src/cz/crcs/ectester/standalone/ECTesterStandalone.java index 3ec11ed..de9953a 100644 --- a/src/cz/crcs/ectester/standalone/ECTesterStandalone.java +++ b/src/cz/crcs/ectester/standalone/ECTesterStandalone.java @@ -8,10 +8,7 @@ import cz.crcs.ectester.data.EC_Store; import cz.crcs.ectester.standalone.consts.KeyAgreementIdent; import cz.crcs.ectester.standalone.consts.KeyPairGeneratorIdent; import cz.crcs.ectester.standalone.consts.SignatureIdent; -import cz.crcs.ectester.standalone.libs.BouncyCastleLib; -import cz.crcs.ectester.standalone.libs.ECLibrary; -import cz.crcs.ectester.standalone.libs.ProviderECLibrary; -import cz.crcs.ectester.standalone.libs.SunECLib; +import cz.crcs.ectester.standalone.libs.*; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; @@ -37,7 +34,7 @@ import java.util.stream.Collectors; * @version v0.1.0 */ public class ECTesterStandalone { - private ECLibrary[] libs = new ECLibrary[]{new SunECLib(), new BouncyCastleLib()}; + private ECLibrary[] libs = new ECLibrary[]{new SunECLib(), new BouncyCastleLib(), new TomcryptLib()}; private EC_Store dataStore; private Config cfg; @@ -297,7 +294,6 @@ public class ECTesterStandalone { } else { Signature sig = sigIdent.getInstance(lib.getProvider()); KeyPairGenerator kpg = kpIdent.getInstance(lib.getProvider()); - AlgorithmParameterSpec spec = null; if (cli.hasOption("ecdsa.bits")) { int bits = Integer.parseInt(cli.getOptionValue("ecdsa.bits")); kpg.initialize(bits); @@ -308,8 +304,7 @@ public class ECTesterStandalone { System.err.println("Curve not found: " + curveName); return; } - spec = curve.toSpec(); - kpg.initialize(spec); + kpg.initialize(curve.toSpec()); } System.out.println("index;data;signtime;verifytime;pubW;privS;signature;verified"); diff --git a/src/cz/crcs/ectester/standalone/libs/NativeECLibrary.java b/src/cz/crcs/ectester/standalone/libs/NativeECLibrary.java index 44fb47b..5d1b9d7 100644 --- a/src/cz/crcs/ectester/standalone/libs/NativeECLibrary.java +++ b/src/cz/crcs/ectester/standalone/libs/NativeECLibrary.java @@ -15,11 +15,13 @@ import java.security.Provider; */ public abstract class NativeECLibrary extends ProviderECLibrary { private String resource; - private String libname; + private String[] requriements; - public NativeECLibrary(String resource, String libname) { + public static String LIB_RESOURCE_DIR = "/cz/crcs/ectester/standalone/libs/jni/"; + + public NativeECLibrary(String resource, String... requirements) { this.resource = resource; - this.libname = libname; + this.requriements = requirements; } @Override @@ -33,8 +35,10 @@ public abstract class NativeECLibrary extends ProviderECLibrary { } else { suffix = "so"; if (System.getProperty("os.name").startsWith("Linux")) { - appData = Paths.get(System.getenv("XDG_DATA_HOME")); - if (appData == null) { + String dataHome = System.getenv("XDG_DATA_HOME"); + if (dataHome != null) { + appData = Paths.get(dataHome); + } else { appData = Paths.get(System.getProperty("user.home"), ".local", "share"); } } else { @@ -43,10 +47,10 @@ public abstract class NativeECLibrary extends ProviderECLibrary { } Path libDir = appData.resolve("ECTesterStandalone"); File libDirFile = libDir.toFile(); - Path libPath = libDir.resolve(libname + "." + suffix); + Path libPath = libDir.resolve(resource + "." + suffix); File libFile = libPath.toFile(); - URL jarURL = NativeECLibrary.class.getResource("/cz/crcs/ectester/standalone/libs/" + resource + "." + suffix); + URL jarURL = NativeECLibrary.class.getResource(LIB_RESOURCE_DIR + resource + "." + suffix); if (jarURL == null) { return false; } @@ -71,6 +75,10 @@ public abstract class NativeECLibrary extends ProviderECLibrary { } jarConnection.getInputStream().close(); + for (String requirement : requriements) { + System.loadLibrary(requirement); + } + System.load(libPath.toString()); provider = createProvider(); diff --git a/src/cz/crcs/ectester/standalone/libs/TomcryptLib.java b/src/cz/crcs/ectester/standalone/libs/TomcryptLib.java index fe4a79d..49e810c 100644 --- a/src/cz/crcs/ectester/standalone/libs/TomcryptLib.java +++ b/src/cz/crcs/ectester/standalone/libs/TomcryptLib.java @@ -8,7 +8,7 @@ import java.security.Provider; public class TomcryptLib extends NativeECLibrary { public TomcryptLib() { - super("tomcrypt", "libtomcrypt"); + super("tomcrypt_provider", "tommath", "tomcrypt"); } @Override diff --git a/src/cz/crcs/ectester/standalone/libs/jni/Makefile b/src/cz/crcs/ectester/standalone/libs/jni/Makefile new file mode 100644 index 0000000..837078c --- /dev/null +++ b/src/cz/crcs/ectester/standalone/libs/jni/Makefile @@ -0,0 +1,48 @@ +ifeq ($(JAVA_HOME),) +ifeq ($(OS),Windows_NT) +which = $(shell where $1) +else +which = $(shell which $1) +endif +JAVAC ?= $(realpath $(call which,javac)) +JAVA_HOME = $(abspath $(dir $(JAVAC))..) +endif + +ifneq ($(JAVA_HOME),) +JNI_INCLUDEDIR ?= $(JAVA_HOME)/include +endif + +ifeq ($(JNI_INCLUDEDIR),) +$(error could not determine JNI include dir, try specifying either \ + JAVA_HOME or JNI_INCLUDEDIR) +endif + +TARGETTRIPLET := $(shell $(CC) -dumpmachine) +ifeq ($(JNI_PLATFORM),) +ifeq ($(findstring mingw,$(TARGETTRIPLET)),mingw) +JNI_PLATFORM:= win32 +else +ifeq ($(findstring linux,$(TARGETTRIPLET)),linux) +JNI_PLATFORM:= linux +# add more checks here +endif +endif +endif + +JNI_PLATFORMINCLUDEDIR ?= $(JNI_INCLUDEDIR)/$(JNI_PLATFORM) + + + +all: tomcrypt_provider.so + +tomcrypt_provider.so: tomcrypt.o + gcc -DLTM_DESC -DUSE_LTM -fPIC -shared -o $@ $< -ltommath -ltomcrypt + +%.o: %.c + gcc -fPIC -I"$(JNI_INCLUDEDIR)" -I"$(JNI_PLATFORMINCLUDEDIR)" -I. -c $< + +clean: + rm -rf *.o + rm -rf *.so + +.PHONY: all clean \ No newline at end of file diff --git a/src/cz/crcs/ectester/standalone/libs/jni/NativeProvider.java b/src/cz/crcs/ectester/standalone/libs/jni/NativeProvider.java new file mode 100644 index 0000000..43b7827 --- /dev/null +++ b/src/cz/crcs/ectester/standalone/libs/jni/NativeProvider.java @@ -0,0 +1,25 @@ +package cz.crcs.ectester.standalone.libs.jni; + +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.security.Provider; + +/** + * @author Jan Jancar johny@neuromancer.sk + */ +public abstract class NativeProvider extends Provider { + + public NativeProvider(String name, double version, String info) { + super(name, version, info); + + AccessController.doPrivileged(new PrivilegedAction() { + public Object run() { + setup(); + return null; + } + }); + } + + abstract void setup(); + +} diff --git a/src/cz/crcs/ectester/standalone/libs/jni/TomCryptProvider.java b/src/cz/crcs/ectester/standalone/libs/jni/TomCryptProvider.java new file mode 100644 index 0000000..01e4c17 --- /dev/null +++ b/src/cz/crcs/ectester/standalone/libs/jni/TomCryptProvider.java @@ -0,0 +1,11 @@ +package cz.crcs.ectester.standalone.libs.jni; + +public class TomCryptProvider extends NativeProvider { + + public TomCryptProvider(String name, double version, String info) { + super(name, version, info); + } + + @Override + native void setup(); +} diff --git a/src/cz/crcs/ectester/standalone/libs/jni/native.h b/src/cz/crcs/ectester/standalone/libs/jni/native.h new file mode 100644 index 0000000..83ef841 --- /dev/null +++ b/src/cz/crcs/ectester/standalone/libs/jni/native.h @@ -0,0 +1,54 @@ +/* DO NOT EDIT THIS FILE - it is machine generated */ +#include +/* Header for class cz_crcs_ectester_standalone_libs_TomcryptLib */ + +#ifndef _Included_cz_crcs_ectester_standalone_libs_TomcryptLib +#define _Included_cz_crcs_ectester_standalone_libs_TomcryptLib +#ifdef __cplusplus +extern "C" { +#endif +/* + * Class: cz_crcs_ectester_standalone_libs_TomcryptLib + * Method: createProvider + * Signature: ()Ljava/security/Provider; + */ +JNIEXPORT jobject JNICALL Java_cz_crcs_ectester_standalone_libs_TomcryptLib_createProvider + (JNIEnv *, jobject); + +#ifdef __cplusplus +} +#endif +#endif +/* Header for class cz_crcs_ectester_standalone_libs_jni_TomCryptProvider */ + +#ifndef _Included_cz_crcs_ectester_standalone_libs_jni_TomCryptProvider +#define _Included_cz_crcs_ectester_standalone_libs_jni_TomCryptProvider +#ifdef __cplusplus +extern "C" { +#endif +#undef cz_crcs_ectester_standalone_libs_jni_TomCryptProvider_serialVersionUID +#define cz_crcs_ectester_standalone_libs_jni_TomCryptProvider_serialVersionUID 1421746759512286392LL +#undef cz_crcs_ectester_standalone_libs_jni_TomCryptProvider_MAX_ARRAY_SIZE +#define cz_crcs_ectester_standalone_libs_jni_TomCryptProvider_MAX_ARRAY_SIZE 2147483639L +#undef cz_crcs_ectester_standalone_libs_jni_TomCryptProvider_KEYS +#define cz_crcs_ectester_standalone_libs_jni_TomCryptProvider_KEYS 0L +#undef cz_crcs_ectester_standalone_libs_jni_TomCryptProvider_VALUES +#define cz_crcs_ectester_standalone_libs_jni_TomCryptProvider_VALUES 1L +#undef cz_crcs_ectester_standalone_libs_jni_TomCryptProvider_ENTRIES +#define cz_crcs_ectester_standalone_libs_jni_TomCryptProvider_ENTRIES 2L +#undef cz_crcs_ectester_standalone_libs_jni_TomCryptProvider_serialVersionUID +#define cz_crcs_ectester_standalone_libs_jni_TomCryptProvider_serialVersionUID 4112578634029874840LL +#undef cz_crcs_ectester_standalone_libs_jni_TomCryptProvider_serialVersionUID +#define cz_crcs_ectester_standalone_libs_jni_TomCryptProvider_serialVersionUID -4298000515446427739LL +/* + * Class: cz_crcs_ectester_standalone_libs_jni_TomCryptProvider + * Method: setup + * Signature: ()V + */ +JNIEXPORT void JNICALL Java_cz_crcs_ectester_standalone_libs_jni_TomCryptProvider_setup + (JNIEnv *, jobject); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/src/cz/crcs/ectester/standalone/libs/jni/tomcrypt.c b/src/cz/crcs/ectester/standalone/libs/jni/tomcrypt.c new file mode 100644 index 0000000..43ae06b --- /dev/null +++ b/src/cz/crcs/ectester/standalone/libs/jni/tomcrypt.c @@ -0,0 +1,40 @@ +#include "native.h" +#include +#define LTM_DESC +#include + +JNIEXPORT jobject JNICALL Java_cz_crcs_ectester_standalone_libs_TomcryptLib_createProvider(JNIEnv *env, jobject this) { + jclass provider_class = (*env)->FindClass(env, "cz/crcs/ectester/standalone/libs/jni/TomCryptProvider"); + + jmethodID init = (*env)->GetMethodID(env, provider_class, "", "(Ljava/lang/String;DLjava/lang/String;)V"); + if (init == NULL) { + return NULL; + } + jstring name = (*env)->NewStringUTF(env, "libtomcrypt " SCRYPT); + double version = strtod(SCRYPT, NULL); + return (*env)->NewObject(env, provider_class, init, name, version, name); +} + +JNIEXPORT void JNICALL Java_cz_crcs_ectester_standalone_libs_jni_TomCryptProvider_setup(JNIEnv *env, jobject this) { + ltc_mp = ltm_desc; + /* Just test ecc key generation at this time. */ + ecc_key mykey; + prng_state prng; + int err; + /* register yarrow */ + if (register_prng(&yarrow_desc) == -1) { + printf("Error registering Yarrow\n"); + return; + } + /* setup the PRNG */ + if ((err = rng_make_prng(128, find_prng("yarrow"), &prng, NULL)) != CRYPT_OK) { + printf("Error setting up PRNG, %s\n", error_to_string(err)); + return; + } + /* make a 192-bit ECC key */ + if ((err = ecc_make_key(&prng, find_prng("yarrow"), 24, &mykey)) != CRYPT_OK) { + printf("Error making key: %s\n", error_to_string(err)); + return; + } + return; +} \ No newline at end of file diff --git a/src/cz/crcs/ectester/standalone/libs/native.h b/src/cz/crcs/ectester/standalone/libs/native.h deleted file mode 100644 index 979f04a..0000000 --- a/src/cz/crcs/ectester/standalone/libs/native.h +++ /dev/null @@ -1,21 +0,0 @@ -/* DO NOT EDIT THIS FILE - it is machine generated */ -#include -/* Header for class cz_crcs_ectester_standalone_libs_TomcryptLib */ - -#ifndef _Included_cz_crcs_ectester_standalone_libs_TomcryptLib -#define _Included_cz_crcs_ectester_standalone_libs_TomcryptLib -#ifdef __cplusplus -extern "C" { -#endif -/* - * Class: cz_crcs_ectester_standalone_libs_TomcryptLib - * Method: getProvider - * Signature: ()Ljava/security/Provider; - */ -JNIEXPORT jobject JNICALL Java_cz_crcs_ectester_standalone_libs_TomcryptLib_getProvider - (JNIEnv *, jobject); - -#ifdef __cplusplus -} -#endif -#endif -- cgit v1.2.3-70-g09d2 From 03265f4cf09b7bb59c09af722b8f44445a635d83 Mon Sep 17 00:00:00 2001 From: J08nY Date: Wed, 29 Nov 2017 02:22:30 +0100 Subject: Add listing of supported curves to standalone libs. --- build-standalone.xml | 4 +-- nbproject/reader/project.properties | 2 +- nbproject/standalone/project.properties | 2 +- .../ectester/standalone/ECTesterStandalone.java | 5 +++ .../ectester/standalone/libs/BouncyCastleLib.java | 14 ++++++++ .../crcs/ectester/standalone/libs/ECLibrary.java | 2 ++ src/cz/crcs/ectester/standalone/libs/SunECLib.java | 14 ++++++++ .../crcs/ectester/standalone/libs/TomcryptLib.java | 4 +++ .../standalone/libs/jni/NativeProvider.java | 8 ++--- src/cz/crcs/ectester/standalone/libs/jni/native.h | 8 +++++ .../crcs/ectester/standalone/libs/jni/tomcrypt.c | 41 +++++++++++++--------- 11 files changed, 78 insertions(+), 26 deletions(-) (limited to 'src/cz/crcs/ectester/standalone/libs/TomcryptLib.java') diff --git a/build-standalone.xml b/build-standalone.xml index 300eec8..6e65c67 100644 --- a/build-standalone.xml +++ b/build-standalone.xml @@ -76,10 +76,10 @@ - + - + diff --git a/nbproject/reader/project.properties b/nbproject/reader/project.properties index d372fd5..21441b3 100644 --- a/nbproject/reader/project.properties +++ b/nbproject/reader/project.properties @@ -6,7 +6,7 @@ annotation.processing.source.output=${build.generated.sources.dir}/ap-source-out application.title=ECTesterReader application.vendor=xsvenda build.classes.dir=${build.dir}/classes -build.classes.excludes=**/*.java,**/*.form,**/*.c,**/*.h,**/*.a +build.classes.excludes=**/*.java,**/*.form,**/*.c,**/*.h,**/*.a,**/*.o,**/Makefile # This directory is removed when the project is cleaned: build.dir=build build.generated.dir=${build.dir}/generated diff --git a/nbproject/standalone/project.properties b/nbproject/standalone/project.properties index 7714914..9fed4c2 100644 --- a/nbproject/standalone/project.properties +++ b/nbproject/standalone/project.properties @@ -6,7 +6,7 @@ annotation.processing.source.output=${build.generated.sources.dir}/ap-source-out application.title=ECTesterStandalone application.vendor=xsvenda build.classes.dir=${build.dir}/classes -build.classes.excludes=**/*.java,**/*.form,**/*.c,**/*.h,**/*.a +build.classes.excludes=**/*.java,**/*.form,**/*.c,**/*.h,**/*.a,**/*.o,**/Makefile # This directory is removed when the project is cleaned: build.dir=build build.generated.dir=${build.dir}/generated diff --git a/src/cz/crcs/ectester/standalone/ECTesterStandalone.java b/src/cz/crcs/ectester/standalone/ECTesterStandalone.java index de9953a..9fca2b6 100644 --- a/src/cz/crcs/ectester/standalone/ECTesterStandalone.java +++ b/src/cz/crcs/ectester/standalone/ECTesterStandalone.java @@ -174,6 +174,11 @@ public class ECTesterStandalone { if (!eckas.isEmpty()) { System.out.println("\t\t- Signatures: " + String.join(",", sigs.stream().map(SignatureIdent::getName).collect(Collectors.toList()))); } + Set curves = lib.getCurves(); + if (!curves.isEmpty()) { + System.out.println("\t\t- Curves: " + String.join(",", curves)); + } + System.out.println(); } } } diff --git a/src/cz/crcs/ectester/standalone/libs/BouncyCastleLib.java b/src/cz/crcs/ectester/standalone/libs/BouncyCastleLib.java index aaf76be..c6600f9 100644 --- a/src/cz/crcs/ectester/standalone/libs/BouncyCastleLib.java +++ b/src/cz/crcs/ectester/standalone/libs/BouncyCastleLib.java @@ -1,7 +1,12 @@ package cz.crcs.ectester.standalone.libs; +import org.bouncycastle.jce.ECNamedCurveTable; import org.bouncycastle.jce.provider.BouncyCastleProvider; +import java.util.Enumeration; +import java.util.Set; +import java.util.TreeSet; + /** * @author Jan Jancar johny@neuromancer.sk */ @@ -11,4 +16,13 @@ public class BouncyCastleLib extends ProviderECLibrary { super(new BouncyCastleProvider()); } + @Override + public Set getCurves() { + Set result = new TreeSet<>(); + Enumeration names = ECNamedCurveTable.getNames(); + while (names.hasMoreElements()) { + result.add((String) names.nextElement()); + } + return result; + } } diff --git a/src/cz/crcs/ectester/standalone/libs/ECLibrary.java b/src/cz/crcs/ectester/standalone/libs/ECLibrary.java index 1e73e61..0f81978 100644 --- a/src/cz/crcs/ectester/standalone/libs/ECLibrary.java +++ b/src/cz/crcs/ectester/standalone/libs/ECLibrary.java @@ -14,6 +14,8 @@ public interface ECLibrary { boolean isInitialized(); + Set getCurves(); + Set getKAs(); Set getSigs(); diff --git a/src/cz/crcs/ectester/standalone/libs/SunECLib.java b/src/cz/crcs/ectester/standalone/libs/SunECLib.java index b64b740..3aec842 100644 --- a/src/cz/crcs/ectester/standalone/libs/SunECLib.java +++ b/src/cz/crcs/ectester/standalone/libs/SunECLib.java @@ -2,6 +2,9 @@ package cz.crcs.ectester.standalone.libs; import sun.security.ec.SunEC; +import java.util.Set; +import java.util.TreeSet; + /** * @author Jan Jancar johny@neuromancer.sk */ @@ -11,4 +14,15 @@ public class SunECLib extends ProviderECLibrary { super(new SunEC()); } + @Override + public Set getCurves() { + String curves = provider.get("AlgorithmParameters.EC SupportedCurves").toString(); + String[] split = curves.split("\\|"); + Set result = new TreeSet<>(); + for (String curve : split) { + String body = curve.split(",")[0].substring(1); + result.add(body); + } + return result; + } } diff --git a/src/cz/crcs/ectester/standalone/libs/TomcryptLib.java b/src/cz/crcs/ectester/standalone/libs/TomcryptLib.java index 49e810c..78db00e 100644 --- a/src/cz/crcs/ectester/standalone/libs/TomcryptLib.java +++ b/src/cz/crcs/ectester/standalone/libs/TomcryptLib.java @@ -1,6 +1,7 @@ package cz.crcs.ectester.standalone.libs; import java.security.Provider; +import java.util.Set; /** * @author Jan Jancar johny@neuromancer.sk @@ -13,4 +14,7 @@ public class TomcryptLib extends NativeECLibrary { @Override native Provider createProvider(); + + @Override + public native Set getCurves(); } diff --git a/src/cz/crcs/ectester/standalone/libs/jni/NativeProvider.java b/src/cz/crcs/ectester/standalone/libs/jni/NativeProvider.java index 53f8b3c..a2233e2 100644 --- a/src/cz/crcs/ectester/standalone/libs/jni/NativeProvider.java +++ b/src/cz/crcs/ectester/standalone/libs/jni/NativeProvider.java @@ -12,11 +12,9 @@ public abstract class NativeProvider extends Provider { public NativeProvider(String name, double version, String info) { super(name, version, info); - AccessController.doPrivileged(new PrivilegedAction() { - public Object run() { - setup(); - return null; - } + AccessController.doPrivileged((PrivilegedAction) () -> { + setup(); + return null; }); } diff --git a/src/cz/crcs/ectester/standalone/libs/jni/native.h b/src/cz/crcs/ectester/standalone/libs/jni/native.h index e4e5009..e607738 100644 --- a/src/cz/crcs/ectester/standalone/libs/jni/native.h +++ b/src/cz/crcs/ectester/standalone/libs/jni/native.h @@ -15,6 +15,14 @@ extern "C" { JNIEXPORT jobject JNICALL Java_cz_crcs_ectester_standalone_libs_TomcryptLib_createProvider (JNIEnv *, jobject); +/* + * Class: cz_crcs_ectester_standalone_libs_TomcryptLib + * Method: getCurves + * Signature: ()Ljava/util/Set; + */ +JNIEXPORT jobject JNICALL Java_cz_crcs_ectester_standalone_libs_TomcryptLib_getCurves + (JNIEnv *, jobject); + #ifdef __cplusplus } #endif diff --git a/src/cz/crcs/ectester/standalone/libs/jni/tomcrypt.c b/src/cz/crcs/ectester/standalone/libs/jni/tomcrypt.c index db1de88..7f8f303 100644 --- a/src/cz/crcs/ectester/standalone/libs/jni/tomcrypt.c +++ b/src/cz/crcs/ectester/standalone/libs/jni/tomcrypt.c @@ -7,49 +7,56 @@ JNIEXPORT jobject JNICALL Java_cz_crcs_ectester_standalone_libs_TomcryptLib_crea jclass provider_class = (*env)->FindClass(env, "cz/crcs/ectester/standalone/libs/jni/NativeProvider$TomCrypt"); jmethodID init = (*env)->GetMethodID(env, provider_class, "", "(Ljava/lang/String;DLjava/lang/String;)V"); - if (init == NULL) { - return NULL; - } + jstring name = (*env)->NewStringUTF(env, "libtomcrypt " SCRYPT); double version = strtod(SCRYPT, NULL); + return (*env)->NewObject(env, provider_class, init, name, version, name); } JNIEXPORT void JNICALL Java_cz_crcs_ectester_standalone_libs_jni_NativeProvider_00024TomCrypt_setup(JNIEnv *env, jobject this) { - /* Initialize libtommath as the math lib. */ ltc_mp = ltm_desc; jclass provider_class = (*env)->FindClass(env, "cz/crcs/ectester/standalone/libs/jni/NativeProvider$TomCrypt"); jmethodID put = (*env)->GetMethodID(env, provider_class, "put", "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;"); - if (put == NULL) { - return; - } - const ltc_ecc_set_type * curve = ltc_ecc_sets; - while (curve->name != NULL) { - printf("%s\n", curve->name); - curve++; - } - /* Just test ecc key generation at this time. */ +/* *//* Just test ecc key generation at this time. *//* ecc_key mykey; prng_state prng; int err; - /* register yarrow */ + *//* register yarrow *//* if (register_prng(&yarrow_desc) == -1) { printf("Error registering Yarrow\n"); return; } - /* setup the PRNG */ + *//* setup the PRNG *//* if ((err = rng_make_prng(128, find_prng("yarrow"), &prng, NULL)) != CRYPT_OK) { printf("Error setting up PRNG, %s\n", error_to_string(err)); return; } - /* make a 192-bit ECC key */ + *//* make a 192-bit ECC key *//* if ((err = ecc_make_key(&prng, find_prng("yarrow"), 24, &mykey)) != CRYPT_OK) { printf("Error making key: %s\n", error_to_string(err)); return; } - return; + return;*/ +} + +JNIEXPORT jobject JNICALL Java_cz_crcs_ectester_standalone_libs_TomcryptLib_getCurves(JNIEnv *env, jobject this) { + jclass hash_set_class = (*env)->FindClass(env, "java/util/TreeSet"); + + jmethodID hash_set_ctr = (*env)->GetMethodID(env, hash_set_class, "", "()V"); + jmethodID hash_set_add = (*env)->GetMethodID(env, hash_set_class, "add", "(Ljava/lang/Object;)Z"); + + jobject result = (*env)->NewObject(env, hash_set_class, hash_set_ctr); + const ltc_ecc_set_type * curve = ltc_ecc_sets; + while (curve->size != 0) { + jstring curve_name = (*env)->NewStringUTF(env, curve->name); + (*env)->CallBooleanMethod(env, result, hash_set_add, curve_name); + curve++; + } + + return result; } \ No newline at end of file -- cgit v1.2.3-70-g09d2 From 715dd7f068dfc9e5b90ce0c1e2d3aad0a9fe982a Mon Sep 17 00:00:00 2001 From: J08nY Date: Thu, 30 Nov 2017 16:06:35 +0100 Subject: Implement ECDH for TomCrypt. --- build-standalone.xml | 1 + .../crcs/ectester/standalone/libs/TomcryptLib.java | 2 +- src/cz/crcs/ectester/standalone/libs/jni/Makefile | 4 +- .../standalone/libs/jni/NativeKeyAgreementSpi.java | 62 ++++++++++++++++++++-- src/cz/crcs/ectester/standalone/libs/jni/native.h | 19 +++++++ .../crcs/ectester/standalone/libs/jni/tomcrypt.c | 52 +++++++++++++++++- 6 files changed, 130 insertions(+), 10 deletions(-) (limited to 'src/cz/crcs/ectester/standalone/libs/TomcryptLib.java') diff --git a/build-standalone.xml b/build-standalone.xml index 7261eee..8098ce2 100644 --- a/build-standalone.xml +++ b/build-standalone.xml @@ -100,6 +100,7 @@ + diff --git a/src/cz/crcs/ectester/standalone/libs/TomcryptLib.java b/src/cz/crcs/ectester/standalone/libs/TomcryptLib.java index 78db00e..57b273a 100644 --- a/src/cz/crcs/ectester/standalone/libs/TomcryptLib.java +++ b/src/cz/crcs/ectester/standalone/libs/TomcryptLib.java @@ -9,7 +9,7 @@ import java.util.Set; public class TomcryptLib extends NativeECLibrary { public TomcryptLib() { - super("tomcrypt_provider", "tommath", "tomcrypt"); + super("tomcrypt_provider", "tommath", "tomcrypt"); } @Override diff --git a/src/cz/crcs/ectester/standalone/libs/jni/Makefile b/src/cz/crcs/ectester/standalone/libs/jni/Makefile index 8750dd5..b60452f 100644 --- a/src/cz/crcs/ectester/standalone/libs/jni/Makefile +++ b/src/cz/crcs/ectester/standalone/libs/jni/Makefile @@ -36,10 +36,10 @@ JNI_PLATFORMINCLUDEDIR ?= $(JNI_INCLUDEDIR)/$(JNI_PLATFORM) all: tomcrypt_provider.so tomcrypt_provider.so: tomcrypt.o - gcc -DLTM_DESC -DUSE_LTM -fPIC -g -shared -o $@ $< -ltommath -ltomcrypt + gcc -fPIC -g -shared -o $@ $< -L. -ltommath -ltomcrypt %.o: %.c - gcc -fPIC -g -I"$(JNI_INCLUDEDIR)" -I"$(JNI_PLATFORMINCLUDEDIR)" -I. -c $< + gcc -DLTM_DESC -fPIC -g -I"$(JNI_INCLUDEDIR)" -I"$(JNI_PLATFORMINCLUDEDIR)" -I. -c $< clean: rm -rf *.o diff --git a/src/cz/crcs/ectester/standalone/libs/jni/NativeKeyAgreementSpi.java b/src/cz/crcs/ectester/standalone/libs/jni/NativeKeyAgreementSpi.java index d1b1f42..fee0ea8 100644 --- a/src/cz/crcs/ectester/standalone/libs/jni/NativeKeyAgreementSpi.java +++ b/src/cz/crcs/ectester/standalone/libs/jni/NativeKeyAgreementSpi.java @@ -1,46 +1,98 @@ package cz.crcs.ectester.standalone.libs.jni; +import cz.crcs.ectester.common.util.ECUtil; + import javax.crypto.KeyAgreementSpi; import javax.crypto.SecretKey; import javax.crypto.ShortBufferException; import java.security.*; +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 abstract class NativeKeyAgreementSpi extends KeyAgreementSpi { + private ECPrivateKey privateKey; + private ECPublicKey publicKey; + private ECParameterSpec params; + @Override protected void engineInit(Key key, SecureRandom random) throws InvalidKeyException { - + if (!(key instanceof ECPrivateKey)) { + throw new InvalidKeyException + ("Key must be instance of PrivateKey"); + } + privateKey = (ECPrivateKey) key; + this.params = privateKey.getParams(); } @Override protected void engineInit(Key key, AlgorithmParameterSpec params, SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException { - + if (!(params instanceof ECParameterSpec)) { + throw new InvalidAlgorithmParameterException(); + } + engineInit(key, random); + this.params = (ECParameterSpec) params; } @Override protected Key engineDoPhase(Key key, boolean lastPhase) throws InvalidKeyException, IllegalStateException { + if (privateKey == null) { + throw new IllegalStateException("Not initialized"); + } + if (publicKey != null) { + throw new IllegalStateException("Phase already executed"); + } + if (!lastPhase) { + throw new IllegalStateException + ("Only two party agreement supported, lastPhase must be true"); + } + if (!(key instanceof ECPublicKey)) { + throw new InvalidKeyException + ("Key must be a PublicKey with algorithm EC"); + } + ECParameterSpec publicParams = ((ECPublicKey) key).getParams(); + if (!(params.getCurve().equals(publicParams.getCurve()) && + params.getGenerator().equals(publicParams.getGenerator()) && + params.getOrder().equals(publicParams.getOrder()) && + params.getCofactor() == publicParams.getCofactor())) { + throw new IllegalStateException("Mismatched parameters."); + } + publicKey = (ECPublicKey) key; return null; } @Override protected byte[] engineGenerateSecret() throws IllegalStateException { - return new byte[0]; + byte[] pubkey = ECUtil.toX962Uncompressed(publicKey.getW()); + byte[] privkey = privateKey.getS().toByteArray(); + return generateSecret(pubkey, privkey, params); } @Override protected int engineGenerateSecret(byte[] sharedSecret, int offset) throws IllegalStateException, ShortBufferException { - return 0; + byte[] secret = engineGenerateSecret(); + if (sharedSecret.length < offset + secret.length) { + throw new ShortBufferException(); + } + System.arraycopy(secret, 0, sharedSecret, offset, secret.length); + return secret.length; } @Override protected SecretKey engineGenerateSecret(String algorithm) throws IllegalStateException, NoSuchAlgorithmException, InvalidKeyException { - return null; + throw new NoSuchAlgorithmException(algorithm); } + abstract byte[] generateSecret(byte[] pubkey, byte[] privkey, ECParameterSpec params); + + public static class TomCrypt extends NativeKeyAgreementSpi { + @Override + native byte[] generateSecret(byte[] pubkey, byte[] privkey, ECParameterSpec params); } } diff --git a/src/cz/crcs/ectester/standalone/libs/jni/native.h b/src/cz/crcs/ectester/standalone/libs/jni/native.h index da3a89c..7f63f61 100644 --- a/src/cz/crcs/ectester/standalone/libs/jni/native.h +++ b/src/cz/crcs/ectester/standalone/libs/jni/native.h @@ -125,3 +125,22 @@ extern "C" { } #endif #endif +/* Header for class cz_crcs_ectester_standalone_libs_jni_NativeKeyAgreementSpi_TomCrypt */ + +#ifndef _Included_cz_crcs_ectester_standalone_libs_jni_NativeKeyAgreementSpi_TomCrypt +#define _Included_cz_crcs_ectester_standalone_libs_jni_NativeKeyAgreementSpi_TomCrypt +#ifdef __cplusplus +extern "C" { +#endif +/* + * Class: cz_crcs_ectester_standalone_libs_jni_NativeKeyAgreementSpi_TomCrypt + * Method: generateSecret + * Signature: ([B[BLjava/security/spec/ECParameterSpec;)[B + */ +JNIEXPORT jbyteArray JNICALL Java_cz_crcs_ectester_standalone_libs_jni_NativeKeyAgreementSpi_00024TomCrypt_generateSecret + (JNIEnv *, jobject, jbyteArray, jbyteArray, jobject); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/src/cz/crcs/ectester/standalone/libs/jni/tomcrypt.c b/src/cz/crcs/ectester/standalone/libs/jni/tomcrypt.c index f7dedce..b43b05a 100644 --- a/src/cz/crcs/ectester/standalone/libs/jni/tomcrypt.c +++ b/src/cz/crcs/ectester/standalone/libs/jni/tomcrypt.c @@ -1,7 +1,6 @@ #include "native.h" #include #include -#define LTM_DESC #include static prng_state ltc_prng; @@ -287,7 +286,7 @@ static jobject generate_from_curve(JNIEnv *env, const ltc_ecc_set_type *curve) { jbyteArray priv_bytes = (*env)->NewByteArray(env, curve->size); jbyte *key_priv = (*env)->GetByteArrayElements(env, priv_bytes, NULL); - mp_to_unsigned_bin(key.k, key_priv); + ltc_mp.unsigned_write(key.k, key_priv); (*env)->ReleaseByteArrayElements(env, priv_bytes, key_priv, 0); jobject ec_priv_param_spec = (*env)->NewLocalRef(env, ec_param_spec); @@ -341,4 +340,53 @@ JNIEXPORT jobject JNICALL Java_cz_crcs_ectester_standalone_libs_jni_NativeKeyPai } else { return NULL; } +} + +JNIEXPORT jbyteArray JNICALL Java_cz_crcs_ectester_standalone_libs_jni_NativeKeyAgreementSpi_00024TomCrypt_generateSecret(JNIEnv *env, jobject this, jbyteArray pubkey, jbyteArray privkey, jobject params){ + ltc_ecc_set_type *curve = create_curve(env, params); + + jsize pub_size = (*env)->GetArrayLength(env, pubkey); + jbyte *pub_data = (*env)->GetByteArrayElements(env, pubkey, NULL); + jsize pub_half = (pub_size - 1) / 2; + + ecc_key pub; + pub.type = PK_PUBLIC; + pub.idx = -1; + pub.dp = curve; + ltc_init_multi(&pub.pubkey.x, &pub.pubkey.y, &pub.pubkey.z, NULL); + ltc_mp.set_int(pub.pubkey.z, 1); + ltc_mp.unsigned_read(pub.pubkey.x, pub_data + 1, (unsigned long) pub_half); + ltc_mp.unsigned_read(pub.pubkey.y, pub_data + 1 + pub_half, (unsigned long) pub_half); + + (*env)->ReleaseByteArrayElements(env, pubkey, pub_data, JNI_ABORT); + + jsize priv_size = (*env)->GetArrayLength(env, privkey); + jbyte *priv_data = (*env)->GetByteArrayElements(env, privkey, NULL); + + ecc_key priv; + priv.type = PK_PRIVATE; + priv.idx = -1; + priv.dp = curve; + ltc_mp.init(&priv.k); + ltc_mp.unsigned_read(priv.k, priv_data, (unsigned long) priv_size); + + (*env)->ReleaseByteArrayElements(env, privkey, priv_data, JNI_ABORT); + + unsigned char result[pub_half]; + + unsigned long output_len = pub_half; + int err; + if ((err = ecc_shared_secret(&priv, &pub, result, &output_len)) != CRYPT_OK) { + printf("Error during shared secret computation: %s\n", error_to_string(err)); + free(curve); + return NULL; + } + + jbyteArray output = (*env)->NewByteArray(env, pub_half); + jbyte *output_data = (*env)->GetByteArrayElements(env, output, NULL); + memcpy(output_data, result, pub_half); + (*env)->ReleaseByteArrayElements(env, output, output_data, JNI_COMMIT); + + free(curve); + return output; } \ No newline at end of file -- cgit v1.2.3-70-g09d2