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:Main.java

public static PKIXCertPathValidatorResult validateCertificate(X509Certificate entity,
        X509Certificate intermediate, X509Certificate CA) throws Exception {
    /*  KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
      ks.load(null, null);// ww  w . ja  v  a  2s  .c  o  m
      String alias = "validationCA";
      ks.setCertificateEntry(alias, CA);
            
     */
    /*  KeyStore intermediatesStore = KeyStore.getInstance(KeyStore.getDefaultType());
    intermediatesStore.load(null, null);
    String alias_intermediate = "validationIntermediate";
    intermediatesStore.setCertificateEntry(alias_intermediate, intermediate);*//*
                                                                                        
                                                                                        
                                                                                X509CertSelector target = new X509CertSelector();
                                                                                target.setCertificate(entity);
                                                                                PKIXBuilderParameters params = new PKIXBuilderParameters(ks, target);
                                                                                ArrayList<X509Certificate> chain = new ArrayList<>();
                                                                                chain.add(intermediate);
                                                                                chain.add(intermediate);
                                                                                CertStoreParameters intermediates = new CollectionCertStoreParameters(chain);
                                                                                params.addCertStore(CertStore.getInstance("Collection", intermediates));
                                                                                CertPathBuilder builder = CertPathBuilder.getInstance("PKIX");
                                                                                 *//*
                                                                                    * If build() returns successfully, the certificate is valid. More details
                                                                                    * about the valid path can be obtained through the PKIXBuilderResult.
                                                                                    * If no valid path can be found, a CertPathBuilderException is thrown.
                                                                                    *//*
                                                                                          PKIXCertPathBuilderResult result = (PKIXCertPathBuilderResult)builder.build(params);
                                                                                          return result;*/

    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    CertPath certPath = certificateFactory
            .generateCertPath(Arrays.asList(new X509Certificate[] { entity, intermediate }));

    TrustAnchor trustAnchor = new TrustAnchor(CA, null);

    CertPathValidator cpv = CertPathValidator.getInstance("PKIX");

    PKIXParameters pkixParams = new PKIXParameters(Collections.singleton(trustAnchor));
    pkixParams.setRevocationEnabled(true);

    return (PKIXCertPathValidatorResult) cpv.validate(certPath, pkixParams);
}

From source file:com.vmware.identity.openidconnect.protocol.PersonUserCertificateGrant.java

public static PersonUserCertificateGrant parse(Map<String, String> parameters) throws ParseException {
    Validate.notNull(parameters, "parameters");

    GrantType grantType = GrantType.parse(ParameterMapUtils.getString(parameters, "grant_type"));
    if (grantType != GRANT_TYPE) {
        throw new ParseException("unexpected grant_type: " + grantType.getValue());
    }//from   w w w .  ja  v  a2 s  .co  m

    String personUserCertificateString = ParameterMapUtils.getString(parameters, "person_user_certificate");

    byte[] certBytes = Base64Utils.decodeToBytes(personUserCertificateString);
    ByteArrayInputStream inputStream = new ByteArrayInputStream(certBytes);

    X509Certificate personUserCertificate;
    try {
        CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
        personUserCertificate = (X509Certificate) certFactory.generateCertificate(inputStream);
    } catch (CertificateException e) {
        throw new ParseException("failed to parse person_user_certificate parameter", e);
    }

    PersonUserAssertion personUserAssertion = PersonUserAssertion.parse(parameters);

    return new PersonUserCertificateGrant(personUserCertificate, personUserAssertion);
}

From source file:dk.nversion.jwt.CryptoUtils.java

public static PublicKey loadCertificate(String filename) throws FileNotFoundException, IOException,
        InvalidKeySpecException, NoSuchAlgorithmException, CertificateException {
    PublicKey key = null;/*from   ww w  .  j a va  2 s  .  c o m*/
    InputStream is = null;
    try {
        is = new FileInputStream(filename);
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        StringBuilder builder = new StringBuilder();
        boolean inKey = false;

        String line;
        while ((line = br.readLine()) != null) {
            if (!inKey) {
                if (line.startsWith("-----BEGIN CERTIFICATE-----")) {
                    inKey = true;
                }
            } else {
                if (line.startsWith("-----END CERTIFICATE-----")) {
                    break;
                }
                builder.append(line);
            }
        }

        if (builder.length() == 0) {
            throw new CertificateException("Did not find a certificate in the file");
        }

        byte[] encoded = Base64.decodeBase64(builder.toString());
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        X509Certificate certificate = (X509Certificate) cf
                .generateCertificate(new ByteArrayInputStream(encoded));
        key = certificate.getPublicKey();

    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException ex) {
                // Ignore
            }
        }
    }
    return key;
}

From source file:org.digidoc4j.X509Cert.java

/**
 * Creates an X509 certificate from a path.
 *
 * @param path X509 certificate path//from   ww w  . j a va 2s . c  o m
 * @throws Exception throws an exception if the X509 certificate parsing fails
 */
X509Cert(String path) throws CertificateException, IOException {
    logger.debug("");
    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    try (FileInputStream inStream = new FileInputStream(new File(path))) {
        originalCert = (X509Certificate) certificateFactory.generateCertificate(inStream);
    }
    logger.debug("Certificate created from path: " + path);
}

From source file:facturatron.facturacion.PAC.finkok.ClassicKeyLoader.java

/**
 * @param crtInputStream    Flujo de entrada del archivo que representa la llave pblica codificada
 *                          en x509// w  w w .ja va 2s.  c  o m
 *
 * @return  Informacin de la llave pblica encapsulada en el objeto {@link X509Certificate}
 *
 * @throws KeyException Lanzada si la codificacin del certificado no es correcta.
 */
public static X509Certificate loadX509Certificate(InputStream crtInputStream) throws KeyException {
    CertificateFactory factory = null;
    X509Certificate x509Crt = null;
    try {
        factory = CertificateFactory.getInstance("X.509");
        x509Crt = (X509Certificate) factory.generateCertificate(crtInputStream);
    } catch (CertificateException e) {
        throw new KeyException("Error al obtener el certificado x.509. La codificacin puede ser incorrecta.",
                e.getCause());
    }

    return x509Crt;
}

From source file:com.chiorichan.http.ssl.CertificateWrapper.java

public CertificateWrapper(File sslCertFile, File sslKeyFile, String sslSecret)
        throws FileNotFoundException, CertificateException {
    if (!sslCertFile.exists())
        throw new FileNotFoundException("The SSL Certificate '" + FileFunc.relPath(sslCertFile)
                + "' (aka. SSL Cert) file does not exist");

    if (!sslKeyFile.exists())
        throw new FileNotFoundException(
                "The SSL Key '" + FileFunc.relPath(sslKeyFile) + "' (aka. SSL Key) file does not exist");

    this.sslCertFile = sslCertFile;
    this.sslKeyFile = sslKeyFile;
    this.sslSecret = sslSecret;

    CertificateFactory cf;//from  w  w  w.  j  av  a 2 s . c om
    try {
        cf = CertificateFactory.getInstance("X.509");
    } catch (CertificateException e) {
        throw new IllegalStateException("Failed to initalize X.509 certificate factory.");
    }

    InputStream in = null;
    try {
        in = new FileInputStream(sslCertFile);
        cert = (X509Certificate) cf.generateCertificate(in);
    } finally {
        if (in != null)
            IOUtils.closeQuietly(in);
    }
}

From source file:com.easarrive.aws.plugins.common.util.SNSUtil.java

public static boolean isMessageSignatureValid(SNSMessage msg) {
    try {/*  w  w  w. ja va2s.co  m*/
        URL url = new URL(msg.getSigningCertURL());
        InputStream inStream = url.openStream();
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        X509Certificate cert = (X509Certificate) cf.generateCertificate(inStream);
        inStream.close();

        Signature sig = Signature.getInstance("SHA1withRSA");
        sig.initVerify(cert.getPublicKey());
        sig.update(getMessageBytesToSign(msg));
        return sig.verify(Base64.decodeBase64(msg.getSignature()));
    } catch (Exception e) {
        throw new SecurityException("Verify method failed.", e);
    }
}

From source file:org.authme.android.util.AuthMeHttpClient.java

private SSLSocketFactory newSslSocketFactory() {
    try {//from w  ww  .  j  av  a 2s .c om
        // Get an instance of the Bouncy Castle KeyStore format
        KeyStore trusted = KeyStore.getInstance("BKS");

        // Could probably load the main keystore and then append, but this works
        trusted.load(null, null);
        InputStream is = context.getResources().openRawResource(R.raw.cacert_root);
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X509");
        Certificate certificate = certificateFactory.generateCertificate(is);
        trusted.setCertificateEntry("CACertRoot", certificate);

        // Now continue on using this keystore

        SSLSocketFactory sf = new SSLSocketFactory(trusted);
        // Hostname verification from certificate
        // http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html#d4e506
        sf.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
        return sf;
    } catch (Exception e) {
        throw new AssertionError(e);
    }
}

From source file:com.sk89q.mclauncher.security.X509KeyStore.java

/**
 * Add root certificates from an input stream.
 * //w w w  . j a  v a 2 s .  co  m
 * @param in
 *            input
 * @throws CertificateException
 *             on error
 * @throws IOException
 *             on I/O error
 */
public void addRootCertificates(InputStream in) throws CertificateException, IOException {
    try {
        BufferedInputStream bufferedIn = new BufferedInputStream(in);
        CertificateFactory cf = CertificateFactory.getInstance("X.509");

        while (bufferedIn.available() > 0) {
            Certificate cert = cf.generateCertificate(bufferedIn);
            addRootCertificate((X509Certificate) cert);
        }
    } finally {
        IOUtils.closeQuietly(in);
    }
}

From source file:eu.europa.ec.markt.dss.validation.xades.XAdESCRLSource.java

@Override
public List<X509CRL> getCRLsFromSignature() {
    List<X509CRL> list = new ArrayList<X509CRL>();

    try {/*from  w  ww  . ja v a  2s  . c  om*/
        NodeList nodeList = (NodeList) XMLUtils.getNodeList(signatureElement, CRL_XPATH);
        for (int i = 0; i < nodeList.getLength(); i++) {
            Element certEl = (Element) nodeList.item(i);
            CertificateFactory factory = CertificateFactory.getInstance("X509");
            byte[] derEncoded = Base64.decodeBase64(certEl.getTextContent());
            X509CRL cert = (X509CRL) factory.generateCRL(new ByteArrayInputStream(derEncoded));
            list.add(cert);
        }
    } catch (CertificateException e) {
        throw new RuntimeException(e);
    } catch (CRLException e) {
        throw new RuntimeException(e);
    }

    return list;
}