Example usage for java.security.cert CertificateFactory generateCertificate

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

Introduction

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

Prototype

public final Certificate generateCertificate(InputStream inStream) throws CertificateException 

Source Link

Document

Generates a certificate object and initializes it with the data read from the input stream inStream .

Usage

From source file:org.soyatec.windowsazure.internal.util.ssl.SslUtil.java

/**
 * Get a certificate object from given file.
 * //from  w  ww. j ava  2  s .c  o m
 * @param cert
 *            the file name.
 * @return a certificate object
 * @throws Exception
 */
public static X509Certificate getAbsolutePath(String cert) throws Exception {
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    FileInputStream in = new FileInputStream(cert);
    X509Certificate c = (X509Certificate) cf.generateCertificate(in);
    return c;
}

From source file:org.bankinterface.util.KeyStoreUtil.java

public static Certificate pemToCert(Reader r) throws IOException, CertificateException {
    String header = "-----BEGIN CERTIFICATE-----";
    String footer = "-----END CERTIFICATE-----";

    BufferedReader reader = new BufferedReader(r);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PrintStream ps = new PrintStream(baos);

    String line;/*from  w  w  w  .  j a v  a  2s  .  co  m*/

    // ignore up to the header
    while ((line = reader.readLine()) != null && !line.equals(header)) {
    }

    // no header found
    if (line == null) {
        throw new IOException("Error reading certificate, missing BEGIN boundary");
    }

    // in between the header and footer is the actual certificate
    while ((line = reader.readLine()) != null && !line.equals(footer)) {
        line = line.replaceAll("\\s", "");
        ps.print(line);
    }

    // no footer found
    if (line == null) {
        throw new IOException("Error reading certificate, missing END boundary");
    }
    ps.close();

    // decode the buffer to a X509Certificate
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    byte[] certBytes = Base64.decodeBase64(baos.toByteArray());
    return cf.generateCertificate(new ByteArrayInputStream(certBytes));
}

From source file:be.fedict.trust.BelgianTrustValidatorFactory.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);
    }/* www  .jav  a2s .  co  m*/
    try {
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        X509Certificate certificate = (X509Certificate) certificateFactory
                .generateCertificate(certificateInputStream);
        return certificate;
    } catch (CertificateException e) {
        throw new RuntimeException("X509 error: " + e.getMessage(), e);
    }
}

From source file:org.apache.xml.security.keys.keyresolver.implementations.RetrievalMethodResolver.java

private static X509Certificate getRawCertificate(XMLSignatureInput resource)
        throws CanonicalizationException, IOException, CertificateException {
    byte inputBytes[] = resource.getBytes();
    // if the resource stores a raw certificate, we have to handle it
    CertificateFactory certFact = CertificateFactory.getInstance(XMLX509Certificate.JCA_CERT_ID);
    X509Certificate cert = (X509Certificate) certFact.generateCertificate(new ByteArrayInputStream(inputBytes));
    return cert;//  w  w  w  . j a  va 2 s  .  c o  m
}

From source file:Main.java

public static SSLSocketFactory setCertificates(InputStream... certificates) {
    try {// ww w. ja va  2 s  .  c  o  m
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null);
        int index = 0;
        for (InputStream certificate : certificates) {
            String certificateAlias = Integer.toString(index++);
            keyStore.setCertificateEntry(certificateAlias, certificateFactory.generateCertificate(certificate));
            try {
                if (certificate != null)
                    certificate.close();
            } catch (IOException e) {
            }
        }
        SSLContext sslContext = SSLContext.getInstance("TLS");
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(keyStore);
        sslContext.init(null, trustManagerFactory.getTrustManagers(), new SecureRandom());
        socketFactory = sslContext.getSocketFactory();

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

From source file:cn.mrdear.pay.util.RSAUtils.java

/**
 * ??// w w  w  . ja  va  2  s  .c  o m
 * 
 * @param type
 *            
 * @param inputStream
 *            ?
 * @return ?
 */
public static Certificate getCertificate(String type, InputStream inputStream) {
    Assert.isNotEmpty(type);
    Assert.notNull(inputStream);

    try {
        CertificateFactory certificateFactory = CertificateFactory.getInstance(type, PROVIDER);
        return certificateFactory.generateCertificate(inputStream);
    } catch (CertificateException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}

From source file:org.wso2.carbon.identity.authenticator.x509Certificate.X509CertificateUtil.java

/**
 * Validate the user certificate/*from ww w.  jav  a  2  s . c  o  m*/
 *
 * @param userName         name of the user
 * @param certificateBytes x509 certificate
 * @return boolean status of the action
 * @throws AuthenticationFailedException
 */
public static boolean validateCertificate(String userName, AuthenticationContext authenticationContext,
        byte[] certificateBytes, boolean isSelfRegistrationEnable) throws AuthenticationFailedException {
    X509Certificate x509Certificate;
    try {
        CertificateFactory cf = CertificateFactory.getInstance("X509");
        x509Certificate = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(certificateBytes));

        if (isSelfRegistrationEnable && isCertificateExist(userName)
                && !isUserCertificateValid(userName, x509Certificate)) {
            return false;
        } else if (!isSelfRegistrationEnable && !isUserExists(userName, authenticationContext)) {
            return false;
        }

        if (isCertificateRevoked(x509Certificate)) {
            if (log.isDebugEnabled()) {
                log.debug("X509 certificate with serial num: " + x509Certificate.getSerialNumber()
                        + " is revoked");
            }
            if (isSelfRegistrationEnable) {
                deleteUserCertificate(userName, x509Certificate);
            }
            return false;
        } else if (isSelfRegistrationEnable && !isCertificateExist(userName)) {
            addUserCertificate(userName, x509Certificate);
        }
    } catch (CertificateException e) {
        throw new AuthenticationFailedException("Error while retrieving certificate ", e);
    } catch (CertificateValidationException e) {
        throw new AuthenticationFailedException("Error while validating client certificate with serial num: ",
                e);
    } catch (UserStoreException e) {
        throw new AuthenticationFailedException("Cannot find the user realm for the username: " + userName, e);
    }
    return true;
}

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 ww .j a v  a  2s  .  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.wso2.carbon.identity.authenticator.x509Certificate.X509CertificateUtil.java

/**
 * Get certificate from claims./*  w  w  w .j  ava 2s  .co  m*/
 *
 * @param username name of the user
 * @return x509 certificate
 * @throws AuthenticationFailedException authentication failed exception
 */
public static X509Certificate getCertificate(String username) throws AuthenticationFailedException {
    X509Certificate x509Certificate;
    UserRealm userRealm = getUserRealm(username);
    try {
        String tenantAwareUsername = MultitenantUtils.getTenantAwareUsername(username);
        String claimURI = getClaimUri();
        if (userRealm != null) {
            Map<String, String> userClaimValues = userRealm.getUserStoreManager()
                    .getUserClaimValues(tenantAwareUsername, new String[] { claimURI }, null);
            String userCertificate = userClaimValues.get(claimURI);
            if (log.isDebugEnabled()) {
                log.debug("The user certificate is " + userCertificate);
            }
            if (StringUtils.isNotEmpty(userCertificate)) {
                CertificateFactory cf = CertificateFactory.getInstance("X509");
                x509Certificate = (X509Certificate) cf
                        .generateCertificate(new ByteArrayInputStream(Base64.decode(userCertificate)));
            } else {
                return null;
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug("UserRealm is null for username: " + username);
            }
            throw new AuthenticationFailedException("Cannot find the user realm for the given tenant domain : "
                    + CarbonContext.getThreadLocalCarbonContext().getTenantDomain());
        }
    } catch (CertificateException e) {
        throw new AuthenticationFailedException("Error while decoding the certificate ", e);
    } catch (UserStoreException e) {
        throw new AuthenticationFailedException("Error while retrieving the user store manager ", e);
    }
    return x509Certificate;
}

From source file:org.globus.gsi.ptls.PureTLSUtil.java

/**
 * Converts PureTLS specific X509 certificate object 
 * into standard Java X509 certificate object
 * (right now it is using BouncyCastle provider to 
 * convert)./*  ww w.  j ava2s  .c o  m*/
 *
 * @param cert PureTLS X509 certificate object 
 * @return standard Java X509 certificate object
 * @exception GeneralSecurityException if conversion fails.
 */
public static X509Certificate convertCert(X509Cert cert) throws GeneralSecurityException {
    CertificateFactory f = CertificateFactory.getInstance("X.509", "BC");
    ByteArrayInputStream in = new ByteArrayInputStream(cert.getDER());
    return (X509Certificate) f.generateCertificate(in);
}