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:net.link.util.test.pkix.PkiTestUtils.java

public static X509Certificate loadCertificate(InputStream inputStream) throws CertificateException {

    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    return (X509Certificate) certificateFactory.generateCertificate(inputStream);
}

From source file:org.taverna.server.master.localworker.SecurityContextDelegate.java

@Override
public void validateTrusted(Trust t) throws InvalidCredentialException {
    InputStream contentsAsStream;
    if (t.certificateBytes != null && t.certificateBytes.length > 0) {
        contentsAsStream = new ByteArrayInputStream(t.certificateBytes);
        t.certificateFile = null;// www  . j  av a2  s  .c  o m
    } else if (t.certificateFile == null || t.certificateFile.trim().isEmpty())
        throw new InvalidCredentialException("absent or empty certificateFile");
    else {
        contentsAsStream = contents(t.certificateFile);
        t.certificateBytes = null;
    }
    t.serverName = null;
    if (t.fileType == null || t.fileType.trim().isEmpty())
        t.fileType = DEFAULT_CERTIFICATE_TYPE;
    t.fileType = t.fileType.trim();
    try {
        t.loadedCertificates = CertificateFactory.getInstance(t.fileType)
                .generateCertificates(contentsAsStream);
        t.serverName = new ArrayList<String>(t.loadedCertificates.size());
        for (Certificate c : t.loadedCertificates)
            t.serverName.add(getPrincipalName(((X509Certificate) c).getSubjectX500Principal()));
    } catch (CertificateException e) {
        throw new InvalidCredentialException(e);
    } catch (ClassCastException e) {
        // Do nothing; truncates the list of server names
    }
}

From source file:io.hops.hopsworks.util.CertificateHelper.java

private static X509Certificate getX509Cert(File cert) throws IllegalStateException {
    try (InputStream inStream = new FileInputStream(cert)) {
        CertificateFactory factory = CertificateFactory.getInstance("X.509");
        X509Certificate x509Cert = (X509Certificate) factory.generateCertificate(inStream);
        return x509Cert;
    } catch (CertificateException | IOException ex) {
        LOG.log(Level.SEVERE, "cert ex {0}", ex);
        throw new IllegalStateException("cert ex", ex);
    }//from w w  w  .j  a  v  a  2  s  . c  o m
}

From source file:nu.yona.server.AppServiceApplication.java

private X509Certificate loadCertificateFromFile(String fileName, String description) {
    logger.info("Loading {} certificate from {}", description, fileName);
    try (InputStream inStream = new FileInputStream(fileName)) {
        return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(inStream);
    } catch (IOException | CertificateException e) {
        throw YonaException.unexpected(e);
    }/*from   w w w. j  a  va 2s.  c o m*/
}

From source file:edu.washington.iam.tools.IamConnectionManager.java

protected X509Certificate readCertificate(String filename) {
    FileInputStream file;//from  www.  j a  va2  s .c om
    X509Certificate cert;
    try {
        file = new FileInputStream(filename);
    } catch (IOException e) {
        log.error("ldap source bad cert file: " + e);
        return null;
    }
    try {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        cert = (X509Certificate) cf.generateCertificate(file);
    } catch (CertificateException e) {
        log.error("ldap source bad cert: " + e);
        return null;
    }
    return cert;
}

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

public static void importPKCS8CertChain(KeyStore ks, String alias, byte[] keyBytes, String keyPass,
        byte[] certChain)
        throws InvalidKeySpecException, NoSuchAlgorithmException, CertificateException, KeyStoreException {
    // load the private key
    KeyFactory kf = KeyFactory.getInstance("RSA");
    PKCS8EncodedKeySpec keysp = new PKCS8EncodedKeySpec(keyBytes);
    PrivateKey pk = kf.generatePrivate(keysp);

    // load the cert chain
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    ByteArrayInputStream bais = new ByteArrayInputStream(certChain);

    Collection<? extends Certificate> certCol = cf.generateCertificates(bais);
    Certificate[] certs = new Certificate[certCol.toArray().length];
    if (certCol.size() == 1) {
        logger.info("Single certificate; no chain");
        bais = new ByteArrayInputStream(certChain);
        Certificate cert = cf.generateCertificate(bais);
        certs[0] = cert;//from www  . j  ava2 s  . c  om
    } else {
        logger.info("Certificate chain length : " + certCol.size());
        certs = certCol.toArray(new Certificate[certCol.size()]);
    }

    ks.setKeyEntry(alias, pk, keyPass.toCharArray(), certs);
}

From source file:org.apache.airavata.credential.store.server.CredentialStoreServerHandler.java

@Override
public String addCertificateCredential(CertificateCredential certificateCredential)
        throws org.apache.airavata.credential.store.exception.CredentialStoreException, TException {
    try {/*from w  w  w .  ja  v a  2 s.c  om*/
        org.apache.airavata.credential.store.credential.impl.certificate.CertificateCredential credential = new org.apache.airavata.credential.store.credential.impl.certificate.CertificateCredential();
        credential.setPortalUserName(certificateCredential.getCommunityUser().getUsername());
        credential.setCommunityUser(new CommunityUser(certificateCredential.getCommunityUser().getGatewayName(),
                certificateCredential.getCommunityUser().getUsername(),
                certificateCredential.getCommunityUser().getUserEmail()));
        String token = TokenGenerator.generateToken(certificateCredential.getCommunityUser().getGatewayName(),
                null);
        credential.setToken(token);
        Base64 encoder = new Base64(64);
        byte[] decoded = encoder.decode(certificateCredential.getX509Cert()
                .replaceAll(X509Factory.BEGIN_CERT, "").replaceAll(X509Factory.END_CERT, ""));
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        X509Certificate certificate = (X509Certificate) cf
                .generateCertificate(new ByteArrayInputStream(decoded));
        X509Certificate[] certificates = new X509Certificate[1];
        certificates[0] = certificate;
        credential.setCertificates(certificates);
        certificateCredentialWriter.writeCredentials(credential);
        return token;
    } catch (CredentialStoreException e) {
        log.error("Error occurred while saving Certificate Credentials.", e);
        throw new org.apache.airavata.credential.store.exception.CredentialStoreException(
                "Error occurred while saving Certificate Credentials.");
    } catch (Exception e) {
        log.error("Error occurred while converting to X509 certificate.", e);
        throw new org.apache.airavata.credential.store.exception.CredentialStoreException(
                "Error occurred while converting to X509 certificate..");
    }
}

From source file:mx.com.quadrum.service.util.firma.ValidacionesCertificado.java

/**
 * Mtodo que valida si el certificado es apocrifo, no valido ante el SAT
 *
 * @param cert Certificado a validar//from ww w .ja  v a 2  s.  c o m
 * @return true si el certificado es apocrifo, en otro caso false
 */
public boolean validateCertificate() {
    try {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        List mylist = new ArrayList();
        TrustAnchor anchor = new TrustAnchor(
                (java.security.cert.X509Certificate) importCertificate(cerInputStream), null);
        mylist.add(certificado);
        CertPath cp = cf.generateCertPath(mylist);
        PKIXParameters params = new PKIXParameters(Collections.singleton(anchor));
        params.setRevocationEnabled(false);
        CertPathValidator cpv = CertPathValidator.getInstance("PKIX");
        return true;
    } catch (Exception ex) {
        System.out.println("Expecion causada a proposito :P");
    }
    return false;
}

From source file:org.wso2.emm.agent.utils.CommonUtils.java

/**
 * Generates keys, CSR and certificates for the devices.
 * @param context - Application context.
 * @param listener - DeviceCertCreationListener which provide device .
 *//*from  w ww .j  a  v  a  2 s  .c  o  m*/
public static void generateDeviceCertificate(final Context context, final DeviceCertCreationListener listener)
        throws AndroidAgentException {

    if (context.getFileStreamPath(Constants.DEVICE_CERTIFCATE_NAME).exists()) {
        try {
            listener.onDeviceCertCreated(
                    new BufferedInputStream(context.openFileInput(Constants.DEVICE_CERTIFCATE_NAME)));
        } catch (FileNotFoundException e) {
            Log.e(TAG, e.getMessage());
        }
    } else {

        try {
            ServerConfig utils = new ServerConfig();
            final KeyPair deviceKeyPair = KeyPairGenerator.getInstance(Constants.DEVICE_KEY_TYPE)
                    .generateKeyPair();
            X500Principal subject = new X500Principal(Constants.DEVICE_CSR_INFO);
            PKCS10CertificationRequest csr = new PKCS10CertificationRequest(Constants.DEVICE_KEY_ALGO, subject,
                    deviceKeyPair.getPublic(), null, deviceKeyPair.getPrivate());

            EndPointInfo endPointInfo = new EndPointInfo();
            endPointInfo.setHttpMethod(org.wso2.emm.agent.proxy.utils.Constants.HTTP_METHODS.POST);
            endPointInfo.setEndPoint(utils.getAPIServerURL(context) + Constants.SCEP_ENDPOINT);
            endPointInfo.setRequestParams(Base64.encodeToString(csr.getEncoded(), Base64.DEFAULT));

            new APIController().invokeAPI(endPointInfo, new APIResultCallBack() {
                @Override
                public void onReceiveAPIResult(Map<String, String> result, int requestCode) {
                    try {
                        CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
                        InputStream in = new ByteArrayInputStream(
                                Base64.decode(result.get("response"), Base64.DEFAULT));
                        X509Certificate cert = (X509Certificate) certFactory.generateCertificate(in);
                        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                        KeyStore keyStore = KeyStore.getInstance("PKCS12");
                        keyStore.load(null);
                        keyStore.setKeyEntry(Constants.DEVICE_CERTIFCATE_ALIAS,
                                (Key) deviceKeyPair.getPrivate(),
                                Constants.DEVICE_CERTIFCATE_PASSWORD.toCharArray(),
                                new java.security.cert.Certificate[] { cert });
                        keyStore.store(byteArrayOutputStream,
                                Constants.DEVICE_CERTIFCATE_PASSWORD.toCharArray());
                        FileOutputStream outputStream = context.openFileOutput(Constants.DEVICE_CERTIFCATE_NAME,
                                Context.MODE_PRIVATE);
                        outputStream.write(byteArrayOutputStream.toByteArray());
                        byteArrayOutputStream.close();
                        outputStream.close();
                        try {
                            listener.onDeviceCertCreated(new BufferedInputStream(
                                    context.openFileInput(Constants.DEVICE_CERTIFCATE_NAME)));
                        } catch (FileNotFoundException e) {
                            Log.e(TAG, e.getMessage());
                        }
                    } catch (CertificateException e) {
                        Log.e(TAG, e.getMessage());
                    } catch (KeyStoreException e) {
                        e.printStackTrace();
                    } catch (NoSuchAlgorithmException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }, Constants.SCEP_REQUEST_CODE, context, true);

        } catch (NoSuchAlgorithmException e) {
            throw new AndroidAgentException("No algorithm for key generation", e);
        } catch (SignatureException e) {
            throw new AndroidAgentException("Invalid Signature", e);
        } catch (NoSuchProviderException e) {
            throw new AndroidAgentException("Invalid provider", e);
        } catch (InvalidKeyException e) {
            throw new AndroidAgentException("Invalid key", e);
        }

    }

}

From source file:com.cedarsoft.crypt.X509Support.java

/**
 * Reads the x509 certificate from the given url
 *
 * @param certificateUrl the certificate url
 * @return the certificate/*from  w w  w. j a  va  2  s  . c om*/
 *
 * @throws IOException if any.
 * @throws GeneralSecurityException
 *                             if any.
 */
@Nonnull
public static X509Certificate readCertificate(@Nonnull URL certificateUrl)
        throws IOException, GeneralSecurityException {
    //Read the cert
    DataInputStream in = new DataInputStream(certificateUrl.openStream());
    try {
        CertificateFactory cf = CertificateFactory.getInstance(X_509_CERTIFICATE_TYPE);
        X509Certificate certificate = (X509Certificate) cf.generateCertificate(in);
        certificate.checkValidity();
        return certificate;
    } finally {
        in.close();
    }
}