Search in sources :

Example 1 with ECPrivateKeyParameters

use of org.spongycastle.crypto.params.ECPrivateKeyParameters in project rskj by rsksmart.

the class BridgeSupportTest method addSignatureFromValidFederator.

/**
 * 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"
 */
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 = new RepositoryImpl(config);
    final Keccak256 keccak256 = PegTestUtils.createHash3();
    Repository track = repository.startTracking();
    BridgeStorageProvider provider = new BridgeStorageProvider(track, PrecompiledContracts.BRIDGE_ADDR, config.getBlockchainConfig().getCommonConstants().getBridgeConstants());
    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, (Block) null);
    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(1, findPublicKeySignedBy(federation.getPublicKeys(), privateKeysToSignWith.get(0)), derEncodedSigs, keccak256.getBytes());
    if (signTwice) {
        // Create another valid signature with the same private key
        ECDSASigner signer = new ECDSASigner();
        ECPrivateKeyParameters privKey = new ECPrivateKeyParameters(privateKeysToSignWith.get(0).getPrivKey(), BtcECKey.CURVE);
        signer.init(true, privKey);
        BigInteger[] components = signer.generateSignature(sighash.getBytes());
        BtcECKey.ECDSASignature sig2 = new BtcECKey.ECDSASignature(components[0], components[1]).toCanonicalised();
        bridgeSupport.addSignature(1, 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(1, findPublicKeySignedBy(federation.getPublicKeys(), privateKeysToSignWith.get(1)), derEncodedSigs2, keccak256.getBytes());
    }
    bridgeSupport.save();
    track.commit();
    provider = new BridgeStorageProvider(repository, PrecompiledContracts.BRIDGE_ADDR, config.getBlockchainConfig().getCommonConstants().getBridgeConstants());
    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());
        // for "InvalidParameters"
        boolean expectSignatureToBePersisted = false;
        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);
    }
}
Also used : RLPList(org.ethereum.util.RLPList) BridgeEventLogger(co.rsk.peg.utils.BridgeEventLogger) BridgeEventLoggerImpl(co.rsk.peg.utils.BridgeEventLoggerImpl) Script(co.rsk.bitcoinj.script.Script) LogInfo(org.ethereum.vm.LogInfo) ECDSASigner(org.spongycastle.crypto.signers.ECDSASigner) Keccak256(co.rsk.crypto.Keccak256) ScriptChunk(co.rsk.bitcoinj.script.ScriptChunk) RLPList(org.ethereum.util.RLPList) ECPrivateKeyParameters(org.spongycastle.crypto.params.ECPrivateKeyParameters) RepositoryImpl(co.rsk.db.RepositoryImpl) BigInteger(java.math.BigInteger)

Example 2 with ECPrivateKeyParameters

use of org.spongycastle.crypto.params.ECPrivateKeyParameters in project java-tron by tronprotocol.

the class ECKey method doSign.

/**
 * Signs the given hash and returns the R and S components as BigIntegers and putData them in
 * ECDSASignature
 *
 * @param input to sign
 * @return ECDSASignature signature that contains the R and S components
 */
public ECDSASignature doSign(byte[] input) {
    if (input.length != 32) {
        throw new IllegalArgumentException("Expected 32 byte input to " + "ECDSA signature, not " + input.length);
    }
    // No decryption of private key required.
    if (privKey == null) {
        throw new MissingPrivateKeyException();
    }
    if (privKey instanceof BCECPrivateKey) {
        ECDSASigner signer = new ECDSASigner(new HMacDSAKCalculator(new SHA256Digest()));
        ECPrivateKeyParameters privKeyParams = new ECPrivateKeyParameters(((BCECPrivateKey) privKey).getD(), CURVE);
        signer.init(true, privKeyParams);
        BigInteger[] components = signer.generateSignature(input);
        return new ECDSASignature(components[0], components[1]).toCanonicalised();
    } else {
        try {
            final Signature ecSig = ECSignatureFactory.getRawInstance(provider);
            ecSig.initSign(privKey);
            ecSig.update(input);
            final byte[] derSignature = ecSig.sign();
            return ECDSASignature.decodeFromDER(derSignature).toCanonicalised();
        } catch (SignatureException | InvalidKeyException ex) {
            throw new RuntimeException("ECKey signing error", ex);
        }
    }
}
Also used : ECDSASigner(org.spongycastle.crypto.signers.ECDSASigner) SignatureException(java.security.SignatureException) InvalidKeyException(java.security.InvalidKeyException) BCECPrivateKey(org.spongycastle.jcajce.provider.asymmetric.ec.BCECPrivateKey) HMacDSAKCalculator(org.spongycastle.crypto.signers.HMacDSAKCalculator) ECPrivateKeyParameters(org.spongycastle.crypto.params.ECPrivateKeyParameters) SHA256Digest(org.spongycastle.crypto.digests.SHA256Digest) Signature(java.security.Signature) BigInteger(java.math.BigInteger)

Example 3 with ECPrivateKeyParameters

use of org.spongycastle.crypto.params.ECPrivateKeyParameters in project AppCoins-ethereumj by AppStoreFoundation.

the class ECKey method doSign.

/**
 * Signs the given hash and returns the R and S components as BigIntegers
 * and put them in ECDSASignature
 *
 * @param input to sign
 * @return ECDSASignature signature that contains the R and S components
 */
public ECDSASignature doSign(byte[] input) {
    if (input.length != 32) {
        throw new IllegalArgumentException("Expected 32 byte input to ECDSA signature, not " + input.length);
    }
    // No decryption of private key required.
    if (privKey == null)
        throw new MissingPrivateKeyException();
    if (privKey instanceof BCECPrivateKey) {
        ECDSASigner signer = new ECDSASigner(new HMacDSAKCalculator(new SHA256Digest()));
        ECPrivateKeyParameters privKeyParams = new ECPrivateKeyParameters(((BCECPrivateKey) privKey).getD(), CURVE);
        signer.init(true, privKeyParams);
        BigInteger[] components = signer.generateSignature(input);
        return new ECDSASignature(components[0], components[1]).toCanonicalised();
    } else {
        try {
            Signature ecSig = ECSignatureFactory.getRawInstance(provider);
            ecSig.initSign(privKey);
            ecSig.update(input);
            byte[] derSignature = ecSig.sign();
            return ECDSASignature.decodeFromDER(derSignature).toCanonicalised();
        } catch (SignatureException | InvalidKeyException ex) {
            throw new RuntimeException("ECKey signing error", ex);
        }
    }
}
Also used : ECDSASigner(org.spongycastle.crypto.signers.ECDSASigner) SignatureException(java.security.SignatureException) InvalidKeyException(java.security.InvalidKeyException) BCECPrivateKey(org.spongycastle.jcajce.provider.asymmetric.ec.BCECPrivateKey) HMacDSAKCalculator(org.spongycastle.crypto.signers.HMacDSAKCalculator) ECPrivateKeyParameters(org.spongycastle.crypto.params.ECPrivateKeyParameters) SHA256Digest(org.spongycastle.crypto.digests.SHA256Digest) Signature(java.security.Signature) BigInteger(java.math.BigInteger)

Example 4 with ECPrivateKeyParameters

use of org.spongycastle.crypto.params.ECPrivateKeyParameters in project aion by aionnetwork.

the class ECKeySecp256k1 method doSign.

/**
 * Groups the two components that make up a signature, and provides a way to
 * encode to Base64 form, which is how ECDSA signatures are represented when
 * embedded in other data structures in the Ethereum protocol. The raw
 * components can be useful for doing further EC maths on them.
 */
/**
 * Signs the given hash and returns the R and S components as BigIntegers
 * and put them in ECDSASignature
 *
 * @param input
 *            to sign
 * @return ECDSASignature signature that contains the R and S components
 */
public ECDSASignature doSign(byte[] input) {
    if (input.length != 32) {
        throw new IllegalArgumentException("Expected 32 byte input to ECDSA signature, not " + input.length);
    }
    // No decryption of private key required.
    if (privKey == null) {
        throw new MissingPrivateKeyException();
    }
    if (privKey instanceof BCECPrivateKey) {
        ECDSASigner signer = new ECDSASigner(new HMacDSAKCalculator(new SHA256Digest()));
        ECPrivateKeyParameters privKeyParams = new ECPrivateKeyParameters(((BCECPrivateKey) privKey).getD(), CURVE);
        signer.init(true, privKeyParams);
        BigInteger[] components = signer.generateSignature(input);
        return new ECDSASignature(components[0], components[1]).toCanonicalised();
    } else {
        try {
            final Signature ecSig = ECSignatureFactory.getRawInstance(provider);
            ecSig.initSign(privKey);
            ecSig.update(input);
            final byte[] derSignature = ecSig.sign();
            return ECDSASignature.decodeFromDER(derSignature).toCanonicalised();
        } catch (SignatureException | InvalidKeyException ex) {
            throw new RuntimeException("ECKey signing error", ex);
        }
    }
}
Also used : ECDSASigner(org.spongycastle.crypto.signers.ECDSASigner) SignatureException(java.security.SignatureException) InvalidKeyException(java.security.InvalidKeyException) BCECPrivateKey(org.spongycastle.jcajce.provider.asymmetric.ec.BCECPrivateKey) HMacDSAKCalculator(org.spongycastle.crypto.signers.HMacDSAKCalculator) ECPrivateKeyParameters(org.spongycastle.crypto.params.ECPrivateKeyParameters) SHA256Digest(org.spongycastle.crypto.digests.SHA256Digest) Signature(java.security.Signature) ISignature(org.aion.crypto.ISignature) BigInteger(java.math.BigInteger)

Example 5 with ECPrivateKeyParameters

use of org.spongycastle.crypto.params.ECPrivateKeyParameters in project SmartMesh_Android by SmartMeshFoundation.

the class Sign2 method sign.

private static ECDSASignature sign(byte[] transactionHash, BigInteger privateKey) {
    ECDSASigner signer = new ECDSASigner(new HMacDSAKCalculator(new SHA256Digest()));
    ECPrivateKeyParameters privKey = new ECPrivateKeyParameters(privateKey, CURVE);
    signer.init(true, privKey);
    BigInteger[] components = signer.generateSignature(transactionHash);
    return new ECDSASignature(components[0], components[1]).toCanonicalised();
}
Also used : HMacDSAKCalculator(org.spongycastle.crypto.signers.HMacDSAKCalculator) ECPrivateKeyParameters(org.spongycastle.crypto.params.ECPrivateKeyParameters) ECDSASigner(org.spongycastle.crypto.signers.ECDSASigner) SHA256Digest(org.spongycastle.crypto.digests.SHA256Digest) BigInteger(java.math.BigInteger)

Aggregations

BigInteger (java.math.BigInteger)6 ECPrivateKeyParameters (org.spongycastle.crypto.params.ECPrivateKeyParameters)6 ECDSASigner (org.spongycastle.crypto.signers.ECDSASigner)6 SHA256Digest (org.spongycastle.crypto.digests.SHA256Digest)5 HMacDSAKCalculator (org.spongycastle.crypto.signers.HMacDSAKCalculator)5 InvalidKeyException (java.security.InvalidKeyException)4 Signature (java.security.Signature)4 SignatureException (java.security.SignatureException)4 BCECPrivateKey (org.spongycastle.jcajce.provider.asymmetric.ec.BCECPrivateKey)4 Script (co.rsk.bitcoinj.script.Script)1 ScriptChunk (co.rsk.bitcoinj.script.ScriptChunk)1 Keccak256 (co.rsk.crypto.Keccak256)1 RepositoryImpl (co.rsk.db.RepositoryImpl)1 BridgeEventLogger (co.rsk.peg.utils.BridgeEventLogger)1 BridgeEventLoggerImpl (co.rsk.peg.utils.BridgeEventLoggerImpl)1 ISignature (org.aion.crypto.ISignature)1 RLPList (org.ethereum.util.RLPList)1 LogInfo (org.ethereum.vm.LogInfo)1