Search in sources :

Example 6 with ECDSASigner

use of org.bouncycastle.crypto.signers.ECDSASigner 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 = createRepository();
    final Keccak256 keccak256 = PegTestUtils.createHash3();
    Repository track = repository.startTracking();
    BridgeStorageProvider provider = new BridgeStorageProvider(track, PrecompiledContracts.BRIDGE_ADDR, bridgeConstants, activationsBeforeForks);
    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(createBaseInputScriptThatSpendsFromTheFederation(federation));
    provider.getRskTxsWaitingForSignatures().put(keccak256, t);
    provider.save();
    track.commit();
    track = repository.startTracking();
    ActivationConfig.ForBlock activations = mock(ActivationConfig.ForBlock.class);
    List<LogInfo> logs = new ArrayList<>();
    BridgeEventLogger eventLogger = new BridgeEventLoggerImpl(bridgeConstants, activations, logs);
    BridgeSupport bridgeSupport = getBridgeSupport(bridgeConstants, new BridgeStorageProvider(track, contractAddress, bridgeConstants, activationsAfterForks), track, eventLogger, mock(Block.class), 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(findPublicKeySignedBy(federation.getBtcPublicKeys(), 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.getBtcPublicKeys(), 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.getBtcPublicKeys(), privateKeysToSignWith.get(1)), derEncodedSigs2, keccak256.getBytes());
    }
    bridgeSupport.save();
    track.commit();
    provider = new BridgeStorageProvider(repository, PrecompiledContracts.BRIDGE_ADDR, bridgeConstants, activationsBeforeForks);
    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(btcParams, ((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 : ECDomainParameters(org.bouncycastle.crypto.params.ECDomainParameters) X9ECParameters(org.bouncycastle.asn1.x9.X9ECParameters) PegTestUtils.createBaseInputScriptThatSpendsFromTheFederation(co.rsk.peg.PegTestUtils.createBaseInputScriptThatSpendsFromTheFederation) PegTestUtils.createBaseRedeemScriptThatSpendsFromTheFederation(co.rsk.peg.PegTestUtils.createBaseRedeemScriptThatSpendsFromTheFederation) RLPList(org.ethereum.util.RLPList) Script(co.rsk.bitcoinj.script.Script) LogInfo(org.ethereum.vm.LogInfo) ECDSASigner(org.bouncycastle.crypto.signers.ECDSASigner) Keccak256(co.rsk.crypto.Keccak256) ScriptChunk(co.rsk.bitcoinj.script.ScriptChunk) RLPList(org.ethereum.util.RLPList) ActivationConfig(org.ethereum.config.blockchain.upgrades.ActivationConfig) ECPrivateKeyParameters(org.bouncycastle.crypto.params.ECPrivateKeyParameters) Repository(org.ethereum.core.Repository) MutableRepository(org.ethereum.db.MutableRepository) Block(org.ethereum.core.Block) BigInteger(java.math.BigInteger)

Example 7 with ECDSASigner

use of org.bouncycastle.crypto.signers.ECDSASigner in project xipki by xipki.

the class XiECContentVerifierProviderBuilder method createSigner.

protected Signer createSigner(AlgorithmIdentifier sigAlgId) throws OperatorCreationException {
    boolean plainDsa = AlgorithmUtil.isPlainECDSASigAlg(sigAlgId);
    if (plainDsa) {
        AlgorithmIdentifier digAlg = digestAlgorithmFinder.find(sigAlgId);
        Digest dig = digestProvider.get(digAlg);
        return new DSAPlainDigestSigner(new ECDSASigner(), dig);
    }
    boolean sm2 = AlgorithmUtil.isSM2SigAlg(sigAlgId);
    if (sm2) {
        AlgorithmIdentifier digAlg = digestAlgorithmFinder.find(sigAlgId);
        if (GMObjectIdentifiers.sm3.equals(digAlg.getAlgorithm())) {
            return new SM2Signer();
        } else {
            throw new OperatorCreationException("cannot create SM2 signer for hash algorithm " + digAlg.getAlgorithm().getId());
        }
    }
    return super.createSigner(sigAlgId);
}
Also used : Digest(org.bouncycastle.crypto.Digest) ECDSASigner(org.bouncycastle.crypto.signers.ECDSASigner) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) SM2Signer(org.bouncycastle.crypto.signers.SM2Signer) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) DSAPlainDigestSigner(org.xipki.security.pkcs12.DSAPlainDigestSigner)

Example 8 with ECDSASigner

use of org.bouncycastle.crypto.signers.ECDSASigner in project web3sdk by FISCO-BCOS.

the class ECKeyPair method verify.

/**
 * Verify a hash with the private key of this key pair.
 *
 * @param hash
 * @param signature
 * @return
 */
public boolean verify(byte[] hash, ECDSASignature signature) {
    ECDSASigner signer = new ECDSASigner();
    // not for signing...
    signer.init(false, new ECPublicKeyParameters(Sign.publicPointFromPrivate(getPrivateKey()), Sign.CURVE));
    return signer.verifySignature(hash, signature.r, signature.s);
}
Also used : ECDSASigner(org.bouncycastle.crypto.signers.ECDSASigner) ECPublicKeyParameters(org.bouncycastle.crypto.params.ECPublicKeyParameters)

Example 9 with ECDSASigner

use of org.bouncycastle.crypto.signers.ECDSASigner in project OsmAnd-tools by osmandapp.

the class SigningUtils method signData.

static String signData(String input, byte[] key) throws BlockIOException {
    ECDSASigner signer = new ECDSASigner(new HMacDSAKCalculator(new SHA256Digest()));
    X9ECParameters params = SECNamedCurves.getByName("secp256k1");
    ECDomainParameters ecParams = new ECDomainParameters(params.getCurve(), params.getG(), params.getN(), params.getH());
    BigInteger priv = new BigInteger(1, key);
    ECPrivateKeyParameters privKey = new ECPrivateKeyParameters(priv, ecParams);
    signer.init(true, privKey);
    BigInteger[] sigs = signer.generateSignature(fromHex(input));
    BigInteger r = sigs[0];
    BigInteger s = sigs[1];
    // BIP62: "S must be less than or equal to half of the Group Order N"
    BigInteger overTwo = params.getN().shiftRight(1);
    if (s.compareTo(overTwo) == 1) {
        s = params.getN().subtract(s);
    }
    try {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        DERSequenceGenerator seq = new DERSequenceGenerator(bos);
        seq.addObject(new ASN1Integer(r));
        seq.addObject(new ASN1Integer(s));
        seq.close();
        return toHex(bos.toByteArray());
    } catch (IOException e) {
        // Cannot happen.
        throw new BlockIOException("That should never happen... File an issue report.");
    }
}
Also used : ECDomainParameters(org.bouncycastle.crypto.params.ECDomainParameters) ECDSASigner(org.bouncycastle.crypto.signers.ECDSASigner) X9ECParameters(org.bouncycastle.asn1.x9.X9ECParameters) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ASN1Integer(org.bouncycastle.asn1.ASN1Integer) IOException(java.io.IOException) HMacDSAKCalculator(org.bouncycastle.crypto.signers.HMacDSAKCalculator) ECPrivateKeyParameters(org.bouncycastle.crypto.params.ECPrivateKeyParameters) SHA256Digest(org.bouncycastle.crypto.digests.SHA256Digest) BigInteger(java.math.BigInteger) DERSequenceGenerator(org.bouncycastle.asn1.DERSequenceGenerator)

Aggregations

ECDSASigner (org.bouncycastle.crypto.signers.ECDSASigner)9 BigInteger (java.math.BigInteger)6 ECPrivateKeyParameters (org.bouncycastle.crypto.params.ECPrivateKeyParameters)5 SHA256Digest (org.bouncycastle.crypto.digests.SHA256Digest)4 HMacDSAKCalculator (org.bouncycastle.crypto.signers.HMacDSAKCalculator)4 IOException (java.io.IOException)2 ASN1Integer (org.bouncycastle.asn1.ASN1Integer)2 X9ECParameters (org.bouncycastle.asn1.x9.X9ECParameters)2 ECDomainParameters (org.bouncycastle.crypto.params.ECDomainParameters)2 ECPublicKeyParameters (org.bouncycastle.crypto.params.ECPublicKeyParameters)2 Script (co.rsk.bitcoinj.script.Script)1 ScriptChunk (co.rsk.bitcoinj.script.ScriptChunk)1 Keccak256 (co.rsk.crypto.Keccak256)1 PegTestUtils.createBaseInputScriptThatSpendsFromTheFederation (co.rsk.peg.PegTestUtils.createBaseInputScriptThatSpendsFromTheFederation)1 PegTestUtils.createBaseRedeemScriptThatSpendsFromTheFederation (co.rsk.peg.PegTestUtils.createBaseRedeemScriptThatSpendsFromTheFederation)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 ECPrivateKey (java.security.interfaces.ECPrivateKey)1 ASN1EncodableVector (org.bouncycastle.asn1.ASN1EncodableVector)1 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)1 ASN1OutputStream (org.bouncycastle.asn1.ASN1OutputStream)1