Search in sources :

Example 16 with CryptoException

use of org.hyperledger.fabric.sdk.exception.CryptoException in project fabric-sdk-java by hyperledger.

the class CryptoPrimitives method decodeECDSASignature.

/**
 * Decodes an ECDSA signature and returns a two element BigInteger array.
 *
 * @param signature ECDSA signature bytes.
 * @return BigInteger array for the signature's r and s values
 * @throws Exception
 */
private static BigInteger[] decodeECDSASignature(byte[] signature) throws Exception {
    ByteArrayInputStream inStream = new ByteArrayInputStream(signature);
    ASN1InputStream asnInputStream = new ASN1InputStream(inStream);
    ASN1Primitive asn1 = asnInputStream.readObject();
    BigInteger[] sigs = new BigInteger[2];
    int count = 0;
    if (asn1 instanceof ASN1Sequence) {
        ASN1Sequence asn1Sequence = (ASN1Sequence) asn1;
        ASN1Encodable[] asn1Encodables = asn1Sequence.toArray();
        for (ASN1Encodable asn1Encodable : asn1Encodables) {
            ASN1Primitive asn1Primitive = asn1Encodable.toASN1Primitive();
            if (asn1Primitive instanceof ASN1Integer) {
                ASN1Integer asn1Integer = (ASN1Integer) asn1Primitive;
                BigInteger integer = asn1Integer.getValue();
                if (count < 2) {
                    sigs[count] = integer;
                }
                count++;
            }
        }
    }
    if (count != 2) {
        throw new CryptoException(format("Invalid ECDSA signature. Expected count of 2 but got: %d. Signature is: %s", count, DatatypeConverter.printHexBinary(signature)));
    }
    return sigs;
}
Also used : ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) ByteArrayInputStream(java.io.ByteArrayInputStream) BigInteger(java.math.BigInteger) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) ASN1Integer(org.bouncycastle.asn1.ASN1Integer) CryptoException(org.hyperledger.fabric.sdk.exception.CryptoException) ASN1Primitive(org.bouncycastle.asn1.ASN1Primitive)

Example 17 with CryptoException

use of org.hyperledger.fabric.sdk.exception.CryptoException in project fabric-sdk-java by hyperledger.

the class CryptoPrimitives method validateCertificate.

boolean validateCertificate(Certificate cert) {
    boolean isValidated;
    if (cert == null) {
        return false;
    }
    try {
        KeyStore keyStore = getTrustStore();
        PKIXParameters parms = new PKIXParameters(keyStore);
        parms.setRevocationEnabled(false);
        // PKIX
        CertPathValidator certValidator = CertPathValidator.getInstance(CertPathValidator.getDefaultType());
        ArrayList<Certificate> start = new ArrayList<>();
        start.add(cert);
        CertificateFactory certFactory = CertificateFactory.getInstance(CERTIFICATE_FORMAT);
        CertPath certPath = certFactory.generateCertPath(start);
        certValidator.validate(certPath, parms);
        isValidated = true;
    } catch (KeyStoreException | InvalidAlgorithmParameterException | NoSuchAlgorithmException | CertificateException | CertPathValidatorException | CryptoException e) {
        logger.error("Cannot validate certificate. Error is: " + e.getMessage() + "\r\nCertificate" + cert.toString());
        isValidated = false;
    }
    return isValidated;
}
Also used : InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) ArrayList(java.util.ArrayList) CertificateException(java.security.cert.CertificateException) KeyStoreException(java.security.KeyStoreException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyStore(java.security.KeyStore) CertificateFactory(java.security.cert.CertificateFactory) CertPathValidator(java.security.cert.CertPathValidator) CertPathValidatorException(java.security.cert.CertPathValidatorException) PKIXParameters(java.security.cert.PKIXParameters) CertPath(java.security.cert.CertPath) CryptoException(org.hyperledger.fabric.sdk.exception.CryptoException) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 18 with CryptoException

use of org.hyperledger.fabric.sdk.exception.CryptoException in project fabric-sdk-java by hyperledger.

the class CryptoPrimitives method getX509Certificate.

/**
 * Return X509Certificate  from pem bytes.
 * So you may ask why this ?  Well some providers (BC) seems to have problems with creating the
 * X509 cert from bytes so here we go through all available providers till one can convert. :)
 *
 * @param pemCertificate
 * @return
 */
private X509Certificate getX509Certificate(byte[] pemCertificate) throws CryptoException {
    X509Certificate ret = null;
    CryptoException rete = null;
    List<Provider> providerList = new LinkedList<>(Arrays.asList(Security.getProviders()));
    if (SECURITY_PROVIDER != null) {
        // Add
        providerList.add(0, SECURITY_PROVIDER);
    }
    try {
        providerList.add(BouncyCastleProvider.class.newInstance());
    } catch (Exception e) {
        logger.warn(e);
    }
    for (Provider provider : providerList) {
        try {
            if (null == provider) {
                continue;
            }
            CertificateFactory certFactory = CertificateFactory.getInstance(CERTIFICATE_FORMAT, provider);
            if (null != certFactory) {
                // BufferedInputStream pem = new BufferedInputStream(new ByteArrayInputStream(pemCertificate));
                Certificate certificate = certFactory.generateCertificate(new ByteArrayInputStream(pemCertificate));
                if (certificate instanceof X509Certificate) {
                    ret = (X509Certificate) certificate;
                    rete = null;
                    break;
                }
            }
        } catch (Exception e) {
            rete = new CryptoException(e.getMessage(), e);
        }
    }
    if (null != rete) {
        throw rete;
    }
    if (ret == null) {
        logger.error("Could not convert pem bytes");
    }
    return ret;
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) CryptoException(org.hyperledger.fabric.sdk.exception.CryptoException) CertificateFactory(java.security.cert.CertificateFactory) X509Certificate(java.security.cert.X509Certificate) LinkedList(java.util.LinkedList) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) KeyStoreException(java.security.KeyStoreException) CertPathValidatorException(java.security.cert.CertPathValidatorException) InvalidArgumentException(org.hyperledger.fabric.sdk.exception.InvalidArgumentException) SignatureException(java.security.SignatureException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) CryptoException(org.hyperledger.fabric.sdk.exception.CryptoException) Provider(java.security.Provider) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 19 with CryptoException

use of org.hyperledger.fabric.sdk.exception.CryptoException in project fabric-sdk-java by hyperledger.

the class HLSDKJCryptoSuiteFactory method getCryptoSuite.

@Override
public CryptoSuite getCryptoSuite(Properties properties) throws CryptoException, InvalidArgumentException {
    CryptoSuite ret = cache.get(properties);
    if (ret == null) {
        try {
            CryptoPrimitives cp = new CryptoPrimitives();
            cp.setProperties(properties);
            cp.init();
            ret = cp;
        } catch (Exception e) {
            throw new CryptoException(e.getMessage(), e);
        }
        cache.put(properties, ret);
    }
    return ret;
}
Also used : CryptoException(org.hyperledger.fabric.sdk.exception.CryptoException) InvalidArgumentException(org.hyperledger.fabric.sdk.exception.InvalidArgumentException) CryptoException(org.hyperledger.fabric.sdk.exception.CryptoException) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Example 20 with CryptoException

use of org.hyperledger.fabric.sdk.exception.CryptoException in project fabric-sdk-java by hyperledger.

the class EventHub method connect.

synchronized boolean connect(final TransactionContext transactionContext, final boolean reconnection) throws EventHubException {
    if (connected) {
        logger.warn(format("%s already connected.", toString()));
        return true;
    }
    eventStream = null;
    final CountDownLatch finishLatch = new CountDownLatch(1);
    logger.debug(format("EventHub %s is connecting.", name));
    lastConnectedAttempt = System.currentTimeMillis();
    Endpoint endpoint = new Endpoint(url, properties);
    managedChannel = endpoint.getChannelBuilder().build();
    clientTLSCertificateDigest = endpoint.getClientTLSCertificateDigest();
    events = EventsGrpc.newStub(managedChannel);
    final ArrayList<Throwable> threw = new ArrayList<>();
    final StreamObserver<PeerEvents.Event> eventStreamLocal = new StreamObserver<PeerEvents.Event>() {

        @Override
        public void onNext(PeerEvents.Event event) {
            logger.debug(format("EventHub %s got  event type: %s", EventHub.this.name, event.getEventCase().name()));
            if (event.getEventCase() == PeerEvents.Event.EventCase.BLOCK) {
                try {
                    BlockEvent blockEvent = new BlockEvent(EventHub.this, event);
                    setLastBlockSeen(blockEvent);
                    // add to channel queue
                    eventQue.addBEvent(blockEvent);
                } catch (InvalidProtocolBufferException e) {
                    EventHubException eventHubException = new EventHubException(format("%s onNext error %s", this, e.getMessage()), e);
                    logger.error(eventHubException.getMessage());
                    threw.add(eventHubException);
                }
            } else if (event.getEventCase() == PeerEvents.Event.EventCase.REGISTER) {
                if (reconnectCount > 1) {
                    logger.info(format("Eventhub %s has reconnecting after %d attempts", name, reconnectCount));
                }
                connected = true;
                connectedTime = System.currentTimeMillis();
                reconnectCount = 0L;
                finishLatch.countDown();
            }
        }

        @Override
        public void onError(Throwable t) {
            connected = false;
            eventStream = null;
            disconnectedTime = System.currentTimeMillis();
            if (shutdown) {
                // IF we're shutdown don't try anything more.
                logger.trace(format("%s was shutdown.", EventHub.this.toString()));
                finishLatch.countDown();
                return;
            }
            final ManagedChannel lmanagedChannel = managedChannel;
            final boolean isTerminated = lmanagedChannel == null ? true : lmanagedChannel.isTerminated();
            final boolean isChannelShutdown = lmanagedChannel == null ? true : lmanagedChannel.isShutdown();
            if (EVENTHUB_RECONNECTION_WARNING_RATE > 1 && reconnectCount % EVENTHUB_RECONNECTION_WARNING_RATE == 1) {
                logger.warn(format("%s terminated is %b shutdown is %b, retry count %d  has error %s.", EventHub.this.toString(), isTerminated, isChannelShutdown, reconnectCount, t.getMessage()));
            } else {
                logger.trace(format("%s terminated is %b shutdown is %b, retry count %d  has error %s.", EventHub.this.toString(), isTerminated, isChannelShutdown, reconnectCount, t.getMessage()));
            }
            finishLatch.countDown();
            // logger.error("Error in stream: " + t.getMessage(), new EventHubException(t));
            if (t instanceof StatusRuntimeException) {
                StatusRuntimeException sre = (StatusRuntimeException) t;
                Status sreStatus = sre.getStatus();
                if (EVENTHUB_RECONNECTION_WARNING_RATE > 1 && reconnectCount % EVENTHUB_RECONNECTION_WARNING_RATE == 1) {
                    logger.warn(format("%s :StatusRuntimeException Status %s.  Description %s ", EventHub.this, sreStatus + "", sreStatus.getDescription()));
                } else {
                    logger.trace(format("%s :StatusRuntimeException Status %s.  Description %s ", EventHub.this, sreStatus + "", sreStatus.getDescription()));
                }
                try {
                    reconnect();
                } catch (Exception e) {
                    logger.warn(format("Eventhub %s Failed shutdown msg:  %s", EventHub.this.name, e.getMessage()));
                }
            }
        }

        @Override
        public void onCompleted() {
            logger.debug(format("Stream completed %s", EventHub.this.toString()));
            finishLatch.countDown();
        }
    };
    sender = events.chat(eventStreamLocal);
    try {
        blockListen(transactionContext);
    } catch (CryptoException e) {
        throw new EventHubException(e);
    }
    try {
        if (!reconnection && !finishLatch.await(EVENTHUB_CONNECTION_WAIT_TIME, TimeUnit.MILLISECONDS)) {
            logger.warn(format("EventHub %s failed to connect in %s ms.", name, EVENTHUB_CONNECTION_WAIT_TIME));
        } else {
            logger.trace(format("Eventhub %s Done waiting for reply!", name));
        }
    } catch (InterruptedException e) {
        logger.error(e);
    }
    logger.debug(format("Eventhub %s connect is done with connect status: %b ", name, connected));
    if (connected) {
        eventStream = eventStreamLocal;
    }
    return connected;
}
Also used : StreamObserver(io.grpc.stub.StreamObserver) Status(io.grpc.Status) PeerEvents(org.hyperledger.fabric.protos.peer.PeerEvents) ArrayList(java.util.ArrayList) InvalidProtocolBufferException(com.google.protobuf.InvalidProtocolBufferException) EventHubException(org.hyperledger.fabric.sdk.exception.EventHubException) CountDownLatch(java.util.concurrent.CountDownLatch) EventHubException(org.hyperledger.fabric.sdk.exception.EventHubException) InvalidProtocolBufferException(com.google.protobuf.InvalidProtocolBufferException) InvalidArgumentException(org.hyperledger.fabric.sdk.exception.InvalidArgumentException) StatusRuntimeException(io.grpc.StatusRuntimeException) CryptoException(org.hyperledger.fabric.sdk.exception.CryptoException) StatusRuntimeException(io.grpc.StatusRuntimeException) ManagedChannel(io.grpc.ManagedChannel) CryptoException(org.hyperledger.fabric.sdk.exception.CryptoException)

Aggregations

CryptoException (org.hyperledger.fabric.sdk.exception.CryptoException)20 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)11 CertificateException (java.security.cert.CertificateException)11 InvalidArgumentException (org.hyperledger.fabric.sdk.exception.InvalidArgumentException)11 KeyStoreException (java.security.KeyStoreException)10 IOException (java.io.IOException)9 InvalidAlgorithmParameterException (java.security.InvalidAlgorithmParameterException)6 InvalidKeyException (java.security.InvalidKeyException)6 SignatureException (java.security.SignatureException)6 CertPathValidatorException (java.security.cert.CertPathValidatorException)6 X509Certificate (java.security.cert.X509Certificate)5 OperatorCreationException (org.bouncycastle.operator.OperatorCreationException)5 ByteArrayInputStream (java.io.ByteArrayInputStream)4 Certificate (java.security.cert.Certificate)4 Test (org.junit.Test)4 BufferedInputStream (java.io.BufferedInputStream)3 KeyStore (java.security.KeyStore)3 PrivateKey (java.security.PrivateKey)3 InvalidProtocolBufferException (com.google.protobuf.InvalidProtocolBufferException)2 BigInteger (java.math.BigInteger)2