List of usage examples for org.bouncycastle.crypto.ec CustomNamedCurves getByName
public static X9ECParameters getByName(String name)
From source file:co.rsk.peg.BridgeSupportTest.java
License:Open Source License
/** * Helper method to test addSignature() with a valid federatorPublicKey parameter and both valid/invalid signatures * @param privateKeysToSignWith keys used to sign the tx. Federator key when we want to produce a valid signature, a random key when we want to produce an invalid signature * @param numberOfInputsToSign There is just 1 input. 1 when testing the happy case, other values to test attacks/bugs. * @param signatureCanonical Signature should be canonical. true when testing the happy case, false to test attacks/bugs. * @param signTwice Sign again with the same key * @param expectedResult "InvalidParameters", "PartiallySigned" or "FullySigned" *///from w ww. j a va2 s .c o m private void addSignatureFromValidFederator(List<BtcECKey> privateKeysToSignWith, int numberOfInputsToSign, boolean signatureCanonical, boolean signTwice, String expectedResult) throws Exception { // Federation is the genesis federation ATM Federation federation = bridgeConstants.getGenesisFederation(); Repository repository = createRepositoryImpl(config); final Keccak256 keccak256 = PegTestUtils.createHash3(); Repository track = repository.startTracking(); BridgeStorageProvider provider = new BridgeStorageProvider(track, PrecompiledContracts.BRIDGE_ADDR, config.getBlockchainConfig().getCommonConstants().getBridgeConstants(), bridgeStorageConfigurationAtHeightZero); BtcTransaction prevTx = new BtcTransaction(btcParams); TransactionOutput prevOut = new TransactionOutput(btcParams, prevTx, Coin.FIFTY_COINS, federation.getAddress()); prevTx.addOutput(prevOut); BtcTransaction t = new BtcTransaction(btcParams); TransactionOutput output = new TransactionOutput(btcParams, t, Coin.COIN, new BtcECKey().toAddress(btcParams)); t.addOutput(output); t.addInput(prevOut).setScriptSig(PegTestUtils.createBaseInputScriptThatSpendsFromTheFederation(federation)); provider.getRskTxsWaitingForSignatures().put(keccak256, t); provider.save(); track.commit(); track = repository.startTracking(); List<LogInfo> logs = new ArrayList<>(); BridgeEventLogger eventLogger = new BridgeEventLoggerImpl(bridgeConstants, logs); BridgeSupport bridgeSupport = new BridgeSupport(config, track, eventLogger, contractAddress, mock(Block.class)); Script inputScript = t.getInputs().get(0).getScriptSig(); List<ScriptChunk> chunks = inputScript.getChunks(); byte[] program = chunks.get(chunks.size() - 1).data; Script redeemScript = new Script(program); Sha256Hash sighash = t.hashForSignature(0, redeemScript, BtcTransaction.SigHash.ALL, false); BtcECKey.ECDSASignature sig = privateKeysToSignWith.get(0).sign(sighash); if (!signatureCanonical) { sig = new BtcECKey.ECDSASignature(sig.r, BtcECKey.CURVE.getN().subtract(sig.s)); } byte[] derEncodedSig = sig.encodeToDER(); List derEncodedSigs = new ArrayList(); for (int i = 0; i < numberOfInputsToSign; i++) { derEncodedSigs.add(derEncodedSig); } bridgeSupport.addSignature(findPublicKeySignedBy(federation.getPublicKeys(), privateKeysToSignWith.get(0)), derEncodedSigs, keccak256.getBytes()); if (signTwice) { // Create another valid signature with the same private key ECDSASigner signer = new ECDSASigner(); X9ECParameters CURVE_PARAMS = CustomNamedCurves.getByName("secp256k1"); ECDomainParameters CURVE = new ECDomainParameters(CURVE_PARAMS.getCurve(), CURVE_PARAMS.getG(), CURVE_PARAMS.getN(), CURVE_PARAMS.getH()); ECPrivateKeyParameters privKey = new ECPrivateKeyParameters(privateKeysToSignWith.get(0).getPrivKey(), CURVE); signer.init(true, privKey); BigInteger[] components = signer.generateSignature(sighash.getBytes()); BtcECKey.ECDSASignature sig2 = new BtcECKey.ECDSASignature(components[0], components[1]) .toCanonicalised(); bridgeSupport.addSignature( findPublicKeySignedBy(federation.getPublicKeys(), privateKeysToSignWith.get(0)), Lists.newArrayList(sig2.encodeToDER()), keccak256.getBytes()); } if (privateKeysToSignWith.size() > 1) { BtcECKey.ECDSASignature sig2 = privateKeysToSignWith.get(1).sign(sighash); byte[] derEncodedSig2 = sig2.encodeToDER(); List derEncodedSigs2 = new ArrayList(); for (int i = 0; i < numberOfInputsToSign; i++) { derEncodedSigs2.add(derEncodedSig2); } bridgeSupport.addSignature( findPublicKeySignedBy(federation.getPublicKeys(), privateKeysToSignWith.get(1)), derEncodedSigs2, keccak256.getBytes()); } bridgeSupport.save(); track.commit(); provider = new BridgeStorageProvider(repository, PrecompiledContracts.BRIDGE_ADDR, config.getBlockchainConfig().getCommonConstants().getBridgeConstants(), bridgeStorageConfigurationAtHeightZero); if ("FullySigned".equals(expectedResult)) { Assert.assertTrue(provider.getRskTxsWaitingForSignatures().isEmpty()); Assert.assertThat(logs, is(not(empty()))); Assert.assertThat(logs, hasSize(3)); LogInfo releaseTxEvent = logs.get(2); Assert.assertThat(releaseTxEvent.getTopics(), hasSize(1)); Assert.assertThat(releaseTxEvent.getTopics(), hasItem(Bridge.RELEASE_BTC_TOPIC)); BtcTransaction releaseTx = new BtcTransaction(bridgeConstants.getBtcParams(), ((RLPList) RLP.decode2(releaseTxEvent.getData()).get(0)).get(1).getRLPData()); Script retrievedScriptSig = releaseTx.getInput(0).getScriptSig(); Assert.assertEquals(4, retrievedScriptSig.getChunks().size()); Assert.assertEquals(true, retrievedScriptSig.getChunks().get(1).data.length > 0); Assert.assertEquals(true, retrievedScriptSig.getChunks().get(2).data.length > 0); } else { Script retrievedScriptSig = provider.getRskTxsWaitingForSignatures().get(keccak256).getInput(0) .getScriptSig(); Assert.assertEquals(4, retrievedScriptSig.getChunks().size()); boolean expectSignatureToBePersisted = false; // for "InvalidParameters" if ("PartiallySigned".equals(expectedResult)) { expectSignatureToBePersisted = true; } Assert.assertEquals(expectSignatureToBePersisted, retrievedScriptSig.getChunks().get(1).data.length > 0); Assert.assertEquals(false, retrievedScriptSig.getChunks().get(2).data.length > 0); } }
From source file:com.cryptolib.CryptoObject.java
License:Open Source License
/** * Constructor.//from w w w . j a va 2s. c o m * Create a new CryptoObject with encryption asymmetric elliptic curve encryption keypair * and digital sign asymmetric elliptic curve keypair. * curve specificies elliptic curve for encryption scheme and sign algorithm e.g. "curve25519" * enc_algorithm must be an implemented elliptic curve encryption algorithm e.g. "ECDH" * shortAuthenticationStringSize must be a positive number, that represents the short authentication byte length. * iv_size must be positiv, byte size of iv for encryption scheme * tag_size must be positiv, byte size of tag for encryption scheme */ public CryptoObject(String curve, String enc_algorithm, int shortAuthenticationStringSize, int iv_size, int tag_size) throws CryptoSocketException { if (0 >= shortAuthenticationStringSize || 0 >= iv_size || 0 >= tag_size) { throw new CryptoSocketException( "shortAuthenticationStringSize,iv_size and tag_size must be a positive number!"); } try { X9ECParameters ecP = CustomNamedCurves.getByName(curve); org.bouncycastle.jce.spec.ECParameterSpec ecGenSpec = new org.bouncycastle.jce.spec.ECParameterSpec( ecP.getCurve(), ecP.getG(), ecP.getN(), ecP.getH(), ecP.getSeed()); this.provider = new BouncyCastleProvider(); KeyPairGenerator g = KeyPairGenerator.getInstance(enc_algorithm, this.provider); this.random = new SecureRandom(); g.initialize(ecGenSpec, this.random); this.encKeypair = g.generateKeyPair(); if (this.encKeypair == null) { throw new CryptoSocketException("Unable to create new key pair!"); } this.OOB = new byte[shortAuthenticationStringSize]; this.random.nextBytes(this.OOB); } catch (NoSuchAlgorithmException nsa) { throw new CryptoSocketException("Algorithm is not supported!"); } catch (InvalidAlgorithmParameterException iap) { throw new CryptoSocketException("Wrong parameter for algorithm!"); } this.enc_algorithm = enc_algorithm; this.curve = curve; this.iv_size = iv_size; this.tag_size = tag_size; }
From source file:com.cryptolib.CryptoObject.java
License:Open Source License
/** * Open commitment and extract message to create shared secret. *//*from w w w. j av a 2s.c o m*/ public void openCommitmentAndCreateSharedSecret(byte[] decommitment) throws CryptoSocketException, InvalidKeyException, NoSuchAlgorithmException { this.cc.open(decommitment); try { BCECPublicKey mypk = (BCECPublicKey) (this.encKeypair.getPublic()); int publicKeySize = mypk.getQ().getEncoded(true).length - 1; byte[] message = this.cc.getOtherMessage(); if (message.length != publicKeySize + this.OOB.length) { throw new CryptoSocketException("Message size is wrong!"); } byte[] otherPK = new byte[publicKeySize + 1]; //compressed encoding magic byte otherPK[0] = (byte) 0x02; byte[] otherOOB = new byte[this.OOB.length]; System.arraycopy(message, 0, otherPK, 1, publicKeySize); System.arraycopy(message, publicKeySize, otherOOB, 0, otherOOB.length); X9ECParameters ecP = CustomNamedCurves.getByName(curve); org.bouncycastle.jce.spec.ECParameterSpec ecGenSpec = new org.bouncycastle.jce.spec.ECParameterSpec( ecP.getCurve(), ecP.getG(), ecP.getN(), ecP.getH()); //ECNamedCurveParameterSpec ecP = ECNamedCurveTable.getParameterSpec(this.curve); ECPublicKeySpec pubKey = new ECPublicKeySpec(ecP.getCurve().decodePoint(otherPK), ecGenSpec); KeyFactory kf = KeyFactory.getInstance(this.enc_algorithm, new BouncyCastleProvider()); ECPublicKey pk = (ECPublicKey) kf.generatePublic(pubKey); createSharedEncKey(pk); mergeOOB(otherOOB); } catch (NoSuchAlgorithmException nsa) { throw new CryptoSocketException("Algorithm is not supported!"); } catch (InvalidKeySpecException iks) { throw new CryptoSocketException("Wrong parameter for algorithm!"); } }
From source file:com.cryptolib.CryptoObject.java
License:Open Source License
/** * Performs ECDH/*from ww w . j av a2s . co m*/ */ public void createSharedEncKey(ECPublicKey key) throws CryptoSocketException { try { X9ECParameters ecP = CustomNamedCurves.getByName(curve); ECDomainParameters ecdp = new ECDomainParameters(ecP.getCurve(), ecP.getG(), ecP.getN(), ecP.getH()); ECPublicKeyParameters ecpkp = new ECPublicKeyParameters(key.getQ(), ecdp); BCECPrivateKey sk = (BCECPrivateKey) this.encKeypair.getPrivate(); ECPrivateKeyParameters ecskp = new ECPrivateKeyParameters(sk.getD(), ecdp); ECDHCBasicAgreement ba = new ECDHCBasicAgreement(); ba.init(ecskp); byte[] byteSharedSecret = ba.calculateAgreement(ecpkp).toByteArray(); byte[] byteSharedSecretSecond = new byte[byteSharedSecret.length / 2]; byte[] byteSharedSecretFirst = new byte[byteSharedSecret.length / 2]; System.arraycopy(byteSharedSecret, 0, byteSharedSecretSecond, 0, byteSharedSecretSecond.length); System.arraycopy(byteSharedSecret, byteSharedSecretSecond.length, byteSharedSecretFirst, 0, byteSharedSecretFirst.length); this.sharedSecretFirst = new SecretKeySpec(byteSharedSecretFirst, "AES"); this.sharedSecretSecond = new SecretKeySpec(byteSharedSecretSecond, "AES"); this.has_symmetric_key = true; this.enc = Cipher.getInstance("AES/GCM/NoPadding"); this.dec = Cipher.getInstance("AES/GCM/NoPadding"); } catch (IllegalStateException is) { throw new CryptoSocketException("unable to create shared encryption key, wrong state!"); } catch (NoSuchAlgorithmException nsa) { throw new CryptoSocketException("Encryption algorithm not found!"); } catch (NoSuchPaddingException nsp) { throw new CryptoSocketException("Invalid padding algorithm!"); } }
From source file:com.distrimind.util.crypto.ASymmetricEncryptionType.java
License:Open Source License
static org.bouncycastle.jce.spec.ECParameterSpec getCurve25519() { if (curve25519 == null) { X9ECParameters ecP = CustomNamedCurves.getByName("curve25519"); // ECParameterSpec curve25519 = ECNamedCurveTable.getParameterSpec(algorithm); curve25519 = new org.bouncycastle.jce.spec.ECParameterSpec(ecP.getCurve(), ecP.getG(), ecP.getN(), ecP.getH(), ecP.getSeed()); }// w ww . ja va2 s . c o m return curve25519; }
From source file:dorkbox.util.serialization.EccPrivateKeySerializer.java
License:Apache License
static void serializeCurve(Output output, ECCurve curve) throws KryoException { byte[] bytes; int length;/*www . j a va2 s . c o m*/ // save out if it's a NAMED curve, or a UN-NAMED curve. If it is named, we can do less work. String curveName = curve.getClass().getSimpleName(); if (CustomNamedCurves.getByName(curveName) != null) { // we use the name instead of serializing the full curve output.writeInt(usesName, true); output.writeString(curveName); return; } else if (curveName.endsWith("Curve")) { String cleanedName = curveName.substring(0, curveName.indexOf("Curve")); if (!cleanedName.isEmpty()) { ASN1ObjectIdentifier oid = CustomNamedCurves.getOID(cleanedName); if (oid != null) { // we use the OID (instead of serializing the entire curve) output.writeInt(usesOid, true); curveName = oid.getId(); output.writeString(curveName); return; } } } // we have to serialize the ENTIRE curve. // save out the curve info BigInteger a = curve.getA().toBigInteger(); BigInteger b = curve.getB().toBigInteger(); BigInteger order = curve.getOrder(); BigInteger cofactor = curve.getCofactor(); BigInteger q = curve.getField().getCharacteristic(); ///////////// bytes = a.toByteArray(); length = bytes.length; output.writeInt(length, true); output.writeBytes(bytes, 0, length); ///////////// bytes = b.toByteArray(); length = bytes.length; output.writeInt(length, true); output.writeBytes(bytes, 0, length); ///////////// bytes = order.toByteArray(); length = bytes.length; output.writeInt(length, true); output.writeBytes(bytes, 0, length); ///////////// bytes = cofactor.toByteArray(); length = bytes.length; output.writeInt(length, true); output.writeBytes(bytes, 0, length); ///////////// bytes = q.toByteArray(); length = bytes.length; output.writeInt(length, true); output.writeBytes(bytes, 0, length); // coordinate system int coordinateSystem = curve.getCoordinateSystem(); output.writeInt(coordinateSystem, true); }
From source file:dorkbox.util.serialization.EccPrivateKeySerializer.java
License:Apache License
static ECCurve deserializeCurve(Input input) throws KryoException { byte[] bytes; int length;/*w ww . j a v a2s .c o m*/ ECCurve curve; int serializationType = input.readInt(true); // lookup via name if (serializationType == usesName) { String curveName = input.readString(); X9ECParameters x9Curve = CustomNamedCurves.getByName(curveName); curve = x9Curve.getCurve(); } // this means we just lookup the curve via the OID else if (serializationType == usesOid) { String oid = input.readString(); X9ECParameters x9Curve = CustomNamedCurves.getByOID(new ASN1ObjectIdentifier(oid)); curve = x9Curve.getCurve(); } // we have to read in the entire curve information. else { ///////////// length = input.readInt(true); bytes = new byte[length]; input.readBytes(bytes, 0, length); BigInteger a = new BigInteger(bytes); ///////////// length = input.readInt(true); bytes = new byte[length]; input.readBytes(bytes, 0, length); BigInteger b = new BigInteger(bytes); ///////////// length = input.readInt(true); bytes = new byte[length]; input.readBytes(bytes, 0, length); BigInteger order = new BigInteger(bytes); ///////////// length = input.readInt(true); bytes = new byte[length]; input.readBytes(bytes, 0, length); BigInteger cofactor = new BigInteger(bytes); ///////////// length = input.readInt(true); bytes = new byte[length]; input.readBytes(bytes, 0, length); BigInteger q = new BigInteger(bytes); // coord system int coordinateSystem = input.readInt(true); curve = new ECCurve.Fp(q, a, b, order, cofactor); ecCurveAccess.setInt(curve, ecCoordIndex, coordinateSystem); } return curve; }
From source file:net.schmizz.sshj.transport.kex.Curve25519DH.java
License:Apache License
/** * TODO want to figure out why BouncyCastle does not work. * @return The initialized curve25519 parameter spec *//*from ww w. j av a2 s . co m*/ public static AlgorithmParameterSpec getCurve25519Params() { X9ECParameters ecP = CustomNamedCurves.getByName("curve25519"); return new ECParameterSpec(ecP.getCurve(), ecP.getG(), ecP.getN(), ecP.getH(), ecP.getSeed()); }
From source file:org.cryptoworkshop.ximix.node.crypto.key.ECKeyPairGenerator.java
License:Apache License
public MessageReply handle(final KeyPairGenerateMessage message) { // TODO: sort out the reply messages try {//from w ww. ja v a2s . c om 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())); } }
From source file:org.cryptoworkshop.ximix.node.crypto.test.ECKeyManagerTest.java
License:Apache License
@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 {/* ww w .j a v a 2 s.co m*/ 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()); } }