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:org.apache.cxf.fediz.service.idp.protocols.TrustedIdpSAMLProtocolHandler.java

private Crypto getCrypto(String certificate) throws ProcessingException {
    if (certificate == null) {
        return null;
    }//from  w ww . ja  va 2  s.  c  om

    // First see if it's a certificate file
    InputStream is = null;
    try {
        is = Merlin.loadInputStream(Thread.currentThread().getContextClassLoader(), certificate);

        CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
        X509Certificate cert = (X509Certificate) certFactory.generateCertificate(is);
        return new CertificateStore(new X509Certificate[] { cert });
    } catch (WSSecurityException ex) {
        LOG.error("Failed to load keystore " + certificate, ex);
        throw new RuntimeException("Failed to load keystore " + certificate);
    } catch (IOException ex) {
        LOG.error("Failed to read keystore", ex);
        throw new RuntimeException("Failed to read keystore");
    } catch (CertificateException ex) {
        // This is ok as it could be a WSS4J properties file
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                // Do nothing
            }
        }
    }

    // Maybe it's a WSS4J properties file...
    return CertsUtils.createCrypto(certificate);
}

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

@Test
public void testTrustConfirmationAddDeleteCertificateDirectly()
        throws CMException, IOException, CertificateException {
    // Initially trust provider list is empty, we only verify by what is in 
    // Credential Manager's Truststore (and it does not contains the certificate for https://heater.cs.man.ac.uk:7443/)

    // Do not forget to initialise Taverna's/Credential Manager's SSLSocketFactory
    credentialManager.initializeSSL();//from   ww w .  j a v a2  s.  c o m

    URL url = new URL("https://heater.cs.man.ac.uk:7443/");
    HttpsURLConnection conn;
    conn = (HttpsURLConnection) url.openConnection();
    try {
        // This should fail
        conn.connect();
        fail("Connection to https://heater.cs.man.ac.uk:7443/ should be untrusted at this point.");
    } catch (SSLHandshakeException sslex) {
        // expected to fail so all is good
    } finally {
        conn.disconnect();
    }

    // Add heater's certificate directly to Credential Manager's Truststore

    // Load the test trusted certificate (belonging to heater.cs.man.ac.uk)
    X509Certificate trustedCertficate;
    URL trustedCertficateFileURL = getClass().getResource("/security/tomcat_heater_certificate.pem");
    System.out.println("testTrustConfirmationAddDeleteCertificateDirectly: trusted certficate file URL "
            + trustedCertficateFileURL);
    File trustedCertFile = new File(trustedCertficateFileURL.getPath());
    FileInputStream inStream = new FileInputStream(trustedCertFile);
    //InputStream inStream = getClass().getClassLoader().getResourceAsStream("security/tomcat_heater_certificate.pem");
    CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
    trustedCertficate = (X509Certificate) certFactory.generateCertificate(inStream);
    try {
        inStream.close();
    } catch (Exception e) {
        // Ignore
    }
    String alias = credentialManager.addTrustedCertificate(trustedCertficate);

    HttpsURLConnection conn2 = (HttpsURLConnection) url.openConnection();
    // This should work now
    conn2.connect();
    //System.out.println(conn2.getHeaderField(0));

    assertEquals("HTTP/1.1 200 OK", conn2.getHeaderField(0));
    conn2.disconnect();

    // Now remove certificate and see if the "trust" changes
    credentialManager.deleteTrustedCertificate(alias);
    HttpsURLConnection conn3;
    conn3 = (HttpsURLConnection) url.openConnection();
    try {
        // This should fail
        conn3.connect();
        fail("Connection to https://heater.cs.man.ac.uk:7443/ should be untrusted at this point.");
    } catch (SSLHandshakeException sslex) {
        // expected to fail so all is good
    } finally {
        conn3.disconnect();
    }
}

From source file:be.fedict.eid.applet.service.signer.time.TSPTimeStampService.java

private static X509Certificate loadCertificate(String resourceName) {
    LOG.debug("loading certificate: " + resourceName);
    Thread currentThread = Thread.currentThread();
    ClassLoader classLoader = currentThread.getContextClassLoader();
    InputStream certificateInputStream = classLoader.getResourceAsStream(resourceName);
    if (null == certificateInputStream) {
        throw new IllegalArgumentException("resource not found: " + resourceName);
    }//from w  w w.j  a va  2 s . co m
    try {
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        return (X509Certificate) certificateFactory.generateCertificate(certificateInputStream);
    } catch (CertificateException e) {
        throw new RuntimeException("X509 error: " + e.getMessage(), e);
    }
}

From source file:org.hyperledger.fabric.sdk.security.CryptoPrimitivesTest.java

@BeforeClass
public static void setUpBeforeClass() throws Exception {
    config = Config.getConfig();// w  w w .  j av a2 s.c  om

    plainText = DatatypeConverter.parseHexBinary(PLAIN_TEXT_HEX);
    sig = DatatypeConverter.parseHexBinary(SIGNATURE_HEX);
    pemCert = DatatypeConverter.parseHexBinary(PEM_CERT_HEX);
    invalidPemCert = DatatypeConverter.parseHexBinary(INVALID_PEM_CERT);

    kf = KeyFactory.getInstance("EC");

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

    crypto = new CryptoPrimitives();
    crypto.init();

}

From source file:tf.nox.wifisetup.WifiSetup.java

@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
private void applyAndroid43EnterpriseSettings(WifiConfiguration currentConfig,
        HashMap<String, String> configMap) {
    try {/*from w w w .  ja v a2  s .  co  m*/
        CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
        InputStream in = getResources().openRawResource(R.raw.cacert);
        // InputStream in = new ByteArrayInputStream(Base64.decode(ca.replaceAll("-----(BEGIN|END) CERTIFICATE-----", ""), 0));
        X509Certificate caCert = (X509Certificate) certFactory.generateCertificate(in);

        WifiEnterpriseConfig enterpriseConfig = new WifiEnterpriseConfig();
        enterpriseConfig.setPhase2Method(Phase2.PAP);
        enterpriseConfig.setAnonymousIdentity(configMap.get(INT_ANONYMOUS_IDENTITY));
        enterpriseConfig.setEapMethod(Eap.TTLS);

        enterpriseConfig.setCaCertificate(caCert);
        enterpriseConfig.setIdentity(s_username);
        enterpriseConfig.setPassword(s_password);
        enterpriseConfig.setSubjectMatch(configMap.get(INT_SUBJECT_MATCH));
        currentConfig.enterpriseConfig = enterpriseConfig;

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

From source file:com.zimbra.cs.service.mail.CreateContact.java

private static String parseCertificate(Element elt, String name, ZimbraSoapContext zsc, OperationContext octxt,
        Contact existing) throws ServiceException {
    String attachId = elt.getAttribute(MailConstants.A_ATTACHMENT_ID, null);
    String result = "";
    InputStream in = null;//from  w  w  w  .  j  av  a2  s.  c om
    if (!Strings.isNullOrEmpty(attachId)) {
        Upload up = FileUploadServlet.fetchUpload(zsc.getAuthtokenAccountId(), attachId, zsc.getAuthToken());
        try {
            ZimbraLog.contact.debug("start processing contact certificate with aid=%s for account=%s", attachId,
                    zsc.getRequestedAccountId());
            in = up.getInputStream();
            byte[] certBytes = IOUtils.toByteArray(in);
            // Load the certificate using Keystore just to make sure it is a valid certificate file.
            // No other validation is done here.
            CertificateFactory factory = CertificateFactory.getInstance(SmimeConstants.PUB_CERT_TYPE);
            factory.generateCertificate(new ByteArrayInputStream(certBytes));
            result = ByteUtil.encodeLDAPBase64(certBytes);
        } catch (IOException | CertificateException e) {
            ZimbraLog.contact.error("Exception in adding user certificate with aid=%s for account %s", attachId,
                    zsc.getRequestedAccountId());
            throw ServiceException.INVALID_REQUEST("Exception in adding certificate", e);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    ZimbraLog.contact.error("Exception in closing inputstream for attachment", e);
                }
            }
        }
    }
    return result;
}

From source file:com.persistent.cloudninja.controller.AuthFilterUtils.java

/**
 * Get Certificate thumb print and Issuer Name from the ACS token.
 * @param acsToken the acs token/*from w  w  w .ja va2s .com*/
 * @return returnData the Map containing Thumb print and issuer name of X509Certiificate
 * @throws NoSuchAlgorithmException
 * @throws CertificateEncodingException
 */
public static Map<String, String> getCertificateThumbPrintAndIssuerName(String acsToken)
        throws NoSuchAlgorithmException, CertificateEncodingException {
    byte[] acsTokenByteArray = null;
    Map<String, String> returnData = new HashMap<String, String>();

    try {
        acsTokenByteArray = acsToken.getBytes("UTF-8");
    } catch (UnsupportedEncodingException e) {
        return null;
    }
    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    builderFactory.setNamespaceAware(true);
    DocumentBuilder docBuilder;
    String issuerName = null;
    StringBuffer thumbprint = null;

    try {
        docBuilder = builderFactory.newDocumentBuilder();
        Document resultDoc = docBuilder.parse(new ByteArrayInputStream(acsTokenByteArray));
        Element keyInfo = (Element) resultDoc.getDocumentElement()
                .getElementsByTagNameNS("http://www.w3.org/2000/09/xmldsig#", "KeyInfo").item(0);

        NodeList x509CertNodeList = keyInfo.getElementsByTagName("X509Certificate");
        Element x509CertNode = (Element) x509CertNodeList.item(0);
        if (x509CertNode == null) {
            return null;
        }
        //generating Certificate to retrieve its detail.
        String x509CertificateData = x509CertNode.getTextContent();
        InputStream inStream = new Base64InputStream(new ByteArrayInputStream(x509CertificateData.getBytes()));
        CertificateFactory x509CertificateFactory = CertificateFactory.getInstance("X.509");
        X509Certificate x509Certificate = (X509Certificate) x509CertificateFactory
                .generateCertificate(inStream);
        String issuerDN = x509Certificate.getIssuerDN().toString();
        String[] issuerDNData = issuerDN.split("=");
        issuerName = issuerDNData[1];

        MessageDigest md = MessageDigest.getInstance("SHA-1");
        byte[] der = x509Certificate.getEncoded();
        md.update(der);
        thumbprint = new StringBuffer();
        thumbprint.append(Hex.encodeHex(md.digest()));
    } catch (Exception e) {
        e.printStackTrace();
    }
    returnData.put("IssuerName", issuerName);
    returnData.put("Thumbprint", thumbprint.toString().toUpperCase());
    return returnData;
}

From source file:org.hyperledger.fabric.sdk.MemberServicesImpl.java

/**
 * Process a batch of tcerts after having retrieved them from the TCA.
 *//*from ww w . j av  a2s  .c  o  m*/
private List<TCert> processTCertBatch(GetTCertBatchRequest req, TCertCreateSetResp resp)
        throws NoSuchPaddingException, InvalidKeyException, NoSuchAlgorithmException, IllegalBlockSizeException,
        BadPaddingException, InvalidAlgorithmParameterException, CryptoException, IOException {
    String enrollKey = req.getEnrollment().getKey();
    byte[] tCertOwnerKDFKey = resp.getCerts().getKey().toByteArray();
    List<Ca.TCert> tCerts = resp.getCerts().getCertsList();

    byte[] byte1 = new byte[] { 1 };
    byte[] byte2 = new byte[] { 2 };

    byte[] tCertOwnerEncryptKey = Arrays.copyOfRange(cryptoPrimitives.calculateMac(tCertOwnerKDFKey, byte1), 0,
            32);
    byte[] expansionKey = cryptoPrimitives.calculateMac(tCertOwnerKDFKey, byte2);

    List<TCert> tCertBatch = new ArrayList<>(tCerts.size());

    // Loop through certs and extract private keys
    for (Ca.TCert tCert : tCerts) {
        X509Certificate x509Certificate;
        try {
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            x509Certificate = (X509Certificate) cf.generateCertificate(tCert.getCert().newInput());
        } catch (Exception ex) {
            logger.debug("Warning: problem parsing certificate bytes; retrying ... ", ex);
            continue;
        }

        // extract the encrypted bytes from extension attribute
        byte[] tCertIndexCT = fromDer(x509Certificate.getExtensionValue(TCERT_ENC_TCERT_INDEX));
        byte[] tCertIndex = cryptoPrimitives.aesCBCPKCS7Decrypt(tCertOwnerEncryptKey, tCertIndexCT);

        byte[] expansionValue = cryptoPrimitives.calculateMac(expansionKey, tCertIndex);

        // compute the private key
        BigInteger k = new BigInteger(1, expansionValue);
        BigInteger n = ((ECPrivateKey) cryptoPrimitives.ecdsaKeyFromPrivate(Hex.decode(enrollKey)))
                .getParameters().getN().subtract(BigInteger.ONE);
        k = k.mod(n).add(BigInteger.ONE);

        BigInteger D = ((ECPrivateKey) cryptoPrimitives.ecdsaKeyFromPrivate(Hex.decode(enrollKey))).getD()
                .add(k);
        D = D.mod(((ECPrivateKey) cryptoPrimitives.ecdsaKeyFromPrivate(Hex.decode(enrollKey))).getParameters()
                .getN());

        // Put private and public key in returned tcert
        TCert tcert = new TCert(tCert.getCert().toByteArray(), cryptoPrimitives.ecdsaKeyFromBigInt(D));

        tCertBatch.add(tcert);
    }

    if (tCertBatch.size() == 0) {
        throw new RuntimeException("Failed fetching TCertBatch. No valid TCert received.");
    }

    return tCertBatch;
}

From source file:com.solace.samples.cloudfoundry.securesession.controller.SolaceController.java

/**
 * This utility function installs a certificate into the JRE's trusted
 * store. Normally you would not do this, but this is provided to
 * demonstrate how to use TLS, and have the client validate a self-signed
 * server certificate./*from w  w w  . j  a v a2s.c om*/
 *
 * @throws Exception
 */
private static void importCertificate() throws Exception {

    File file = new File(CERTIFICATE_FILE_NAME);
    logger.info("Loading certificate from " + file.getAbsolutePath());

    // This loads the KeyStore from the default location
    // (i.e. default for a Clound Foundry app) using the default password.
    FileInputStream is = new FileInputStream(TRUST_STORE);
    char[] password = TRUST_STORE_PASSWORD.toCharArray();
    KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
    keystore.load(is, password);
    is.close();

    // Create an ByteArrayInputStream stream from the
    FileInputStream fis = new FileInputStream(CERTIFICATE_FILE_NAME);
    DataInputStream dis = new DataInputStream(fis);
    byte[] bytes = new byte[dis.available()];
    dis.readFully(bytes);
    dis.close();
    ByteArrayInputStream certstream = new ByteArrayInputStream(bytes);

    // This takes that Byte Array and creates a certificate out of it.
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    Certificate certs = cf.generateCertificate(certstream);

    // Finally, store the new certificate in the keystore.
    keystore.setCertificateEntry(CERTIFICATE_ALIAS, certs);

    // Save the new keystore contents
    FileOutputStream out = new FileOutputStream(TRUST_STORE);
    keystore.store(out, password);
    out.close();

}

From source file:org.cesecore.util.PKIXCertRevocationStatusChecker.java

private CRL getCRL(final URL url) {
    CRL crl = null;// w  w w  .ja  va2  s  . co  m
    try {
        final URLConnection con = url.openConnection();
        final InputStream is = con.getInputStream();
        final CertificateFactory cf = CertificateFactory.getInstance("X.509");
        crl = cf.generateCRL(is);
        is.close();
        log.info("Downloaded CRL from " + url);
    } catch (IOException | CertificateException | CRLException e) {
        if (log.isDebugEnabled()) {
            log.debug("Fetching CRL from " + url.toString() + " failed. " + e.getLocalizedMessage());
        }
    }
    return crl;
}