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:oracle.custom.ui.utils.ServerUtils.java

public static PublicKey getServerPublicKey(String domainName) throws Exception {
    HttpClient client = getClient(domainName);
    PublicKey key = null;/*  www .  j  a  v  a 2  s.c  o m*/
    String url = getIDCSBaseURL(domainName) + "/admin/v1/SigningCert/jwk";
    URI uri = new URI(url);
    HttpHost host = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
    HttpGet httpGet = new HttpGet(uri);
    httpGet.addHeader("Authorization", "Bearer " + AccessTokenUtils.getAccessToken(domainName));
    HttpResponse response = client.execute(host, httpGet);
    try {
        HttpEntity entity2 = response.getEntity();
        String res = EntityUtils.toString(entity2);
        EntityUtils.consume(entity2);
        ObjectMapper mapper = new ObjectMapper();
        System.out.println("result is " + res);
        SigningKeys signingKey = mapper.readValue(res, SigningKeys.class);

        String base64Cert = signingKey.getKeys().get(0).getX5c().get(0);
        byte encodedCert[] = Base64.getDecoder().decode(base64Cert);
        ByteArrayInputStream inputStream = new ByteArrayInputStream(encodedCert);

        CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
        X509Certificate cert = (X509Certificate) certFactory.generateCertificate(inputStream);
        key = cert.getPublicKey();
    } finally {
        if (response instanceof CloseableHttpResponse) {
            ((CloseableHttpResponse) response).close();
        }
    }
    return key;
}

From source file:com.isa.ws.utiles.UtilesSWHelper.java

/**
 * Converts a byte array to a X509Certificate instance.
 * @param bytes the byte array/* ww w .jav a2  s .  c  om*/
 * @return a X509Certificate instance
 * @throws CertificateException if the conversion fails
 */
public static X509Certificate fromByteArrayToX509Certificate(byte[] bytes) throws CertificateException {
    CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
    InputStream in = new ByteArrayInputStream(bytes);
    X509Certificate cert = (X509Certificate) certFactory.generateCertificate(in);
    return cert;
}

From source file:be.e_contract.mycarenet.certra.CertRAClient.java

private byte[] getCmsData(byte[] cms) throws Exception {
    CMSSignedData cmsSignedData = new CMSSignedData(cms);
    SignerInformationStore signers = cmsSignedData.getSignerInfos();
    SignerInformation signer = (SignerInformation) signers.getSigners().iterator().next();
    SignerId signerId = signer.getSID();

    Store certificateStore = cmsSignedData.getCertificates();
    Collection<X509CertificateHolder> certificateCollection = certificateStore.getMatches(signerId);

    X509CertificateHolder certificateHolder = certificateCollection.iterator().next();
    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    X509Certificate certificate = (X509Certificate) certificateFactory
            .generateCertificate(new ByteArrayInputStream(certificateHolder.getEncoded()));
    // we trust SSL here, no need for explicit verification of CMS signing
    // certificate

    LOG.debug("CMS signing certificate subject: " + certificate.getSubjectX500Principal());

    SignerInformationVerifier signerInformationVerifier = new JcaSimpleSignerInfoVerifierBuilder()
            .build(certificate);//  w  ww.  j  a  v a2s  .  c om
    boolean signatureResult = signer.verify(signerInformationVerifier);
    if (false == signatureResult) {
        throw new SecurityException("woops");
    }

    CMSTypedData signedContent = cmsSignedData.getSignedContent();
    byte[] responseData = (byte[]) signedContent.getContent();

    return responseData;
}

From source file:org.apache.tomcat.util.net.jsse.JSSE14Support.java

/** Return the X509certificates or null if we can't get them.
 *  XXX We should allow unverified certificates 
 *///from   www.j a  v a 2  s. c  o m
protected X509Certificate[] getX509Certificates(SSLSession session) throws IOException {
    Certificate[] certs = null;
    try {
        certs = session.getPeerCertificates();
    } catch (Throwable t) {
        logger.debug("Error getting client certs", t);
        return null;
    }
    if (certs == null)
        return null;

    X509Certificate[] x509Certs = new X509Certificate[certs.length];
    for (int i = 0; i < certs.length; i++) {
        if (certs[i] instanceof X509Certificate) {
            // always currently true with the JSSE 1.1.x
            x509Certs[i] = (X509Certificate) certs[i];
        } else {
            try {
                byte[] buffer = certs[i].getEncoded();
                CertificateFactory cf = CertificateFactory.getInstance("X.509");
                ByteArrayInputStream stream = new ByteArrayInputStream(buffer);
                x509Certs[i] = (X509Certificate) cf.generateCertificate(stream);
            } catch (Exception ex) {
                logger.info("Error translating cert " + certs[i], ex);
                return null;
            }
        }
        if (logger.isTraceEnabled())
            logger.trace("Cert #" + i + " = " + x509Certs[i]);
    }
    if (x509Certs.length < 1)
        return null;
    return x509Certs;
}

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

public List<X509Certificate> toRRNChain() throws CertificateException {
    CertificateFactory certificateFactory = null;
    X509Certificate rootCert = null;
    X509Certificate rrnCert = null;
    List<X509Certificate> rrnChain = null;

    if (getRootCertificate() == null || getRRNCertificate() == null)
        return null;

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

    rootCert = (X509Certificate) certificateFactory.generateCertificate(
            new ByteArrayInputStream(Base64.decodeBase64(getRootCertificate().getBytes())));
    rrnCert = (X509Certificate) certificateFactory
            .generateCertificate(new ByteArrayInputStream(Base64.decodeBase64(getRRNCertificate().getBytes())));

    rrnChain = new LinkedList<X509Certificate>();
    rrnChain.add(rrnCert);/*from  w w w  .  j  ava2s  .c  om*/
    rrnChain.add(rootCert);

    return rrnChain;
}

From source file:bobs.mcapisignature.CertUtils.java

public static X509Certificate getX509Certificate(CERT_CONTEXT pcert) throws CertificateException {
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    X509Certificate cert = (X509Certificate) cf
            .generateCertificate(new ByteArrayInputStream(certToBytes(pcert)));

    return cert;/* w w w .j a  v  a 2  s .  c  o  m*/
}

From source file:org.apache.taverna.security.credentialmanager.impl.CredentialManagerImplTest.java

/**
 * @throws java.lang.Exception//from   w  w  w.  j  a va 2  s .co  m
 */
@BeforeClass
public static void setUpBeforeClass() throws Exception {

    // Just in case, add the BouncyCastle provider
    // It gets added from the CredentialManagerImpl constructor as well
    // but we may need some crypto operations before we invoke the Cred. Manager 
    Security.addProvider(new BouncyCastleProvider());

    // Create a test username and password for a service
    serviceURI = new URI("http://someservice");
    usernamePassword = new UsernamePassword("testuser", "testpasswd");

    // Load the test private key and its certificate
    File privateKeyCertFile = new File(privateKeyFileURL.getPath());
    KeyStore pkcs12Keystore = java.security.KeyStore.getInstance("PKCS12", "BC"); // We have to use the BC provider here as the certificate chain is not loaded if we use whichever provider is first in Java!!!
    FileInputStream inStream = new FileInputStream(privateKeyCertFile);
    pkcs12Keystore.load(inStream, privateKeyAndPKCS12KeystorePassword.toCharArray());
    // KeyStore pkcs12Keystore = credentialManager.loadPKCS12Keystore(privateKeyCertFile, privateKeyPassword);
    Enumeration<String> aliases = pkcs12Keystore.aliases();
    while (aliases.hasMoreElements()) {
        // The test-private-key-cert.p12 file contains only one private key
        // and corresponding certificate entry
        String alias = aliases.nextElement();
        if (pkcs12Keystore.isKeyEntry(alias)) { // is it a (private) key entry?
            privateKey = pkcs12Keystore.getKey(alias, privateKeyAndPKCS12KeystorePassword.toCharArray());
            privateKeyCertChain = pkcs12Keystore.getCertificateChain(alias);
            break;
        }
    }
    inStream.close();

    // Load the test trusted certificate (belonging to *.Google.com)
    File trustedCertFile = new File(trustedCertficateFileURL.getPath());
    inStream = new FileInputStream(trustedCertFile);
    CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
    trustedCertficate = (X509Certificate) certFactory.generateCertificate(inStream);
    try {
        inStream.close();
    } catch (Exception e) {
        // Ignore
    }

    keystoreChangedObserver = new Observer<KeystoreChangedEvent>() {

        @Override
        public void notify(Observable<KeystoreChangedEvent> sender, KeystoreChangedEvent message)
                throws Exception {
            // TODO Auto-generated method stub

        }
    };
}

From source file:net.sf.taverna.t2.security.credentialmanager.impl.CredentialManagerImplIT.java

/**
 * @throws java.lang.Exception// w w w.jav a2 s .  co m
 */
@BeforeClass
@Ignore
public static void setUpBeforeCLass() throws Exception {

    Security.addProvider(new BouncyCastleProvider());

    // Create some test username and passwords for services
    serviceURI = new URI("http://someservice");
    usernamePassword = new UsernamePassword("testuser", "testpasswd");
    serviceURI2 = new URI("http://someservice2");
    usernamePassword2 = new UsernamePassword("testuser2", "testpasswd2");
    serviceURI3 = new URI("http://someservice3");
    usernamePassword3 = new UsernamePassword("testuser3", "testpasswd3");

    // Load the test private key and its certificate
    File privateKeyCertFile = new File(privateKeyFileURL.getPath());
    KeyStore pkcs12Keystore = java.security.KeyStore.getInstance("PKCS12", "BC"); // We have to use the BC provider here as the certificate chain is not loaded if we use whichever provider is first in Java!!!
    FileInputStream inStream = new FileInputStream(privateKeyCertFile);
    pkcs12Keystore.load(inStream, privateKeyAndPKCS12KeystorePassword.toCharArray());
    // KeyStore pkcs12Keystore = credentialManager.loadPKCS12Keystore(privateKeyCertFile, privateKeyPassword);
    Enumeration<String> aliases = pkcs12Keystore.aliases();
    while (aliases.hasMoreElements()) {
        // The test-private-key-cert.p12 file contains only one private key
        // and corresponding certificate entry
        String alias = aliases.nextElement();
        if (pkcs12Keystore.isKeyEntry(alias)) { // is it a (private) key entry?
            privateKey = pkcs12Keystore.getKey(alias, privateKeyAndPKCS12KeystorePassword.toCharArray());
            privateKeyCertChain = pkcs12Keystore.getCertificateChain(alias);
            break;
        }
    }
    inStream.close();

    // Load the test trusted certificate (belonging to *.Google.com)
    File trustedCertFile = new File(trustedCertficateGoogleFileURL.getPath());
    inStream = new FileInputStream(trustedCertFile);
    CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
    trustedCertficateGoogle = (X509Certificate) certFactory.generateCertificate(inStream);
    try {
        inStream.close();
    } catch (Exception e) {
        // Ignore
    }
    // Load the test trusted certificate (belonging to heater.cs.man.ac.uk)
    File trustedCertFile2 = new File(trustedCertficateHeaterFileURL.getPath());
    inStream = new FileInputStream(trustedCertFile2);
    trustedCertficateHeater = (X509Certificate) certFactory.generateCertificate(inStream);
    try {
        inStream.close();
    } catch (Exception e) {
        // Ignore
    }

    credentialManager = new CredentialManagerImpl();

    //      // The code below sets up the Keystore and Truststore files and loads some data into them
    //      // and saves them into a temp directory. These files can later be used for testing the Credential
    //      // Manager with non-empty keystores.
    //      Random randomGenerator = new Random();
    //      String credentialManagerDirectoryPath = System
    //            .getProperty("java.io.tmpdir")
    //            + System.getProperty("file.separator")
    //            + "taverna-security-"
    //            + randomGenerator.nextInt(1000000);
    //      System.out.println("Credential Manager's directory path: "
    //            + credentialManagerDirectoryPath);
    //      credentialManagerDirectory = new File(credentialManagerDirectoryPath);
    //      credentialManager.setConfigurationDirectoryPath(credentialManagerDirectory);
    //      
    //      // Create the dummy master password provider
    //      masterPasswordProvider = new DummyMasterPasswordProvider();
    //      masterPasswordProvider.setMasterPassword(masterPassword);
    //      List<MasterPasswordProvider> masterPasswordProviders = new ArrayList<MasterPasswordProvider>();
    //      masterPasswordProviders.add(masterPasswordProvider);
    //      credentialManager.setMasterPasswordProviders(masterPasswordProviders);
    //      
    //      // Add some stuff into Credential Manager
    //      credentialManager.addUsernameAndPasswordForService(usernamePassword, serviceURI);
    //      credentialManager.addUsernameAndPasswordForService(usernamePassword2, serviceURI2);
    //      credentialManager.addUsernameAndPasswordForService(usernamePassword3, serviceURI3);
    //      credentialManager.addKeyPair(privateKey, privateKeyCertChain);
    //      credentialManager.addTrustedCertificate(trustedCertficate);

    // Set up a random temp directory and copy the test keystore files 
    // from resources/security
    Random randomGenerator = new Random();
    String credentialManagerDirectoryPath = System.getProperty("java.io.tmpdir")
            + System.getProperty("file.separator") + "taverna-security-" + randomGenerator.nextInt(1000000);
    System.out.println("Credential Manager's directory path: " + credentialManagerDirectoryPath);
    credentialManagerDirectory = new File(credentialManagerDirectoryPath);
    if (!credentialManagerDirectory.exists()) {
        credentialManagerDirectory.mkdir();
    }
    URL keystoreFileURL = CredentialManagerImplIT.class.getResource("/security/t2keystore.ubr");
    File keystoreFile = new File(keystoreFileURL.getPath());
    File keystoreDestFile = new File(credentialManagerDirectory, "taverna-keystore.ubr");
    URL truststroreFileURL = CredentialManagerImplIT.class.getResource("/security/t2truststore.ubr");
    File truststoreFile = new File(truststroreFileURL.getPath());
    File truststoreDestFile = new File(credentialManagerDirectory, "taverna-truststore.ubr");
    FileUtils.copyFile(keystoreFile, keystoreDestFile);
    FileUtils.copyFile(truststoreFile, truststoreDestFile);
    credentialManager.setConfigurationDirectoryPath(credentialManagerDirectory);

    // Create the dummy master password provider
    masterPasswordProvider = new DummyMasterPasswordProvider();
    masterPasswordProvider.setMasterPassword(masterPassword);
    List<MasterPasswordProvider> masterPasswordProviders = new ArrayList<MasterPasswordProvider>();
    masterPasswordProviders.add(masterPasswordProvider);
    credentialManager.setMasterPasswordProviders(masterPasswordProviders);

    // Set an empty list for trust confirmation providers
    credentialManager.setTrustConfirmationProviders(new ArrayList<TrustConfirmationProvider>());

    keystoreChangedObserver = new Observer<KeystoreChangedEvent>() {
        @Override
        public void notify(Observable<KeystoreChangedEvent> sender, KeystoreChangedEvent message)
                throws Exception {
            // TODO Auto-generated method stub
        }
    };
    credentialManager.addObserver(keystoreChangedObserver);
}

From source file:be.solidx.hot.nio.HttpsClient.java

private TrustManager[] handleTrustManagers(Map<String, Object> options)
        throws CertificateException, IOException, URISyntaxException {
    boolean rejectUnauthorized = (boolean) options.get(REJECTUNAUTHORIZED);
    if (options.get(CA) != null) {
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        return new TrustManager[] { new TrustManager(
                (X509Certificate) certificateFactory
                        .generateCertificate(getInputStream(new URI(options.get(CA).toString()))),
                rejectUnauthorized) };// w  w  w . ja  va2  s.c o  m
    } else if (!rejectUnauthorized) {
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        return new TrustManager[] { new TrustManager(null, rejectUnauthorized) };
    }
    return null;
}

From source file:XmldapCertsAndKeys.java

public static X509Certificate getXmldapCert1() throws CertificateException {
    byte[] certBytes = Base64.decode(cert1B64);
    CertificateFactory cf = CertificateFactory.getInstance("X509");
    ByteArrayInputStream inStream = new ByteArrayInputStream(certBytes);
    return (X509Certificate) cf.generateCertificate(inStream);
}