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:com.google.android.apps.santatracker.presentquest.PlacesIntentService.java

@Nullable
private String getAppSignature() {
    // Cache this so we don't need to calculate the signature on every request
    if (mAppSignature != null) {
        return mAppSignature;
    }/* w ww.j av  a  2s  .co  m*/

    try {
        // Get signatures for the package
        Signature[] sigs = getPackageManager().getPackageInfo(getPackageName(),
                PackageManager.GET_SIGNATURES).signatures;

        // There should only be one signature, anything else is suspicious
        if (sigs == null || sigs.length > 1 || sigs.length == 0) {
            Log.w(TAG, "Either 0 or >1 signatures, returning null");
            return null;
        }

        byte[] certBytes = sigs[0].toByteArray();

        InputStream input = new ByteArrayInputStream(certBytes);
        CertificateFactory cf = CertificateFactory.getInstance("X509");
        X509Certificate cert = (X509Certificate) cf.generateCertificate(input);

        MessageDigest md = MessageDigest.getInstance("SHA1");
        byte[] publicKey = md.digest(cert.getEncoded());

        // Build a hex string of the SHA1 Digest
        StringBuilder hexString = new StringBuilder();
        for (byte aPublicKey : publicKey) {
            // Convert each byte to hex
            String appendString = Integer.toHexString(0xFF & aPublicKey);
            if (appendString.length() == 1) {
                hexString.append("0");
            }

            // Convert to upper case and add ":" separators so it matches keytool output
            appendString = appendString.toUpperCase() + ":";

            hexString.append(appendString);
        }

        // Convert to string, chop off trailing colon
        String signature = hexString.toString();
        if (signature.endsWith(":")) {
            signature = signature.substring(0, signature.length() - 1);
        }

        // Set and return
        mAppSignature = signature;
        return mAppSignature;
    } catch (Exception e) {
        Log.e(TAG, "getSignature", e);
    }

    return null;
}

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

public List<X509Certificate> toSignChain() throws CertificateException {
    CertificateFactory certificateFactory = null;
    X509Certificate rootCert = null;
    X509Certificate citizenCert = null;
    X509Certificate signingCert = null;
    List<X509Certificate> signChain = null;

    if (getRootCertificate() == null || getCitizenCACertificate() == null || getSigningCertificate() == null)
        return null;

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

    rootCert = (X509Certificate) certificateFactory.generateCertificate(
            new ByteArrayInputStream(Base64.decodeBase64(getRootCertificate().getBytes())));
    citizenCert = (X509Certificate) certificateFactory.generateCertificate(
            new ByteArrayInputStream(Base64.decodeBase64(getCitizenCACertificate().getBytes())));
    signingCert = (X509Certificate) certificateFactory.generateCertificate(
            new ByteArrayInputStream(Base64.decodeBase64(getSigningCertificate().getBytes())));

    signChain = new LinkedList<X509Certificate>();
    signChain.add(signingCert);/*from  ww w . j a va 2s  .  c  o m*/
    signChain.add(citizenCert);
    signChain.add(rootCert);

    return signChain;
}

From source file:io.fabric8.kubernetes.api.KubernetesFactory.java

private void configureCaCert(WebClient webClient) {
    try (InputStream pemInputStream = getInputStreamFromDataOrFile(caCertData, caCertFile)) {
        CertificateFactory certFactory = CertificateFactory.getInstance("X509");
        X509Certificate cert = (X509Certificate) certFactory.generateCertificate(pemInputStream);

        KeyStore trustStore = KeyStore.getInstance("JKS");
        trustStore.load(null);/* w  w w.  j  av  a  2  s .  com*/

        String alias = cert.getSubjectX500Principal().getName();
        trustStore.setCertificateEntry(alias, cert);

        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(trustStore);

        HTTPConduit conduit = WebClient.getConfig(webClient).getHttpConduit();

        TLSClientParameters params = conduit.getTlsClientParameters();

        if (params == null) {
            params = new TLSClientParameters();
            conduit.setTlsClientParameters(params);
        }

        TrustManager[] existingTrustManagers = params.getTrustManagers();
        TrustManager[] trustManagers;

        if (existingTrustManagers == null || ArrayUtils.isEmpty(existingTrustManagers)) {
            trustManagers = trustManagerFactory.getTrustManagers();
        } else {
            trustManagers = (TrustManager[]) ArrayUtils.addAll(existingTrustManagers,
                    trustManagerFactory.getTrustManagers());
        }

        params.setTrustManagers(trustManagers);

    } catch (Exception e) {
        log.error("Could not create trust manager for " + caCertFile, e);
    }
}

From source file:org.eclipse.emf.emfstore.internal.client.model.connectionmanager.KeyStoreManager.java

/**
 * {@inheritDoc}//from   w  w  w.j av a  2s.co m
 * 
 * @see org.eclipse.emf.emfstore.client.provider.ESKeyStoreManager#addCertificate(java.lang.String,
 *      java.io.InputStream)
 */
public void addCertificate(String alias, InputStream certificate) throws ESCertificateException {
    if (!isDefaultCertificate(alias)) {
        loadKeyStore();
        try {
            final CertificateFactory factory = CertificateFactory.getInstance(CERTIFICATE_TYPE);
            final Certificate newCertificate = factory.generateCertificate(certificate);
            keyStore.setCertificateEntry(alias, newCertificate);
            storeKeyStore();
        } catch (final CertificateException e) {
            final String message = Messages.KeyStoreManager_Choose_Valid_Certificate;
            throw new ESCertificateException(message);
        } catch (final KeyStoreException e) {
            final String message = "Storing certificate failed!"; //$NON-NLS-1$
            WorkspaceUtil.logException(message, e);
            throw new ESCertificateException(message, e);
        }
    }
}

From source file:org.kaazing.maven.plugins.TrustStoreMojo.java

KeyStore getTrustStore(Map<String, String> certs, String storeType) throws Exception {

    KeyStore ks = KeyStore.getInstance(storeType);

    // Initialize an empty keystore
    ks.load(null, null);/*w ww  . j av  a 2 s . c  o m*/

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

    for (Map.Entry<String, String> elt : certs.entrySet()) {
        String alias = elt.getKey();

        try {
            ByteArrayInputStream bais = new ByteArrayInputStream(elt.getValue().getBytes(UTF8));

            X509Certificate cert = (X509Certificate) certFactory.generateCertificate(bais);
            cert.checkValidity();

            getLog().info(String.format("Adding certificate with alias '%s'", alias));
            ks.setCertificateEntry(alias, cert);

        } catch (CertificateExpiredException cee) {
            getLog().error(String.format("NOT Adding certificate %s: %s", alias, cee));

        } catch (CertificateNotYetValidException cnyve) {
            getLog().error(String.format("NOT Adding certificate %s: %s", alias, cnyve));
        }
    }

    return ks;
}

From source file:io.fabric8.kubernetes.api.KubernetesFactory.java

private void configureClientCert(WebClient webClient) {
    try (InputStream certInputStream = getInputStreamFromDataOrFile(clientCertData, clientCertFile)) {
        CertificateFactory certFactory = CertificateFactory.getInstance("X509");
        X509Certificate cert = (X509Certificate) certFactory.generateCertificate(certInputStream);

        InputStream keyInputStream = getInputStreamFromDataOrFile(clientKeyData, clientKeyFile);
        PEMReader reader = new PEMReader(keyInputStream);
        RSAPrivateCrtKeySpec keySpec = new PKCS1EncodedKeySpec(reader.getDerBytes()).getKeySpec();
        KeyFactory kf = KeyFactory.getInstance(clientKeyAlgo);
        RSAPrivateKey privKey = (RSAPrivateKey) kf.generatePrivate(keySpec);

        KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(null);//  w ww .ja va 2s  . c  o  m

        String alias = cert.getSubjectX500Principal().getName();
        keyStore.setKeyEntry(alias, privKey, clientKeyPassword, new Certificate[] { cert });

        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, clientKeyPassword);

        HTTPConduit conduit = WebClient.getConfig(webClient).getHttpConduit();

        TLSClientParameters params = conduit.getTlsClientParameters();

        if (params == null) {
            params = new TLSClientParameters();
            conduit.setTlsClientParameters(params);
        }

        KeyManager[] existingKeyManagers = params.getKeyManagers();
        KeyManager[] keyManagers;

        if (existingKeyManagers == null || ArrayUtils.isEmpty(existingKeyManagers)) {
            keyManagers = keyManagerFactory.getKeyManagers();
        } else {
            keyManagers = (KeyManager[]) ArrayUtils.addAll(existingKeyManagers,
                    keyManagerFactory.getKeyManagers());
        }

        params.setKeyManagers(keyManagers);

    } catch (Exception e) {
        log.error("Could not create key manager for " + clientCertFile + " (" + clientKeyFile + ")", e);
    }
}

From source file:IntergrationTest.OCSPIntegrationTest.java

/**
 * Read PEM certificate into javax.security.x509Certificate.
 *
 * @param pemCert//w w w . j  a  v  a 2 s.c o  m
 *
 * @return
 */
private X509Certificate readPemCert(byte[] pemCert) {
    CertificateFactory certificateFactory = null;
    try {
        certificateFactory = CertificateFactory.getInstance("X.509");
    } catch (CertificateException e) {
        e.printStackTrace();
    }
    X509Certificate x509cert;
    InputStream stream = new ByteArrayInputStream(pemCert);
    try {
        x509cert = (X509Certificate) certificateFactory.generateCertificate(stream);
        return x509cert;
    } catch (CertificateException e) {
        e.printStackTrace();
        return null;
    }
}

From source file:com.blackducksoftware.integration.hub.jenkins.site.BlackDuckHubUpdateSite.java

/**
 * Verifies the signature in the update center data file.
 *///from  w w  w .  j  a  v  a2  s  .c  om
private FormValidation verifySignature(final JSONObject o) throws IOException {
    try {
        FormValidation warning = null;

        final JSONObject signature = o.getJSONObject("signature");
        if (signature.isNullObject()) {
            return FormValidation.error("No signature block found in update center '" + getId() + "'");
        }
        o.remove("signature");

        final List<X509Certificate> certs = new ArrayList<X509Certificate>();
        {// load and verify certificates
            final CertificateFactory cf = CertificateFactory.getInstance("X509");
            for (final Object cert : signature.getJSONArray("certificates")) {
                final X509Certificate c = (X509Certificate) cf.generateCertificate(
                        new ByteArrayInputStream(Base64.decode(cert.toString().toCharArray())));
                try {
                    c.checkValidity();
                } catch (final CertificateExpiredException e) { // even if the certificate isn't valid yet,
                    // we'll proceed it anyway
                    warning = FormValidation.warning(e, String.format(
                            "Certificate %s has expired in update center '%s'", cert.toString(), getId()));
                } catch (final CertificateNotYetValidException e) {
                    warning = FormValidation.warning(e, String.format(
                            "Certificate %s is not yet valid in update center '%s'", cert.toString(), getId()));
                }
                certs.add(c);
            }

            // all default root CAs in JVM are trusted, plus certs bundled in Jenkins
            final Set<TrustAnchor> anchors = new HashSet<TrustAnchor>(); // CertificateUtil.getDefaultRootCAs();
            final ServletContext context = Jenkins.getInstance().servletContext;
            anchors.add(new TrustAnchor(loadLicenseCaCertificate(), null));
            for (final String cert : (Set<String>) context.getResourcePaths("/WEB-INF/update-center-rootCAs")) {
                if (cert.endsWith(".txt")) {
                    continue; // skip text files that are meant to be documentation
                }
                final InputStream stream = context.getResourceAsStream(cert);
                if (stream != null) {
                    try {
                        anchors.add(new TrustAnchor((X509Certificate) cf.generateCertificate(stream), null));
                    } finally {
                        IOUtils.closeQuietly(stream);
                    }
                }
            }
            CertificateUtil.validatePath(certs, anchors);
        }

        // this is for computing a digest to check sanity
        final MessageDigest sha1 = MessageDigest.getInstance("SHA1");
        final DigestOutputStream dos = new DigestOutputStream(new NullOutputStream(), sha1);

        // this is for computing a signature
        final Signature sig = Signature.getInstance("SHA1withRSA");
        sig.initVerify(certs.get(0));
        final SignatureOutputStream sos = new SignatureOutputStream(sig);

        // until JENKINS-11110 fix, UC used to serve invalid digest (and therefore unverifiable signature)
        // that only covers the earlier portion of the file. This was caused by the lack of close() call
        // in the canonical writing, which apparently leave some bytes somewhere that's not flushed to
        // the digest output stream. This affects Jenkins [1.424,1,431].
        // Jenkins 1.432 shipped with the "fix" (1eb0c64abb3794edce29cbb1de50c93fa03a8229) that made it
        // compute the correct digest, but it breaks all the existing UC json metadata out there. We then
        // quickly discovered ourselves in the catch-22 situation. If we generate UC with the correct signature,
        // it'll cut off [1.424,1.431] from the UC. But if we don't, we'll cut off [1.432,*).
        //
        // In 1.433, we revisited 1eb0c64abb3794edce29cbb1de50c93fa03a8229 so that the original "digest"/"signature"
        // pair continues to be generated in a buggy form, while "correct_digest"/"correct_signature" are generated
        // correctly.
        //
        // Jenkins should ignore "digest"/"signature" pair. Accepting it creates a vulnerability that allows
        // the attacker to inject a fragment at the end of the json.
        o.writeCanonical(new OutputStreamWriter(new TeeOutputStream(dos, sos), "UTF-8")).close();

        // did the digest match? this is not a part of the signature validation, but if we have a bug in the c14n
        // (which is more likely than someone tampering with update center), we can tell
        final String computedDigest = new String(Base64.encode(sha1.digest()));
        final String providedDigest = signature.optString("correct_digest");
        if (providedDigest == null) {
            return FormValidation.error("No correct_digest parameter in update center '" + getId()
                    + "'. This metadata appears to be old.");
        }
        if (!computedDigest.equalsIgnoreCase(providedDigest)) {
            return FormValidation.error("Digest mismatch: " + computedDigest + " vs " + providedDigest
                    + " in update center '" + getId() + "'");
        }

        final String providedSignature = signature.getString("correct_signature");
        if (!sig.verify(Base64.decode(providedSignature.toCharArray()))) {
            return FormValidation.error(
                    "Signature in the update center doesn't match with the certificate in update center '"
                            + getId() + "'");
        }

        if (warning != null) {
            return warning;
        }
        return FormValidation.ok();
    } catch (final GeneralSecurityException e) {
        return FormValidation.error(e, "Signature verification failed in the update center '" + getId() + "'");
    }
}

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

public List<X509Certificate> toAuthChain() throws CertificateException {
    CertificateFactory certificateFactory = null;
    X509Certificate rootCert = null;
    X509Certificate citizenCert = null;
    X509Certificate authenticationCert = null;
    List<X509Certificate> authChain = null;

    if (getRootCertificate() == null || getCitizenCACertificate() == null
            || getAuthenticationCertificate() == null)
        return null;

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

    rootCert = (X509Certificate) certificateFactory.generateCertificate(
            new ByteArrayInputStream(Base64.decodeBase64(getRootCertificate().getBytes())));
    citizenCert = (X509Certificate) certificateFactory.generateCertificate(
            new ByteArrayInputStream(Base64.decodeBase64(getCitizenCACertificate().getBytes())));
    authenticationCert = (X509Certificate) certificateFactory.generateCertificate(
            new ByteArrayInputStream(Base64.decodeBase64(getAuthenticationCertificate().getBytes())));

    authChain = new LinkedList<X509Certificate>();
    authChain.add(authenticationCert);//ww  w  .  ja v  a 2  s.c om
    authChain.add(citizenCert);
    authChain.add(rootCert);

    return authChain;
}

From source file:org.wso2.carbon.apimgt.impl.utils.CertificateMgtUtils.java

/**
 * This method generates a certificate from a base64 encoded certificate string and add to the configured trust
 * store./*www .j a v a 2 s . co m*/
 *
 * @param base64Cert : The base 64 encoded string of the server certificate.
 * @param alias      : The alias for the certificate.
 * @return : ResponseCode which matches the execution result.
 *
 * Response Codes.
 * SUCCESS : If certificate added successfully.
 * INTERNAL_SERVER_ERROR : If any internal error occurred
 * ALIAS_EXISTS_IN_TRUST_STORE : If the alias exists in trust store.
 * CERTIFICATE_EXPIRED : If the given certificate is expired.
 */
public ResponseCode addCertificateToTrustStore(String base64Cert, String alias) {

    boolean isCertExists = false;
    boolean expired = false;
    InputStream serverCert = null;
    try {
        //Decode base64 encoded certificate.
        byte[] cert = (Base64.decodeBase64(base64Cert.getBytes(CHARSET_UTF_8)));
        serverCert = new ByteArrayInputStream(cert);
        if (serverCert.available() == 0) {
            log.error("Certificate is empty for the provided alias " + alias);
            return ResponseCode.INTERNAL_SERVER_ERROR;
        }

        //Read the client-truststore.jks into a KeyStore.
        File trustStoreFile = new File(TRUST_STORE);
        localTrustStoreStream = new FileInputStream(trustStoreFile);
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(localTrustStoreStream, TRUST_STORE_PASSWORD);

        CertificateFactory cf = CertificateFactory.getInstance(CERTIFICATE_TYPE);
        while (serverCert.available() > 0) {
            Certificate certificate = cf.generateCertificate(serverCert);
            //Check whether the Alias exists in the trust store.
            if (trustStore.containsAlias(alias)) {
                isCertExists = true;
            } else {
                /*
                * If alias is not exists, check whether the certificate is expired or not. If expired set the
                * expired flag.
                * */
                X509Certificate x509Certificate = (X509Certificate) certificate;
                if (x509Certificate.getNotAfter().getTime() <= System.currentTimeMillis()) {
                    expired = true;
                    if (log.isDebugEnabled()) {
                        log.debug("Provided certificate is expired.");
                    }
                } else {
                    //If not expired add the certificate to trust store.
                    trustStore.setCertificateEntry(alias, certificate);
                }
            }
        }
        fileOutputStream = new FileOutputStream(trustStoreFile);
        trustStore.store(fileOutputStream, TRUST_STORE_PASSWORD);
        responseCode = expired ? ResponseCode.CERTIFICATE_EXPIRED
                : isCertExists ? ResponseCode.ALIAS_EXISTS_IN_TRUST_STORE : ResponseCode.SUCCESS;
    } catch (CertificateException e) {
        log.error("Error loading certificate.", e);
        responseCode = ResponseCode.INTERNAL_SERVER_ERROR;
    } catch (FileNotFoundException e) {
        log.error("Error reading/ writing to the certificate file.", e);
        responseCode = ResponseCode.INTERNAL_SERVER_ERROR;
    } catch (NoSuchAlgorithmException e) {
        log.error("Could not find the algorithm to load the certificate.", e);
        responseCode = ResponseCode.INTERNAL_SERVER_ERROR;
    } catch (UnsupportedEncodingException e) {
        log.error("Error retrieving certificate from String", e);
        responseCode = ResponseCode.INTERNAL_SERVER_ERROR;
    } catch (KeyStoreException e) {
        log.error("Error reading certificate contents.", e);
        responseCode = ResponseCode.INTERNAL_SERVER_ERROR;
    } catch (IOException e) {
        log.error("Error in loading the certificate.", e);
        responseCode = ResponseCode.INTERNAL_SERVER_ERROR;
    } finally {
        closeStreams(localTrustStoreStream, fileOutputStream, serverCert);
    }
    return responseCode;
}