Example usage for org.bouncycastle.asn1 ASN1InputStream ASN1InputStream

List of usage examples for org.bouncycastle.asn1 ASN1InputStream ASN1InputStream

Introduction

In this page you can find the example usage for org.bouncycastle.asn1 ASN1InputStream ASN1InputStream.

Prototype

public ASN1InputStream(InputStream input, boolean lazyEvaluate) 

Source Link

Document

Create an ASN1InputStream where no DER object will be longer than limit, and constructed objects such as sequences will be parsed lazily.

Usage

From source file:com.infinities.keystone4j.utils.Cms.java

License:Apache License

@SuppressWarnings("rawtypes")
public String verifySignature(byte[] sigbytes, String signingCertFileName, String caFileName)
        throws CMSException, CertificateException, OperatorCreationException, NoSuchAlgorithmException,
        NoSuchProviderException, CertPathBuilderException, InvalidAlgorithmParameterException, IOException,
        CertificateVerificationException {
    logger.debug("signingCertFile: {}, caFile:{}", new Object[] { signingCertFileName, caFileName });
    Security.addProvider(new BouncyCastleProvider());
    X509Certificate signercert = generateCertificate(signingCertFileName);
    X509Certificate cacert = generateCertificate(caFileName);
    Set<X509Certificate> additionalCerts = new HashSet<X509Certificate>();
    additionalCerts.add(cacert);/*from w w  w  .  jav  a 2  s  .c o  m*/

    CertificateVerifier.verifyCertificate(signercert, additionalCerts, true); // .validateKeyChain(signercert,
    // certs);
    if (Base64Verifier.isBase64(sigbytes)) {
        try {
            sigbytes = Base64.decode(sigbytes);
            logger.debug("Signature file is BASE64 encoded");
        } catch (Exception ioe) {
            logger.warn("Problem decoding from b64", ioe);
        }
    }

    // sigbytes = Base64.decode(sigbytes);

    // --- Use Bouncy Castle provider to verify included-content CSM/PKCS#7
    // signature ---
    ASN1InputStream in = null;
    try {
        logger.debug("sigbytes size: {}", sigbytes.length);
        in = new ASN1InputStream(new ByteArrayInputStream(sigbytes), Integer.MAX_VALUE);

        CMSSignedData s = new CMSSignedData(ContentInfo.getInstance(in.readObject()));
        Store store = s.getCertificates();
        SignerInformationStore signers = s.getSignerInfos();
        Collection c = signers.getSigners();
        Iterator it = c.iterator();
        int verified = 0;

        while (it.hasNext()) {
            X509Certificate cert = null;
            SignerInformation signer = (SignerInformation) it.next();
            Collection certCollection = store.getMatches(signer.getSID());
            if (certCollection.isEmpty() && signercert == null)
                continue;
            else if (signercert != null) // use a signer cert file for
                // verification, if it was
                // provided
                cert = signercert;
            else { // use the certificates included in the signature for
                   // verification
                Iterator certIt = certCollection.iterator();
                cert = (X509Certificate) certIt.next();
            }

            // if (signer.verify(new
            // JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(cert)))
            // verified++;
        }

        if (verified == 0) {
            logger.warn(" No signers' signatures could be verified !");
        } else if (signercert != null)
            logger.info("Verified a signature using signer certificate file  {}", signingCertFileName);
        else
            logger.info("Verified a signature using a certificate in the signature data");

        CMSProcessableByteArray cpb = (CMSProcessableByteArray) s.getSignedContent();
        byte[] rawcontent = (byte[]) cpb.getContent();

        return new String(rawcontent);
    } catch (Exception ex) {
        logger.error("Couldn't verify included-content CMS signature", ex);
        throw new RuntimeException("Couldn't verify included-content CMS signature", ex);
    } finally {
        if (in != null) {
            in.close();
        }
    }
}

From source file:edu.vt.middleware.crypt.util.CryptReader.java

License:Open Source License

/**
 * Attempts to create a Bouncy Castle <code>DERObject</code> from a byte array
 * representing ASN.1 encoded data./*from w w  w  . j av  a 2s .  c  om*/
 *
 * @param  data  ASN.1 encoded data as byte array.
 * @param  discardWrapper  In some cases the value of the encoded data may
 * itself be encoded data, where the latter encoded data is desired. Recall
 * ASN.1 data is of the form {TAG, SIZE, DATA}. Set this flag to true to skip
 * the first two bytes, e.g. TAG and SIZE, and treat the remaining bytes as
 * the encoded data.
 *
 * @return  DER object.
 *
 * @throws  IOException  On I/O errors.
 */
public static DERObject readEncodedBytes(final byte[] data, final boolean discardWrapper) throws IOException {
    final ByteArrayInputStream inBytes = new ByteArrayInputStream(data);
    int size = data.length;
    if (discardWrapper) {
        inBytes.skip(2);
        size = data.length - 2;
    }

    final ASN1InputStream in = new ASN1InputStream(inBytes, size);
    try {
        return in.readObject();
    } finally {
        try {
            in.close();
        } catch (IOException e) {
            final Log logger = LogFactory.getLog(CryptReader.class);
            if (logger.isWarnEnabled()) {
                logger.warn("Error closing ASN.1 input stream.", e);
            }
        }
    }
}

From source file:org.cryptoworkshop.ximix.client.connection.NodeServicesConnection.java

License:Apache License

public synchronized MessageReply sendMessage(MessageType type, ASN1Encodable messagePayload)
        throws ServiceConnectionException {
    // maybe we're down?
    if (isTryingToConnect.get()) {
        return new MessageReply(MessageReply.Type.ERROR,
                new ErrorMessage("Link to node " + name + " unavailable"));
    }//from w ww.j a  v  a 2 s .  c  om

    // if there is an error we do one retry to rebuild the line before exiting.
    for (int i = 0; i != 2; i++) {
        if (connection == null) {
            buildConnection();
        }

        byte[] encodedMessage;

        try {
            if (type instanceof ClientMessage.Type) {
                encodedMessage = new ClientMessage((ClientMessage.Type) type, messagePayload).getEncoded();

            } else {
                encodedMessage = new CommandMessage((CommandMessage.Type) type, messagePayload).getEncoded();
            }
        } catch (IOException e) {
            throw new ServiceConnectionException("Malformed message: " + e.getMessage(), e);
        }

        try {
            cOut.write(encodedMessage);

            return MessageReply.getInstance(new ASN1InputStream(cIn, 300000).readObject()); // TODO
        } catch (Exception e) {
            try {
                this.shutdown();
            } catch (Exception ex) {
                eventNotifier.notify(EventNotifier.Level.WARN,
                        "Exception resetting link to " + address + ": " + e.getMessage(), e);
            }

            eventNotifier.notify(EventNotifier.Level.WARN,
                    "Unable to open link to " + address + " - retrying.");
            try {
                Thread.sleep(5000); // TODO: configure?
            } catch (InterruptedException ex) {
                Thread.currentThread().interrupt();
            }
        }
    }

    return new MessageReply(MessageReply.Type.ERROR, new ErrorMessage("Link to node " + name + " unavailable"));
}

From source file:org.cryptoworkshop.ximix.client.connection.NodeServicesConnection.java

License:Apache License

private void open() throws IOException, ServiceConnectionException {
    this.connection = new Socket(address, portNo);

    cOut = connection.getOutputStream();
    cIn = connection.getInputStream();/*from  w w  w .  ja  va  2 s  .  c om*/

    ASN1InputStream aIn = new ASN1InputStream(cIn, 300000); // TODO:

    nodeInfo = NodeInfo.getInstance(aIn.readObject());
    if (!name.equals(nodeInfo.getName())) {
        try {
            close();
        } catch (ServiceConnectionException e) {
            // ignore
        }
        eventNotifier.notify(EventNotifier.Level.ERROR,
                "Node " + name + " identified itself as " + nodeInfo.getName() + " - closing connection");
        throw new ServiceConnectionException(
                "Node " + name + " identified itself as " + nodeInfo.getName() + " - closing connection");
    }
}

From source file:org.cryptoworkshop.ximix.node.core.XimixServices.java

License:Apache License

public void run() {
    try {/*w  w w  .jav a  2  s . c o  m*/
        s.setSoTimeout(5000); // TODO: should be a config item

        InputStream sIn = s.getInputStream();
        OutputStream sOut = s.getOutputStream();

        ASN1InputStream aIn = new ASN1InputStream(sIn, maxInputSize); // TODO: should be a config item
        DEROutputStream aOut = new DEROutputStream(sOut);

        aOut.writeObject(new NodeInfo(nodeContext.getName(), nodeContext.getCapabilities()));

        while (!stopped.get()) {
            try {
                //System.out.println("Connection from: "+s.getRemoteSocketAddress())
                Object o;

                while ((o = aIn.readObject()) != null && !nodeContext.isStopCalled()) {
                    Message message = Message.getInstance(o);

                    NodeService nodeService = nodeContext.getService(message);

                    nodeContext.getEventNotifier().notify(EventNotifier.Level.DEBUG,
                            "Received Message: " + message.getType());

                    if (nodeService != null) {
                        MessageReply reply = nodeService.handle(message);

                        nodeContext.getEventNotifier().notify(EventNotifier.Level.DEBUG,
                                "Reply Message: " + reply);
                        aOut.writeObject(reply);
                    } else {
                        aOut.writeObject(new MessageReply(MessageReply.Type.ERROR,
                                new DERUTF8String("Node " + nodeContext.getName()
                                        + ": unable to find service for " + message.getType())));
                    }
                }

                nodeContext.getEventNotifier().notify(EventNotifier.Level.INFO, "Service connection on "
                        + nodeContext.getName() + " shutdown, stop called = " + nodeContext.isStopCalled());
                break;
            } catch (SocketTimeoutException e) {
                continue;
            }
        }

        shutdownLatch.countDown();
        s.close();
    } catch (IOException e) {
        throwableHandler.notify(EventNotifier.Level.WARN, e);
    }
}