Search in sources :

Example 16 with ECPrivateKeyParameters

use of org.bouncycastle.crypto.params.ECPrivateKeyParameters in project web3sdk by FISCO-BCOS.

the class SM2Signer method generateSignature.

@Override
public byte[] generateSignature() throws CryptoException {
    byte[] eHash = digestDoFinal();
    BigInteger n = ecParams.getN();
    BigInteger e = calculateE(eHash);
    BigInteger d = ((ECPrivateKeyParameters) ecKey).getD();
    BigInteger r, s;
    ECMultiplier basePointMultiplier = createBasePointMultiplier();
    // 5.2.1 Draft RFC:  SM2 Public Key Algorithms
    do // generate s
    {
        BigInteger k;
        do // generate r
        {
            // A3
            k = kCalculator.nextK();
            // A4
            ECPoint p = basePointMultiplier.multiply(ecParams.getG(), k).normalize();
            // A5
            r = e.add(p.getAffineXCoord().toBigInteger()).mod(n);
        } while (r.equals(ZERO) || r.add(k).equals(n));
        // A6
        BigInteger dPlus1ModN = d.add(ONE).modInverse(n);
        s = k.subtract(r.multiply(d)).mod(n);
        s = dPlus1ModN.multiply(s).mod(n);
    } while (s.equals(ZERO));
    // A7
    try {
        return derEncode(r, s);
    } catch (IOException ex) {
        throw new CryptoException("unable to encode signature: " + ex.getMessage(), ex);
    }
}
Also used : ECPrivateKeyParameters(org.bouncycastle.crypto.params.ECPrivateKeyParameters) BigInteger(java.math.BigInteger) ECMultiplier(org.bouncycastle.math.ec.ECMultiplier) IOException(java.io.IOException) ECPoint(org.bouncycastle.math.ec.ECPoint) CryptoException(org.bouncycastle.crypto.CryptoException)

Example 17 with ECPrivateKeyParameters

use of org.bouncycastle.crypto.params.ECPrivateKeyParameters in project web3sdk by FISCO-BCOS.

the class SM2Signer method generateSignature2.

public BigInteger[] generateSignature2() throws CryptoException {
    byte[] eHash = digestDoFinal();
    BigInteger n = ecParams.getN();
    BigInteger e = calculateE(eHash);
    BigInteger d = ((ECPrivateKeyParameters) ecKey).getD();
    BigInteger r, s;
    ECMultiplier basePointMultiplier = createBasePointMultiplier();
    // 5.2.1 Draft RFC:  SM2 Public Key Algorithms
    do // generate s
    {
        BigInteger k;
        do // generate r
        {
            // A3
            k = kCalculator.nextK();
            // A4
            ECPoint p = basePointMultiplier.multiply(ecParams.getG(), k).normalize();
            // A5
            r = e.add(p.getAffineXCoord().toBigInteger()).mod(n);
        } while (r.equals(ZERO) || r.add(k).equals(n));
        // A6
        BigInteger dPlus1ModN = d.add(ONE).modInverse(n);
        s = k.subtract(r.multiply(d)).mod(n);
        s = dPlus1ModN.multiply(s).mod(n);
    } while (s.equals(ZERO));
    return new BigInteger[] { r, s };
}
Also used : ECPrivateKeyParameters(org.bouncycastle.crypto.params.ECPrivateKeyParameters) BigInteger(java.math.BigInteger) ECMultiplier(org.bouncycastle.math.ec.ECMultiplier) ECPoint(org.bouncycastle.math.ec.ECPoint)

Example 18 with ECPrivateKeyParameters

use of org.bouncycastle.crypto.params.ECPrivateKeyParameters in project hutool by looly.

the class SM2Test method getPublicKeyByPrivateKeyTest.

@Test
public void getPublicKeyByPrivateKeyTest() {
    // issue#I38SDP,openSSL生成的PKCS#1格式私钥
    String priKey = "MHcCAQEEIE29XqAFV/rkJbnJzCoQRJLTeAHG2TR0h9ZCWag0+ZMEoAoGCCqBHM9VAYItoUQDQgAESkOzNigIsH5ehFvr9y" + "QNQ66genyOrm+Q4umCA4aWXPeRzmcTAWSlTineiReTFN2lqor2xaulT8u3a4w3AM/F6A==";
    PrivateKey privateKey = KeyUtil.generatePrivateKey("sm2", new OpenSSHPrivateKeySpec(SecureUtil.decode(priKey)));
    final ECPrivateKeyParameters privateKeyParameters = ECKeyUtil.toPrivateParams(privateKey);
    final SM2 sm2 = new SM2(privateKeyParameters, ECKeyUtil.getPublicParams(privateKeyParameters));
    String src = "Sm2Test";
    byte[] data = sm2.encrypt(src, KeyType.PublicKey);
    byte[] sign = sm2.sign(src.getBytes(StandardCharsets.UTF_8));
    Assert.assertTrue(sm2.verify(src.getBytes(StandardCharsets.UTF_8), sign));
    byte[] dec = sm2.decrypt(data, KeyType.PrivateKey);
    Assert.assertArrayEquals(dec, src.getBytes(StandardCharsets.UTF_8));
}
Also used : ECPrivateKeyParameters(org.bouncycastle.crypto.params.ECPrivateKeyParameters) PrivateKey(java.security.PrivateKey) OpenSSHPrivateKeySpec(org.bouncycastle.jcajce.spec.OpenSSHPrivateKeySpec) SM2(cn.hutool.crypto.asymmetric.SM2) Test(org.junit.Test)

Example 19 with ECPrivateKeyParameters

use of org.bouncycastle.crypto.params.ECPrivateKeyParameters in project hutool by looly.

the class BCUtilTest method createECPrivateKeyParametersTest.

@Test
public void createECPrivateKeyParametersTest() {
    String privateKeyHex = "5F6CA5BB044C40ED2355F0372BF72A5B3AE6943712F9FDB7C1FFBAECC06F3829";
    final ECPrivateKeyParameters keyParameters = BCUtil.toSm2Params(privateKeyHex);
    Assert.assertNotNull(keyParameters);
}
Also used : ECPrivateKeyParameters(org.bouncycastle.crypto.params.ECPrivateKeyParameters) Test(org.junit.Test)

Example 20 with ECPrivateKeyParameters

use of org.bouncycastle.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 = 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)

Aggregations

ECPrivateKeyParameters (org.bouncycastle.crypto.params.ECPrivateKeyParameters)26 BigInteger (java.math.BigInteger)20 ECPoint (org.bouncycastle.math.ec.ECPoint)11 ECDomainParameters (org.bouncycastle.crypto.params.ECDomainParameters)8 ECPublicKeyParameters (org.bouncycastle.crypto.params.ECPublicKeyParameters)5 ECDSASigner (org.bouncycastle.crypto.signers.ECDSASigner)5 ECMultiplier (org.bouncycastle.math.ec.ECMultiplier)5 IOException (java.io.IOException)4 ASN1Integer (org.bouncycastle.asn1.ASN1Integer)4 X9ECParameters (org.bouncycastle.asn1.x9.X9ECParameters)4 AsymmetricCipherKeyPair (org.bouncycastle.crypto.AsymmetricCipherKeyPair)4 SHA256Digest (org.bouncycastle.crypto.digests.SHA256Digest)4 HMacDSAKCalculator (org.bouncycastle.crypto.signers.HMacDSAKCalculator)4 DSAPrivateKeyParameters (org.bouncycastle.crypto.params.DSAPrivateKeyParameters)3 ParametersWithRandom (org.bouncycastle.crypto.params.ParametersWithRandom)3 InvalidKeyException (java.security.InvalidKeyException)2 PrivateKey (java.security.PrivateKey)2 ASN1EncodableVector (org.bouncycastle.asn1.ASN1EncodableVector)2 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)2 DHParameter (org.bouncycastle.asn1.pkcs.DHParameter)2