@Test public void testExportImport() throws GeneralSecurityException { // Create a curve25519 parameter spec X9ECParameters params = CustomNamedCurves.getByName("curve25519"); ECParameterSpec ecParameterSpec = new ECParameterSpec(params.getCurve(), params.getG(), params.getN(), params.getH(), params.getSeed()); // Create public key KeyAgreementPeer peer = new ECDHPeer(ecParameterSpec, null, "BC"); ECPublicKey ecPublicKey = (ECPublicKey) peer.getPublicKey(); // Export public key byte[] encoded = ecPublicKey.getQ().getEncoded(true); System.out.println(Arrays.toString(encoded)); System.out.println("Encoded length: " + encoded.length); // Import public key ECPublicKey importedECPublicKey = loadPublicKey(encoded); Assert.assertArrayEquals(ecPublicKey.getEncoded(), importedECPublicKey.getEncoded()); }
public static ECDomainParameters getParametersForNamedCurve(int namedCurve) { String curveName = getNameOfNamedCurve(namedCurve); if (curveName == null) { return null; } // Parameters are lazily created the first time a particular curve is accessed X9ECParameters ecP = CustomNamedCurves.getByName(curveName); if (ecP == null) { ecP = ECNamedCurveTable.getByName(curveName); if (ecP == null) { return null; } } // It's a bit inefficient to do this conversion every time return new ECDomainParameters(ecP.getCurve(), ecP.getG(), ecP.getN(), ecP.getH(), ecP.getSeed()); }
public static void main(String[] args) { SortedSet names = new TreeSet(enumToList(ECNamedCurveTable.getNames())); names.addAll(enumToList(CustomNamedCurves.getNames())); Iterator it = names.iterator(); while (it.hasNext()) { String name = (String)it.next(); X9ECParameters x9 = CustomNamedCurves.getByName(name); if (x9 == null) { x9 = ECNamedCurveTable.getByName(name); } if (x9 != null && ECAlgorithms.isF2mCurve(x9.getCurve())) { System.out.print(name + ":"); implPrintNonZeroTraceBits(x9); } } }
public static void main(String[] args) { SortedSet names = new TreeSet(enumToList(ECNamedCurveTable.getNames())); names.addAll(enumToList(CustomNamedCurves.getNames())); Iterator it = names.iterator(); while (it.hasNext()) { String name = (String)it.next(); X9ECParameters x9 = CustomNamedCurves.getByName(name); if (x9 == null) { x9 = ECNamedCurveTable.getByName(name); } if (x9 != null && ECAlgorithms.isF2mCurve(x9.getCurve())) { System.out.print(name + ":"); implPrintRootZ(x9); } } }
public static X9ECParameters getNamedCurveByOid( ASN1ObjectIdentifier oid) { X9ECParameters params = CustomNamedCurves.getByOID(oid); if (params == null) { params = X962NamedCurves.getByOID(oid); if (params == null) { params = SECNamedCurves.getByOID(oid); } if (params == null) { params = NISTNamedCurves.getByOID(oid); } if (params == null) { params = TeleTrusTNamedCurves.getByOID(oid); } } return params; }
public static X9ECParameters getNamedCurveByName( String curveName) { X9ECParameters params = CustomNamedCurves.getByName(curveName); if (params == null) { params = X962NamedCurves.getByName(curveName); if (params == null) { params = SECNamedCurves.getByName(curveName); } if (params == null) { params = NISTNamedCurves.getByName(curveName); } if (params == null) { params = TeleTrusTNamedCurves.getByName(curveName); } } return params; }
@Test public void testDuplicateKey() { ECKeyManager keyManager = new ECKeyManager(new TestUtils.BasicNodeContext("Test")); X9ECParameters ecParameters = CustomNamedCurves.getByName("secp256r1"); ECDomainParameters domainParameters = new ECDomainParameters(ecParameters.getCurve(), ecParameters.getG(), ecParameters.getN(), ecParameters.getH()); ECPoint h = domainParameters.getG().multiply(BigInteger.valueOf(1000001)); keyManager.generateKeyPair("Test1", Algorithm.EC_ELGAMAL, 1, domainParameters, h); try { keyManager.generateKeyPair("Test1", Algorithm.EC_ELGAMAL, 1, domainParameters, h); Assert.fail("duplicate key not detected"); } catch (IllegalStateException e) { Assert.assertEquals("Key Test1 already exists.", e.getMessage()); } }
@Test public void testFailedCommitment() throws Exception { ECKeyManager keyManager = new ECKeyManager(new TestUtils.BasicNodeContext("Test")); X9ECParameters ecParameters = CustomNamedCurves.getByName("secp256r1"); ECDomainParameters domainParameters = new ECDomainParameters(ecParameters.getCurve(), ecParameters.getG(), ecParameters.getN(), ecParameters.getH()); ECPoint h = domainParameters.getG().multiply(BigInteger.valueOf(1000001)); AsymmetricCipherKeyPair kp = keyManager.generateKeyPair("Test1", Algorithm.EC_ELGAMAL, 1, domainParameters, h); ECPrivateKeyParameters privKey = (ECPrivateKeyParameters)kp.getPrivate(); ECPublicKeyParameters pubKey = (ECPublicKeyParameters)kp.getPublic(); ECPoint commitment = pubKey.getParameters().getG().multiply(privKey.getD()).add(h); try { keyManager.buildSharedKey("Test1", new ECCommittedSecretShareMessage(0, privKey.getD(), BigInteger.TEN, new ECPoint[]{commitment}, pubKey.getQ(), new ECPoint[]{pubKey.getQ()})); Assert.fail("bad commitment not detected"); } catch (IllegalStateException e) { Assert.assertEquals("Commitment for Test1 failed!", e.getMessage()); } }
@Test public void testBasicGenerationNoPeers() throws Exception { XimixNodeContext context = new XimixNodeContext(new HashMap<String, ServicesConnection>(), new Config(createConfig("A")), new TestNotifier()); try { List<String> peers = Arrays.asList("A", "B", "C"); NamedKeyGenParams kGenParams = new NamedKeyGenParams("EC_KEY", Algorithm.EC_ELGAMAL, "secp256r1", 4, peers); X9ECParameters ecParameters = CustomNamedCurves.getByName("secp256r1"); ECDomainParameters domainParameters = new ECDomainParameters(ecParameters.getCurve(), ecParameters.getG(), ecParameters.getN(), ecParameters.getH()); ECPoint h = domainParameters.getG().multiply(BigInteger.valueOf(1000001)); ECCommittedSecretShareMessage[] messages = ((ECNewDKGGenerator)context.getKeyPairGenerator(Algorithm.EC_ELGAMAL)) .generateThresholdKey("EC_KEY", domainParameters, kGenParams.getNodesToUse().size(), kGenParams.getThreshold(), h); Assert.fail("no exception!"); } catch (IllegalArgumentException e) { if (!"numberOfPeers must at least be as big as the threshold value.".equals(e.getMessage())) { Assert.fail("exception but wrong message"); } } }
/** * Loads and returns the elliptic-curve public key from the data byte array. * @param data * @return * @throws NoSuchAlgorithmException * @throws NoSuchProviderException * @throws InvalidKeySpecException */ public static ECPublicKey loadPublicKey(byte[] data) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException { X9ECParameters params = CustomNamedCurves.getByName("curve25519"); ECParameterSpec ecParameterSpec = new ECParameterSpec(params.getCurve(), params.getG(), params.getN(), params.getH(), params.getSeed()); ECPublicKeySpec publicKey = new ECPublicKeySpec(ecParameterSpec.getCurve().decodePoint(data), ecParameterSpec); KeyFactory kf = KeyFactory.getInstance("ECDH", "BC"); return (ECPublicKey) kf.generatePublic(publicKey); }
static X9ECParameters getX9Parameters(ASN1ObjectIdentifier curveOID) { X9ECParameters x9 = CustomNamedCurves.getByOID(curveOID); if (x9 == null) { x9 = ECNamedCurveTable.getByOID(curveOID); } return x9; }
@Test public void testBasicGeneration() throws Exception { Map<String, XimixNodeContext> contextMap = createContextMap(5); XimixNodeContext context = contextMap.get("A"); List<String> peers = Arrays.asList("A", "B", "C", "D", "E"); NamedKeyGenParams kGenParams = new NamedKeyGenParams("EC_KEY", Algorithm.EC_ELGAMAL, "secp256r1", 4, peers); X9ECParameters ecParameters = CustomNamedCurves.getByName("secp256r1"); ECDomainParameters domainParameters = new ECDomainParameters(ecParameters.getCurve(), ecParameters.getG(), ecParameters.getN(), ecParameters.getH()); ECPoint h = domainParameters.getG().multiply(BigInteger.valueOf(1000001)); ECCommittedSecretShareMessage[] messages = ((ECNewDKGGenerator)context.getKeyPairGenerator(Algorithm.EC_ELGAMAL)) .generateThresholdKey("EC_KEY", domainParameters, kGenParams.getNodesToUse().size(), kGenParams.getThreshold(), h); Assert.assertEquals(5, messages.length); X9ECParameters params = CustomNamedCurves.getByName("secp256r1"); ECDomainParameters domainParams = new ECDomainParameters(params.getCurve(), params.getG(), params.getN(), params.getH(), params.getSeed()); for (int i = 0; i != messages.length; i++) { ECCommittedSecretShareMessage message = ECCommittedSecretShareMessage.getInstance(params.getCurve(), messages[i].getEncoded()); ECCommittedSecretShare share = new ECCommittedSecretShare(message.getValue(), message.getWitness(), message.getCommitmentFactors()); Assert.assertTrue(share.isRevealed(i, domainParams, h)); } }
public void verify() throws JSONException, JSONIOException, IOException, TranscriptVerificationException { BallotUnpacker unpacker = new BallotUnpacker(mapProperties); ASN1InputStream aIn = new ASN1InputStream(new FileInputStream(pointFile)); String baseName = pointFile.getName().substring(0, pointFile.getName().lastIndexOf('.')); String[] details = baseName.split("_"); // The second part of the name tells us which type the race is BufferedReader bfIn = new BufferedReader(new FileReader(new File(pointFile.getParentFile(), baseName + "." + unpacker.getSuffix(details[0], details[1], details[2]) + ".csv"))); int ballotLength = unpacker.getBallotLength(details[0], details[1], details[2]); int lineNumber = 1; Object o; while ((o = aIn.readObject()) != null) { PointSequence seq = PointSequence.getInstance(CustomNamedCurves.getByName("secp256r1").getCurve(), o); ECPoint[] points = seq.getECPoints(); List<Integer> candidates = new ArrayList<>(); int maxCandidateID = 0; for (int i = 0; i != points.length; i++) { int[] votes = unpacker.lookup(details[0], details[1], details[2], points[i]); for (int j = 0; j != votes.length; j++) { candidates.add(votes[j]); if (votes[j] > maxCandidateID) { maxCandidateID = votes[j]; } } } int[] preferences = new int[ballotLength]; int preference = 1; for (int i = 0; i != candidates.size(); i++) { preferences[candidates.get(i) - 1] = preference++; } StringBuilder sBuild = new StringBuilder(); for (int i = 0; i != preferences.length; i++) { if (i != 0) { sBuild.append(","); } if (preferences[i] != 0) { sBuild.append(Integer.toString(preferences[i])); } } String recorded = bfIn.readLine(); if (!sBuild.toString().equals(recorded)) { throw new TranscriptVerificationException("Recorded CSV ballot (" + lineNumber + ") \"" + recorded + "\" does not match EC output \"" + sBuild.toString() +"\""); } lineNumber++; } aIn.close(); bfIn.close(); }
public static void main(String[] args) throws Exception { BallotUnpacker unpacker = new BallotUnpacker(new File(args[0])); File inputVotes = new File(args[1]); ASN1InputStream aIn = new ASN1InputStream(new FileInputStream(inputVotes)); String[] details = args[1].split("_"); Object o; while ((o = aIn.readObject()) != null) { PointSequence seq = PointSequence.getInstance(CustomNamedCurves.getByName("secp256r1").getCurve(), o); System.err.println(unpacker.lookup(details[0], details[1], details[2], seq.getECPoints()[0])); } // // Look up each sample packing and check it is found correctly // for (int i = 0; i < numberOfTests; i++) { // long innerStartTime = System.currentTimeMillis(); // byte[] res = bsf.binarySearch(samplePacking.get(i).getEncoded(true)); // if (res != null) { // String foundResult = Arrays.toString(BinarySearchFile.convertToPlain(res, blockSize)); // String expected = Arrays.toString(expectedResult.get(i)); // // if (!foundResult.equals(expected)) { // logger.warn("Incorrect result); expected: {} found {}", expected, foundResult); // failure++; // } // else { // success++; // } // } // else { // failure++; // logger.warn("Result not found: expected: {} found null", Arrays.toString(expectedResult.get(i))); // } // long innerEndTime = System.currentTimeMillis(); // long diff = innerEndTime - innerStartTime; // // if (diff > maxSearchTime) { // maxSearchTime = diff; // } // if (diff < minSearchTime) { // minSearchTime = diff; // } // } }
public MessageReply handle(final KeyPairGenerateMessage message) { // TODO: sort out the reply messages try { switch (((Type)message.getType())) { case GENERATE: final NamedKeyGenParams ecKeyGenParams = (NamedKeyGenParams)NamedKeyGenParams.getInstance(message.getPayload()); final List<String> involvedPeers = ecKeyGenParams.getNodesToUse(); X9ECParameters params = CustomNamedCurves.getByName(ecKeyGenParams.getDomainParameters()); if (params == null) { params = ECNamedCurveTable.getByName(ecKeyGenParams.getDomainParameters()); } paramsMap.put(ecKeyGenParams.getKeyID(), new ECDomainParameters(params.getCurve(), params.getG(), params.getN(), params.getH(), params.getSeed())); sharedHMap.init(ecKeyGenParams.getKeyID(), involvedPeers.size()); BigInteger h = generateH(params.getN(), new SecureRandom()); // TODO: provide randomness? ECPoint[] messages = new ECPoint[involvedPeers.size()]; for (int i = 0; i != messages.length; i++) { messages[i] = params.getG().multiply(h); } nodeContext.execute(new SendHTask(message.getAlgorithm(), ecKeyGenParams.getKeyID(), involvedPeers, messages)); final List<String> peerList = ecKeyGenParams.getNodesToUse(); ECNewDKGGenerator generator = (ECNewDKGGenerator)nodeContext.getKeyPairGenerator(ecKeyGenParams.getAlgorithm()); ECCommittedSecretShareMessage[] comMessages = generator.generateThresholdKey( ecKeyGenParams.getKeyID(), paramsMap.get(ecKeyGenParams.getKeyID()), peerList.size(), ecKeyGenParams.getThreshold(), sharedHMap.getShare(ecKeyGenParams.getKeyID()).getValue().normalize()); nodeContext.execute(new SendShareTask(generator, message.getAlgorithm(), ecKeyGenParams.getKeyID(), peerList, comMessages)); return new MessageReply(MessageReply.Type.OKAY); case STORE_H: StoreMessage storeMessage = StoreMessage.getInstance(message.getPayload()); ShareMessage shareMessage = ShareMessage.getInstance(storeMessage.getSecretShareMessage()); nodeContext.execute(new StoreHTask(storeMessage.getID(), shareMessage)); return new MessageReply(MessageReply.Type.OKAY); case STORE: StoreMessage sssMessage = StoreMessage.getInstance(message.getPayload()); // we may not have been asked to generate our share yet, if this is the case we need to queue up our share requests // till we can validate them. generator = (ECNewDKGGenerator)nodeContext.getKeyPairGenerator(message.getAlgorithm()); nodeContext.execute(new StoreShareTask(generator, sssMessage.getID(), sssMessage.getSecretShareMessage())); return new MessageReply(MessageReply.Type.OKAY); default: return new MessageReply(MessageReply.Type.ERROR, new DERUTF8String("Unknown command in NodeKeyGenerationService.")); } } catch (Exception e) { nodeContext.getEventNotifier().notify(EventNotifier.Level.ERROR, "NodeKeyGenerationService failure: " + e.getMessage(), e); return new MessageReply(MessageReply.Type.ERROR, new DERUTF8String("NodeKeyGenerationService failure: " + e.getMessage())); } }
@Test public void testSingleKeyStoreAndLoad() throws Exception { ECKeyManager keyManager = new ECKeyManager(new TestUtils.BasicNodeContext("Test")); X9ECParameters ecParameters = CustomNamedCurves.getByName("secp256r1"); ECDomainParameters domainParameters = new ECDomainParameters(ecParameters.getCurve(), ecParameters.getG(), ecParameters.getN(), ecParameters.getH()); ECPoint h = domainParameters.getG().multiply(BigInteger.valueOf(1000001)); AsymmetricCipherKeyPair kp = keyManager.generateKeyPair("Test1", Algorithm.EC_ELGAMAL, 1, domainParameters, h); ECPrivateKeyParameters privKey = (ECPrivateKeyParameters)kp.getPrivate(); ECPublicKeyParameters pubKey = (ECPublicKeyParameters)kp.getPublic(); ECPoint commitment = pubKey.getParameters().getG().multiply(privKey.getD()).add(h); keyManager.buildSharedKey("Test1", new ECCommittedSecretShareMessage(0, privKey.getD(), BigInteger.ONE, new ECPoint[]{commitment}, pubKey.getQ(), new ECPoint[]{pubKey.getQ()})); keyManager.fetchPublicKey("Test1"); // make sure we've synced up byte[] p12enc = keyManager.getEncoded(passwd); KeyStore keyStore = KeyStore.getInstance("PKCS12", "BC"); keyStore.load(new ByteArrayInputStream(p12enc), passwd); Assert.assertEquals(1, keyStore.size()); Assert.assertTrue(keyStore.containsAlias("Test1")); ECKeyManager rebuiltKeyManager = new ECKeyManager(new TestUtils.BasicNodeContext("Test")); rebuiltKeyManager.load(passwd, p12enc); Assert.assertFalse(keyManager.isSigningKey("Test1")); Assert.assertFalse(rebuiltKeyManager.isSigningKey("Test1")); Assert.assertEquals(SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(kp.getPublic()), keyManager.fetchPublicKey("Test1")); Assert.assertEquals(((ECPrivateKeyParameters)kp.getPrivate()).getD(), keyManager.getPartialPrivateKey("Test1")); Assert.assertEquals(keyManager.fetchPublicKey("Test1"), rebuiltKeyManager.fetchPublicKey("Test1")); Assert.assertEquals(keyManager.getPartialPrivateKey("Test1"), rebuiltKeyManager.getPartialPrivateKey("Test1")); }