Example usage for java.security.cert CertificateFactory getInstance

List of usage examples for java.security.cert CertificateFactory getInstance

Introduction

In this page you can find the example usage for java.security.cert CertificateFactory getInstance.

Prototype

public static final CertificateFactory getInstance(String type) throws CertificateException 

Source Link

Document

Returns a certificate factory object that implements the specified certificate type.

Usage

From source file:be.e_contract.mycarenet.etee.Unsealer.java

private byte[] getVerifiedContent(byte[] cmsData)
        throws CertificateException, CMSException, IOException, OperatorCreationException {
    CMSSignedData cmsSignedData = new CMSSignedData(cmsData);
    SignerInformationStore signers = cmsSignedData.getSignerInfos();
    SignerInformation signer = (SignerInformation) signers.getSigners().iterator().next();
    SignerId signerId = signer.getSID();

    Store certificateStore = cmsSignedData.getCertificates();
    @SuppressWarnings("unchecked")
    Collection<X509CertificateHolder> certificateCollection = certificateStore.getMatches(signerId);
    if (null == this.senderCertificate) {
        if (certificateCollection.isEmpty()) {
            throw new SecurityException("no sender certificate present");
        }//w ww.  j  a  v a 2  s  .  c om
        X509CertificateHolder certificateHolder = certificateCollection.iterator().next();
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        X509Certificate certificate = (X509Certificate) certificateFactory
                .generateCertificate(new ByteArrayInputStream(certificateHolder.getEncoded()));

        this.senderCertificate = certificate;
        LOG.debug("signer certificate subject: " + certificate.getSubjectX500Principal());
    }

    /*
     * By reusing the sender certificate we have the guarantee that the
     * outer signature and inner signature share the same origin.
     */
    SignerInformationVerifier signerInformationVerifier = new JcaSimpleSignerInfoVerifierBuilder()
            .build(this.senderCertificate);
    boolean signatureResult = signer.verify(signerInformationVerifier);
    if (false == signatureResult) {
        throw new SecurityException("woops");
    }

    CMSTypedData signedContent = cmsSignedData.getSignedContent();
    byte[] data = (byte[]) signedContent.getContent();
    return data;
}

From source file:com.cloud.bridge.auth.ec2.AuthenticationHandler.java

/**
 * For EC2 SOAP calls this function's goal is to extract the X509 certificate that is
 * part of the WS-Security wrapped SOAP request.   We need the cert in order to 
 * map it to the user's Cloud API key and Cloud Secret Key.
 *//*from   w w  w .ja v  a  2  s . com*/
public InvocationResponse invoke(MessageContext msgContext) throws AxisFault {
    // -> the certificate we want is embedded into the soap header
    try {
        SOAPEnvelope soapEnvelope = msgContext.getEnvelope();
        String xmlHeader = soapEnvelope.toString();
        //System.out.println( "entire request: " + xmlHeader );

        InputStream is = new ByteArrayInputStream(xmlHeader.getBytes("UTF-8"));
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document request = db.parse(is);
        NodeList certs = request.getElementsByTagNameNS(
                "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd",
                "BinarySecurityToken");
        if (0 < certs.getLength()) {
            Node item = certs.item(0);
            String result = new String(item.getFirstChild().getNodeValue());
            byte[] certBytes = Base64.decodeBase64(result.getBytes());

            Certificate userCert = null;
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            ByteArrayInputStream bs = new ByteArrayInputStream(certBytes);
            while (bs.available() > 0)
                userCert = cf.generateCertificate(bs);
            //System.out.println( "cert: " + userCert.toString());              
            String uniqueId = AuthenticationUtils.X509CertUniqueId(userCert);
            logger.debug("X509 cert's uniqueId: " + uniqueId);

            // -> find the Cloud API key and the secret key from the cert's uniqueId 
            /*               UserCredentialsDao credentialDao = new UserCredentialsDao();
                           UserCredentials cloudKeys = credentialDao.getByCertUniqueId( uniqueId );
            */
            UserCredentialsVO cloudKeys = ucDao.getByCertUniqueId(uniqueId);
            if (null == cloudKeys) {
                logger.error("Cert does not map to Cloud API keys: " + uniqueId);
                throw new AxisFault("User not properly registered: Certificate does not map to Cloud API Keys",
                        "Client.Blocked");
            } else
                UserContext.current().initContext(cloudKeys.getAccessKey(), cloudKeys.getSecretKey(),
                        cloudKeys.getAccessKey(), "SOAP Request", null);
            //System.out.println( "end of cert match: " + UserContext.current().getSecretKey());
        }
    } catch (AxisFault e) {
        throw e;
    } catch (Exception e) {
        logger.error("EC2 Authentication Handler: ", e);
        throw new AxisFault("An unknown error occurred.", "Server.InternalError");
    }
    return InvocationResponse.CONTINUE;
}

From source file:org.globus.gsi.stores.ResourceSigningPolicyStoreTest.java

private X509Certificate readCertificate(String certPath) {
    try {/*from  ww w.  j ava  2 s. c  om*/
        FileInputStream fr = new FileInputStream(certPath);
        CertificateFactory cf = CertificateFactory.getInstance("X509");
        X509Certificate crt = (X509Certificate) cf.generateCertificate(fr);
        logger.info("Read certificate:");
        logger.info("\tCertificate for: " + crt.getSubjectDN());
        logger.info("\tCertificate issued by: " + crt.getIssuerDN());
        logger.info("\tCertificate is valid from " + crt.getNotBefore() + " to " + crt.getNotAfter());
        logger.info("\tCertificate SN# " + crt.getSerialNumber());
        logger.info("\tGenerated with " + crt.getSigAlgName());

        return crt;
    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}

From source file:com.glaf.core.security.SecurityUtils.java

/**
 * ?????,??/*from   w  w w. j a  v a 2s.c o m*/
 * 
 * @param ctx
 *            
 * @param symmetryKey
 *            
 * @param pubKey
 *            
 * @return String(?base64?)
 */
public static String generateDigitalEnvelope(SecurityContext ctx, Key symmetryKey, byte[] pubKey) {
    String result = null;
    InputStream inputStream = null;
    try {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        inputStream = new ByteArrayInputStream(pubKey);
        java.security.cert.Certificate cert = cf.generateCertificate(inputStream);
        inputStream.close();
        PublicKey publicKey = cert.getPublicKey();
        Cipher cipher = Cipher.getInstance(ctx.getAsymmetryAlgorithm());

        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        result = Base64.encodeBase64String(cipher.doFinal(symmetryKey.getEncoded()));
        return result;
    } catch (Exception ex) {
        throw new SecurityException(ex);
    } finally {
        try {
            if (inputStream != null) {
                inputStream.close();
                inputStream = null;
            }
        } catch (IOException ex) {
        }
    }
}

From source file:org.projectforge.business.ldap.MyTrustManager.java

public void addCertificate(final String alias, final InputStream is) {
    CertificateFactory factory;// w ww  .  j  a v a  2  s .  co  m
    try {
        factory = CertificateFactory.getInstance("X.509");
        certificate = factory.generateCertificate(is);
        // keyStore.setCertificateEntry(alias, certificate);
    } catch (final CertificateException ex) {
        log.error("Exception encountered " + ex + " while adding certificate '" + alias + "'", ex);
        // } catch (final KeyStoreException ex) {
        // log.error("Exception encountered " + ex + " while adding certificate '" + alias + "'", ex);
    }
}

From source file:net.ripe.rpki.commons.crypto.x509cert.X509CertificateParser.java

private void parse() {
    try {/*  w w w  .j ava 2 s  . c o  m*/
        final Closer closer = Closer.create();
        try {
            final InputStream input = closer.register(new ByteArrayInputStream(encoded));
            final CertificateFactory factory = CertificateFactory.getInstance("X.509");
            certificate = (X509Certificate) factory.generateCertificate(input);
        } catch (final CertificateException e) {
            certificate = null;
        } catch (final Throwable t) {
            throw closer.rethrow(t);
        } finally {
            closer.close();
        }
    } catch (final IOException e) {
        certificate = null;
    }
    result.rejectIfNull(certificate, CERTIFICATE_PARSED);
}

From source file:eu.europa.ec.markt.dss.ws.impl.SignatureServiceImpl.java

private SignatureParameters createParameters(SignatureFormat signatureInfoLevel,
        SignedPropertiesContainer container) throws IOException {
    SignatureParameters params = new SignatureParameters();
    params.setSignatureFormat(signatureInfoLevel);
    if (container != null) {
        params.setClaimedSignerRole(container.getClaimedSignerRole());
        params.setSignaturePackaging(SignaturePackaging.valueOf(container.getSignaturePackaging()));
        params.setSigningDate(container.getSigningDate());

        try {//from   www. j av a  2s . c  om
            CertificateFactory factory = CertificateFactory.getInstance("X509");
            params.setSigningCertificate((X509Certificate) factory
                    .generateCertificate(new ByteArrayInputStream(container.getSigningCertificate())));
            List<X509Certificate> chain = new ArrayList<X509Certificate>();
            for (byte[] cert : container.getCertificateChain()) {
                chain.add((X509Certificate) factory.generateCertificate(new ByteArrayInputStream(cert)));
            }
            params.setCertificateChain(chain);
        } catch (CertificateException ex) {
            throw new IOException("Cannot read certficate");
        }
    }

    return params;
}

From source file:com.linkedin.pinot.common.utils.ClientSSLContextGenerator.java

private TrustManager[] setupTrustManagers()
        throws CertificateException, KeyStoreException, IOException, NoSuchAlgorithmException {
    // This is the cert authority that validates server's cert, so we need to put it in our
    // trustStore.
    if (_serverCACertFile != null) {
        LOGGER.info("Initializing trust store from {}", _serverCACertFile);
        FileInputStream is = new FileInputStream(new File(_serverCACertFile));
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null);/* w ww .ja va2 s.  c o  m*/
        CertificateFactory certificateFactory = CertificateFactory.getInstance(CERTIFICATE_TYPE);
        int i = 0;
        while (is.available() > 0) {
            X509Certificate cert = (X509Certificate) certificateFactory.generateCertificate(is);
            LOGGER.info("Read certificate serial number {} by issuer {} ", cert.getSerialNumber().toString(16),
                    cert.getIssuerDN().toString());

            String serverKey = "https-server-" + i;
            trustStore.setCertificateEntry(serverKey, cert);
            i++;
        }

        TrustManagerFactory tmf = TrustManagerFactory.getInstance(CERTIFICATE_TYPE);
        tmf.init(trustStore);
        LOGGER.info("Successfully initialized trust store");
        return tmf.getTrustManagers();
    }
    // Server verification disabled. Trust all servers
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        @Override
        public void checkClientTrusted(X509Certificate[] x509Certificates, String s)
                throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] x509Certificates, String s)
                throws CertificateException {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }
    } };
    return trustAllCerts;
}

From source file:org.apache.synapse.transport.certificatevalidation.crl.CRLVerifier.java

/**
 * Downloads CRL from the crlUrl. Does not support HTTPS
 *///  w  ww  .j  a  v a2  s . c  o m
protected X509CRL downloadCRLFromWeb(String crlURL) throws IOException, CertificateVerificationException {
    InputStream crlStream = null;
    try {
        URL url = new URL(crlURL);
        crlStream = url.openStream();
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        return (X509CRL) cf.generateCRL(crlStream);
    } catch (MalformedURLException e) {
        throw new CertificateVerificationException("CRL Url is malformed", e);
    } catch (IOException e) {
        throw new CertificateVerificationException("Cant reach URI: " + crlURL + " - only support HTTP", e);
    } catch (CertificateException e) {
        throw new CertificateVerificationException(e);
    } catch (CRLException e) {
        throw new CertificateVerificationException("Cannot generate X509CRL from the stream data", e);
    } finally {
        if (crlStream != null)
            crlStream.close();
    }
}

From source file:org.disrupted.rumble.database.statistics.StatisticManager.java

public void onEventAsync(LinkLayerStarted event) {
    if (!event.linkLayerIdentifier.equals(WifiLinkLayerAdapter.LinkLayerIdentifier))
        return;/* w  w  w  . j  av a  2s .co m*/

    if (RumblePreferences.UserOkWithSharingAnonymousData(RumbleApplication.getContext())
            && RumblePreferences.isTimeToSync(RumbleApplication.getContext())) {
        if (!NetUtil.isURLReachable("http://disruptedsystems.org/"))
            return;

        try {
            // generate the JSON file
            byte[] json = generateStatJSON().toString().getBytes();

            // configure SSL
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            InputStream caInput = new BufferedInputStream(
                    RumbleApplication.getContext().getAssets().open("certs/disruptedsystemsCA.pem"));
            Certificate ca = cf.generateCertificate(caInput);

            String keyStoreType = KeyStore.getDefaultType();
            KeyStore keyStore = KeyStore.getInstance(keyStoreType);
            keyStore.load(null, null);
            keyStore.setCertificateEntry("ca", ca);

            String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
            TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
            tmf.init(keyStore);

            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, tmf.getTrustManagers(), null);

            URL url = new URL("https://data.disruptedsystems.org/post");
            HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
            urlConnection.setSSLSocketFactory(sslContext.getSocketFactory());

            // then configure the header
            urlConnection.setInstanceFollowRedirects(true);
            urlConnection.setRequestMethod("POST");
            urlConnection.setDoOutput(true);
            urlConnection.setRequestProperty("Content-Type", "application/json");
            urlConnection.setRequestProperty("Accept", "application/json");
            urlConnection.setRequestProperty("charset", "utf-8");
            urlConnection.setRequestProperty("Content-Length", Integer.toString(json.length));
            urlConnection.setUseCaches(false);

            // connect and send the JSON
            urlConnection.setConnectTimeout(10 * 1000);
            urlConnection.connect();
            urlConnection.getOutputStream().write(json);
            if (urlConnection.getResponseCode() != 200)
                throw new IOException("request failed");

            // erase the database
            RumblePreferences.updateLastSync(RumbleApplication.getContext());
            cleanDatabase();
        } catch (Exception ex) {
            Log.e(TAG, "Failed to establish SSL connection to server: " + ex.toString());
        }
    }
}