Search in sources :

Example 81 with Signature

use of org.bouncycastle.asn1.ocsp.Signature in project athenz by yahoo.

the class CryptoTest method testSignVerifyECParamPrime256v1Key.

@Test
public void testSignVerifyECParamPrime256v1Key() {
    PrivateKey privateKey = Crypto.loadPrivateKey(ecPrivateParamPrime256v1Key);
    assertNotNull(privateKey);
    String signature = Crypto.sign(serviceToken, privateKey);
    PublicKey publicKey = Crypto.loadPublicKey(ecPublicParamPrime256v1Key);
    assertNotNull(publicKey);
    assertTrue(Crypto.verify(serviceToken, publicKey, signature));
}
Also used : PrivateKey(java.security.PrivateKey) PublicKey(java.security.PublicKey) DERIA5String(org.bouncycastle.asn1.DERIA5String) Test(org.testng.annotations.Test)

Example 82 with Signature

use of org.bouncycastle.asn1.ocsp.Signature in project athenz by yahoo.

the class CryptoTest method testSignVerifyExtractedRSAKey.

@Test
public void testSignVerifyExtractedRSAKey() {
    PrivateKey privateKey = Crypto.loadPrivateKey(rsaPrivateKey);
    assertNotNull(privateKey);
    String signature = Crypto.sign(serviceToken, privateKey);
    assertEquals(signature, serviceRSASignature);
    PublicKey publicKey = Crypto.extractPublicKey(privateKey);
    assertNotNull(publicKey);
    assertTrue(Crypto.verify(serviceToken, publicKey, signature));
}
Also used : PrivateKey(java.security.PrivateKey) PublicKey(java.security.PublicKey) DERIA5String(org.bouncycastle.asn1.DERIA5String) Test(org.testng.annotations.Test)

Example 83 with Signature

use of org.bouncycastle.asn1.ocsp.Signature in project athenz by yahoo.

the class CryptoTest method testSignVerifyECParamKeyOpenssl.

@Test
public void testSignVerifyECParamKeyOpenssl() {
    PublicKey publicKey = Crypto.loadPublicKey(ecPublicParamPrime256v1Key);
    assertNotNull(publicKey);
    // this test case is from ysecure using openssl
    String plainText = "This is a test of the ysecure public key interface.  This is only a test.";
    String signature = "MEUCIBjTLIhH_Rc3fkRXJ8CvzSqkIwxXqReg7nOe_q1t_C73AiEAky4NAP.CwlYKXlto93f_JTYOQqDpZSJeTYSe80fQ5vY-";
    assertTrue(Crypto.verify(plainText, publicKey, signature));
}
Also used : PublicKey(java.security.PublicKey) DERIA5String(org.bouncycastle.asn1.DERIA5String) Test(org.testng.annotations.Test)

Example 84 with Signature

use of org.bouncycastle.asn1.ocsp.Signature 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 85 with Signature

use of org.bouncycastle.asn1.ocsp.Signature in project airlift by airlift.

the class TestCertificationRequest method test.

@Test
public void test() throws Exception {
    // test only with state because BC encodes every other value using UTF8String instead of PrintableString used by the JDK
    String name = "C=country";
    KeyPairGenerator generator = KeyPairGenerator.getInstance("EC");
    generator.initialize(new ECGenParameterSpec("secp256r1"));
    KeyPair keyPair = generator.generateKeyPair();
    CertificationRequestInfo certificationRequestInfo = new CertificationRequestInfo(new X500Principal(name), keyPair.getPublic());
    SignatureAlgorithmIdentifier signatureAlgorithmIdentifier = findSignatureAlgorithmIdentifier("SHA256withECDSA");
    byte[] signature = certificationRequestInfo.sign(signatureAlgorithmIdentifier, keyPair.getPrivate());
    CertificationRequest certificationRequest = new CertificationRequest(certificationRequestInfo, signatureAlgorithmIdentifier, signature);
    assertEquals(certificationRequest.getCertificationRequestInfo(), certificationRequestInfo);
    assertEquals(certificationRequest.getSignatureAlgorithmIdentifier(), signatureAlgorithmIdentifier);
    assertEquals(base16().encode(certificationRequest.getSignature()), base16().encode(signature));
    assertEquals(certificationRequest, certificationRequest);
    assertEquals(certificationRequest.hashCode(), certificationRequest.hashCode());
    PKCS10CertificationRequest expectedCertificationRequest = new PKCS10CertificationRequest(new org.bouncycastle.asn1.pkcs.CertificationRequest(new org.bouncycastle.asn1.pkcs.CertificationRequestInfo(new X500Name(name), SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()), new DERSet()), new DefaultSignatureAlgorithmIdentifierFinder().find("SHA256withECDSA"), new DERBitString(signature)));
    assertEquals(base16().encode(certificationRequest.getEncoded()), base16().encode(expectedCertificationRequest.getEncoded()));
}
Also used : PKCS10CertificationRequest(org.bouncycastle.pkcs.PKCS10CertificationRequest) KeyPair(java.security.KeyPair) ECGenParameterSpec(java.security.spec.ECGenParameterSpec) DERBitString(org.bouncycastle.asn1.DERBitString) DERBitString(org.bouncycastle.asn1.DERBitString) KeyPairGenerator(java.security.KeyPairGenerator) X500Name(org.bouncycastle.asn1.x500.X500Name) DERSet(org.bouncycastle.asn1.DERSet) DefaultSignatureAlgorithmIdentifierFinder(org.bouncycastle.operator.DefaultSignatureAlgorithmIdentifierFinder) SignatureAlgorithmIdentifier.findSignatureAlgorithmIdentifier(io.airlift.security.csr.SignatureAlgorithmIdentifier.findSignatureAlgorithmIdentifier) X500Principal(javax.security.auth.x500.X500Principal) PKCS10CertificationRequest(org.bouncycastle.pkcs.PKCS10CertificationRequest) Test(org.testng.annotations.Test)

Aggregations

IOException (java.io.IOException)58 DERIA5String (org.bouncycastle.asn1.DERIA5String)36 ASN1EncodableVector (org.bouncycastle.asn1.ASN1EncodableVector)31 DERBitString (org.bouncycastle.asn1.DERBitString)31 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)30 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)30 InvalidKeyException (java.security.InvalidKeyException)28 X509Certificate (java.security.cert.X509Certificate)28 SignatureException (java.security.SignatureException)27 DERSequence (org.bouncycastle.asn1.DERSequence)26 PublicKey (java.security.PublicKey)25 ASN1InputStream (org.bouncycastle.asn1.ASN1InputStream)23 DEROctetString (org.bouncycastle.asn1.DEROctetString)22 AlgorithmIdentifier (org.bouncycastle.asn1.x509.AlgorithmIdentifier)22 Signature (java.security.Signature)21 CertificateException (java.security.cert.CertificateException)21 BigInteger (java.math.BigInteger)20 OperatorCreationException (org.bouncycastle.operator.OperatorCreationException)19 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)18 NoSuchProviderException (java.security.NoSuchProviderException)16