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.EncryptionToken.java

private X509Certificate parseEncryptionCertificate(byte[] encodedEncryptionToken)
        throws CMSException, CertificateException, IOException, OperatorCreationException {
    CMSSignedData cmsSignedData = new CMSSignedData(encodedEncryptionToken);

    // get signer identifier
    SignerInformationStore signers = cmsSignedData.getSignerInfos();
    SignerInformation signer = (SignerInformation) signers.getSigners().iterator().next();
    SignerId signerId = signer.getSID();

    // get signer certificate
    Store certificateStore = cmsSignedData.getCertificates();
    LOG.debug("certificate store type: " + certificateStore.getClass().getName());
    @SuppressWarnings("unchecked")
    Collection<X509CertificateHolder> signingCertificateCollection = certificateStore.getMatches(signerId);
    X509CertificateHolder signingCertificateHolder = signingCertificateCollection.iterator().next();
    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    X509Certificate signingCertificate = (X509Certificate) certificateFactory
            .generateCertificate(new ByteArrayInputStream(signingCertificateHolder.getEncoded()));
    LOG.debug("signing certificate: " + signingCertificate.getSubjectX500Principal());

    // verify CMS signature
    SignerInformationVerifier signerInformationVerifier = new JcaSimpleSignerInfoVerifierBuilder()
            .build(signingCertificate);//ww w. j av a 2s.co m
    boolean signatureResult = signer.verify(signerInformationVerifier);
    if (false == signatureResult) {
        throw new SecurityException("ETK signature invalid");
    }

    // get encryption certificate
    CMSTypedData signedContent = cmsSignedData.getSignedContent();
    byte[] data = (byte[]) signedContent.getContent();
    X509Certificate encryptionCertificate = (X509Certificate) certificateFactory
            .generateCertificate(new ByteArrayInputStream(data));

    LOG.debug("all available certificates:");
    logCertificates(certificateStore, null);

    // get authentication certificate
    CustomSelector authenticationSelector = new CustomSelector();
    authenticationSelector.setSubject(encryptionCertificate.getIssuerX500Principal());
    @SuppressWarnings("unchecked")
    Collection<X509CertificateHolder> authenticationCertificates = certificateStore
            .getMatches(authenticationSelector);
    if (authenticationCertificates.size() != 1) {
        LOG.debug("no authentication certificate match");
    }
    X509CertificateHolder authenticationCertificateHolder = authenticationCertificates.iterator().next();
    this.authenticationCertificate = (X509Certificate) certificateFactory
            .generateCertificate(new ByteArrayInputStream(authenticationCertificateHolder.getEncoded()));

    verifyProxyCertificate(encryptionCertificate, this.authenticationCertificate);

    return encryptionCertificate;
}

From source file:be.fedict.eid.dss.protocol.simple.SimpleDSSProtocolService.java

public void init(ServletContext servletContext, DSSProtocolContext dssContext) {
    LOG.debug("init");
    this.dssContext = dssContext;

    try {/*from   w w w.  ja v a  2  s . c o  m*/
        this.certificateFactory = CertificateFactory.getInstance("X.509");
    } catch (CertificateException e) {
        throw new RuntimeException("could not create certificate factory instance: " + e.getMessage(), e);
    }
}

From source file:com.shalzz.attendance.wrapper.MySSLSocketFactory.java

/**
 * Gets a KeyStore containing the Certificate
 * /*from  w  w w  . j av  a2  s .  c om*/
 * @param cert InputStream of the Certificate
 * @return KeyStore
 */
public static KeyStore getKeystoreOfCA(InputStream cert) {

    // Load CAs from an InputStream
    InputStream caInput = null;
    Certificate ca = null;
    try {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        caInput = new BufferedInputStream(cert);
        ca = cf.generateCertificate(caInput);
    } catch (CertificateException e1) {
        e1.printStackTrace();
    } finally {
        try {
            caInput.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // Create a KeyStore containing our trusted CAs
    String keyStoreType = KeyStore.getDefaultType();
    KeyStore keyStore = null;
    try {
        keyStore = KeyStore.getInstance(keyStoreType);
        keyStore.load(null, null);
        keyStore.setCertificateEntry("ca", ca);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return keyStore;
}

From source file:be.fedict.eidviewer.lib.file.Version4XMLFileCertificates.java

public List<X509Certificate> toAuthChain() throws CertificateException {
    CertificateFactory certificateFactory = null;
    X509Certificate rootCert = null;
    X509Certificate citizenCert = null;
    X509Certificate authenticationCert = null;
    List<X509Certificate> authChain = null;

    if (getRootCertificate() == null || getCitizenCACertificate() == null
            || getAuthenticationCertificate() == null)
        return null;

    certificateFactory = CertificateFactory.getInstance("X.509");

    rootCert = (X509Certificate) certificateFactory.generateCertificate(
            new ByteArrayInputStream(Base64.decodeBase64(getRootCertificate().getBytes())));
    citizenCert = (X509Certificate) certificateFactory.generateCertificate(
            new ByteArrayInputStream(Base64.decodeBase64(getCitizenCACertificate().getBytes())));
    authenticationCert = (X509Certificate) certificateFactory.generateCertificate(
            new ByteArrayInputStream(Base64.decodeBase64(getAuthenticationCertificate().getBytes())));

    authChain = new LinkedList<X509Certificate>();
    authChain.add(authenticationCert);/*from ww w.j  a v  a 2s .c  o m*/
    authChain.add(citizenCert);
    authChain.add(rootCert);

    return authChain;
}

From source file:com.fine47.http.SecureSocketFactory.java

private SecureSocketFactory(String factoryId, KeyStore store, String alias) throws CertificateException,
        NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
    super(store);

    // Loading the CA certificate from store.
    Certificate rootca = store.getCertificate(alias);

    // Turn it to X509 format.
    InputStream is = new ByteArrayInputStream(rootca.getEncoded());
    X509Certificate x509ca = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(is);
    ActivityHttpClient.silentCloseInputStream(is);

    if (null == x509ca) {
        throw new CertificateException("Found expired SSL certificate in this store: " + factoryId);
    }//  w ww  .  j ava2 s  . c om

    // Check the CA's validity.
    x509ca.checkValidity();

    // Accepted CA is only the one installed in the store.
    acceptedIssuers = new X509Certificate[] { x509ca };

    // Get the public key.
    publicKey = rootca.getPublicKey();

    sslCtx = SSLContext.getInstance("TLS");
    sslCtx.init(null, new TrustManager[] { new X509TrustManager() {

        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            Exception error = null;

            if (null == chain || 0 == chain.length) {
                error = new CertificateException("Certificate chain is invalid");
            } else if (null == authType || 0 == authType.length()) {
                error = new CertificateException("Authentication type is invalid");
            } else
                try {
                    for (X509Certificate cert : chain) {
                        if (ActivityHttpClient.isDebugging()) {
                            Log.d(ActivityHttpClient.LOG_TAG, "Server Certificate Details:");
                            Log.d(ActivityHttpClient.LOG_TAG, "---------------------------");
                            Log.d(ActivityHttpClient.LOG_TAG, "IssuerDN: " + cert.getIssuerDN().toString());
                            Log.d(ActivityHttpClient.LOG_TAG, "SubjectDN: " + cert.getSubjectDN().toString());
                            Log.d(ActivityHttpClient.LOG_TAG, "Serial Number: " + cert.getSerialNumber());
                            Log.d(ActivityHttpClient.LOG_TAG, "Version: " + cert.getVersion());
                            Log.d(ActivityHttpClient.LOG_TAG, "Not before: " + cert.getNotBefore().toString());
                            Log.d(ActivityHttpClient.LOG_TAG, "Not after: " + cert.getNotAfter().toString());
                            Log.d(ActivityHttpClient.LOG_TAG, "---------------------------");
                        }

                        // Make sure that it hasn't expired.
                        cert.checkValidity();

                        // Verify the certificate's chain.
                        cert.verify(publicKey);
                    }
                } catch (InvalidKeyException ex) {
                    error = ex;
                } catch (NoSuchAlgorithmException ex) {
                    error = ex;
                } catch (NoSuchProviderException ex) {
                    error = ex;
                } catch (SignatureException ex) {
                    error = ex;
                }
            if (null != error && ActivityHttpClient.isDebugging()) {
                Log.e(ActivityHttpClient.LOG_TAG, "Error while setting up a secure socket factory.", error);
                throw new CertificateException(error);
            }
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return acceptedIssuers;
        }
    } }, null);

    setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
}

From source file:net.ripe.rpki.commons.crypto.crl.X509Crl.java

private static X509CRL makeX509CRLFromEncoded(byte[] encoded) {
    final X509CRL crl;
    if (null != encoded) {
        try {//from  w ww  . j  a  v  a2  s  .c  om
            final Closer closer = Closer.create();
            try {
                final ByteArrayInputStream in = new ByteArrayInputStream(encoded);
                final CertificateFactory factory = CertificateFactory.getInstance("X.509");
                crl = (X509CRL) factory.generateCRL(in);
            } catch (final CertificateException e) {
                throw closer.rethrow(new IllegalArgumentException(e));
            } catch (final CRLException e) {
                throw closer.rethrow(new IllegalArgumentException(e));
            } catch (final Throwable t) {
                throw closer.rethrow(t);
            } finally {
                closer.close();
            }
        } catch (final IOException e) {
            throw new RuntimeException("Error managing CRL I/O stream", e);
        }
    } else {
        crl = null;
    }
    return crl;

}

From source file:com.github.mrstampy.gameboot.otp.OtpTestConfiguration.java

/**
 * Client context./*  w w w  . j av a2s  .co m*/
 *
 * @return the SSL context
 * @throws Exception
 *           the exception
 */
@Bean(name = CLIENT_SSL_CONTEXT)
public SSLContext clientContext() throws Exception {
    CertificateFactory cf = CertificateFactory.getInstance(X_509);
    Certificate cert = cf.generateCertificate(getResource(CERT_LOCATION));

    KeyStore keystore = getKeyStore();
    keystore.load(null);
    keystore.setCertificateEntry(ALIAS, cert);

    return createContext(keystore, null);
}

From source file:org.candlepin.CRLBenchmark.java

@Benchmark
@Fork(value = 1, jvmArgsAppend = { "-Xloggc:gc_in_memory.log", "-verbose:gc", "-XX:+PrintGCDetails",
        "-XX:+PrintGCTimeStamps" })
public void inMemory() {
    InputStream stream = null;/*from w  ww.j a va 2 s. co  m*/
    try {
        List<BigInteger> l = new LinkedList<BigInteger>();

        stream = new BufferedInputStream(new FileInputStream(crlFile));
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        X509CRL crl = (X509CRL) cf.generateCRL(stream);

        for (X509CRLEntry entry : crl.getRevokedCertificates()) {
            l.add(entry.getSerialNumber());
        }

        if (!"1999999".equals(l.get(1999999).toString())) {
            throw new RuntimeException("CRL list read in is incorrect");
        } else {
            System.out.println("Read " + l.size() + " entries");
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (stream != null) {
            try {
                stream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:demo.sts.provider.cert.CrlVerifier.java

public X509CRL getCrlFromStream(InputStream is) throws CertificateException, CRLException {
    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    return (X509CRL) certificateFactory.generateCRL(is);
}