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;
}
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;
}
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;
}
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;
}
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;
}
Aggregations