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: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;
    }//from  w ww  . j a v  a 2 s . c  o  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:org.apache.cloudstack.network.ssl.CertServiceImpl.java

private Certificate readCertificateFromPemObject(final PemObject pemObject) throws CertificateException {
    Preconditions.checkNotNull(pemObject);
    final ByteArrayInputStream bais = new ByteArrayInputStream(pemObject.getContent());
    final CertificateFactory certificateFactory = CertificateFactory.getInstance("X509");

    return certificateFactory.generateCertificate(bais);
}

From source file:org.apache.atlas.web.filters.AtlasKnoxSSOAuthenticationFilter.java

public static RSAPublicKey parseRSAPublicKey(String pem)
        throws CertificateException, UnsupportedEncodingException, ServletException {
    String PEM_HEADER = "-----BEGIN CERTIFICATE-----\n";
    String PEM_FOOTER = "\n-----END CERTIFICATE-----";
    String fullPem = PEM_HEADER + pem + PEM_FOOTER;
    PublicKey key = null;//from w ww.  j a v  a2  s.  co m
    try {
        CertificateFactory fact = CertificateFactory.getInstance("X.509");
        ByteArrayInputStream is = new ByteArrayInputStream(fullPem.getBytes("UTF8"));
        X509Certificate cer = (X509Certificate) fact.generateCertificate(is);
        key = cer.getPublicKey();
    } catch (CertificateException ce) {
        String message = null;
        if (pem.startsWith(PEM_HEADER)) {
            message = "CertificateException - be sure not to include PEM header "
                    + "and footer in the PEM configuration element.";
        } else {
            message = "CertificateException - PEM may be corrupt";
        }
        throw new ServletException(message, ce);
    } catch (UnsupportedEncodingException uee) {
        throw new ServletException(uee);
    }
    return (RSAPublicKey) key;
}

From source file:com.cws.esolutions.security.dao.certmgmt.impl.CertificateManagerImpl.java

/**
 * @see com.cws.esolutions.security.dao.certmgmt.interfaces.ICertificateManager#applyCertificateRequest(String, File, File, String)
 *//* w  w  w.ja  va  2  s .c om*/
public synchronized boolean applyCertificateRequest(final String commonName, final File certificateFile,
        final File keystoreFile, final String storePassword) throws CertificateManagementException {
    final String methodName = ICertificateManager.CNAME
            + "#applyCertificateRequest(final String commonName, final File certificateFile, final File keystoreFile, final String storePassword) throws CertificateManagementException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", commonName);
        DEBUGGER.debug("Value: {}", certificateFile);
        DEBUGGER.debug("Value: {}", keystoreFile);
    }

    final File rootDirectory = certConfig.getRootDirectory();
    final File certificateDirectory = FileUtils
            .getFile(certConfig.getCertificateDirectory() + "/" + commonName);
    final File storeDirectory = FileUtils.getFile(certConfig.getStoreDirectory() + "/" + commonName);

    if (DEBUG) {
        DEBUGGER.debug("rootDirectory: {}", rootDirectory);
        DEBUGGER.debug("certificateDirectory: {}", certificateDirectory);
        DEBUGGER.debug("storeDirectory: {}", storeDirectory);
        DEBUGGER.debug("certificateFile: {}", certificateFile);
        DEBUGGER.debug("keystoreFile: {}", keystoreFile);
    }

    boolean isComplete = false;
    FileInputStream certStream = null;
    FileOutputStream storeStream = null;
    FileInputStream keystoreInput = null;
    FileInputStream rootCertStream = null;
    FileInputStream intermediateCertStream = null;

    try {
        if (!(rootDirectory.exists())) {
            throw new CertificateManagementException(
                    "Root certificate directory either does not exist or cannot be written to. Cannot continue.");
        }

        if (!(rootDirectory.canWrite())) {
            throw new CertificateManagementException(
                    "Root certificate directory either does not exist or cannot be written to. Cannot continue.");
        }

        if (!(certConfig.getRootCertificateFile().exists())) {
            throw new CertificateManagementException("Root certificate file does not exist. Cannot continue.");
        }

        if (!(certConfig.getIntermediateCertificateFile().exists())) {
            throw new CertificateManagementException(
                    "Intermediate certificate file does not exist. Cannot continue.");
        }

        if (!(storeDirectory.canWrite())) {
            throw new CertificateManagementException(
                    "Keystore directory either does not exist or cannot be written to. Cannot continue.");
        }

        if (!(keystoreFile.canWrite())) {
            throw new CertificateManagementException(
                    "Unable to write to applicable keystore. Cannot continue.");
        }

        keystoreInput = FileUtils.openInputStream(keystoreFile);
        certStream = FileUtils.openInputStream(certificateFile);

        if (DEBUG) {
            DEBUGGER.debug("keystoreInput: {}", keystoreInput);
            DEBUGGER.debug("certStream: {}", certStream);
        }

        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(keystoreInput, storePassword.toCharArray());

        if (DEBUG) {
            DEBUGGER.debug("KeyStore: {}", keyStore);
        }

        Key privateKey = keyStore.getKey(commonName, storePassword.toCharArray());
        CertificateFactory certFactory = CertificateFactory.getInstance(certConfig.getCertificateType());

        if (DEBUG) {
            DEBUGGER.debug("CertificateFactory: {}", certFactory);
        }

        rootCertStream = FileUtils.openInputStream(FileUtils.getFile(certConfig.getRootCertificateFile()));
        intermediateCertStream = FileUtils
                .openInputStream(FileUtils.getFile(certConfig.getIntermediateCertificateFile()));

        if (DEBUG) {
            DEBUGGER.debug("rootCertStream: {}", rootCertStream);
            DEBUGGER.debug("intermediateCertStream: {}", intermediateCertStream);
        }

        X509Certificate[] responseCert = new X509Certificate[] {
                (X509Certificate) certFactory.generateCertificate(rootCertStream),
                (X509Certificate) certFactory.generateCertificate(intermediateCertStream),
                (X509Certificate) certFactory.generateCertificate(certStream) };

        if (DEBUG) {
            DEBUGGER.debug("X509Certificate[]", (Object) responseCert);
        }

        storeStream = FileUtils.openOutputStream(keystoreFile);
        keyStore.setKeyEntry(commonName, privateKey, storePassword.toCharArray(), responseCert);
        keyStore.store(storeStream, storePassword.toCharArray());

        isComplete = true;
    } catch (FileNotFoundException fnfx) {
        throw new CertificateManagementException(fnfx.getMessage(), fnfx);
    } catch (IOException iox) {
        throw new CertificateManagementException(iox.getMessage(), iox);
    } catch (NoSuchAlgorithmException nsax) {
        throw new CertificateManagementException(nsax.getMessage(), nsax);
    } catch (IllegalStateException isx) {
        throw new CertificateManagementException(isx.getMessage(), isx);
    } catch (KeyStoreException ksx) {
        throw new CertificateManagementException(ksx.getMessage(), ksx);
    } catch (CertificateException cx) {
        throw new CertificateManagementException(cx.getMessage(), cx);
    } catch (UnrecoverableKeyException ukx) {
        throw new CertificateManagementException(ukx.getMessage(), ukx);
    } finally {
        if (storeStream != null) {
            IOUtils.closeQuietly(storeStream);
        }

        if (intermediateCertStream != null) {
            IOUtils.closeQuietly(intermediateCertStream);
        }

        if (rootCertStream != null) {
            IOUtils.closeQuietly(rootCertStream);
        }

        if (certStream != null) {
            IOUtils.closeQuietly(certStream);
        }

        if (keystoreInput != null) {
            IOUtils.closeQuietly(keystoreInput);
        }
    }

    return isComplete;
}

From source file:com.arm.connector.bridge.core.Utils.java

static public X509Certificate createX509CertificateFromPEM(ErrorLogger logger, String pem, String cert_type) {
    try {//from  w w w  . ja v  a2 s.  c o  m
        String temp = Utils.escapeChars(pem);
        String certPEM = temp.replace("-----BEGIN CERTIFICATE-----", "");
        certPEM = certPEM.replace("-----END CERTIFICATE-----", "");

        // DEBUG
        //logger.info("createX509CertificateFromPEM: " + certPEM);

        Base64 b64 = new Base64();
        byte[] decoded = b64.decode(certPEM);

        CertificateFactory cf = CertificateFactory.getInstance(cert_type);
        return (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(decoded));
    } catch (Exception ex) {
        // exception caught
        logger.warning("createX509CertificateFromPEM: Exception during private key gen", ex);
    }
    return null;
}

From source file:org.eclipse.smarthome.binding.digitalstrom.internal.lib.serverconnection.impl.HttpTransportImpl.java

@Override
public String writePEMCertFile(String path) {
    String correctedPath = StringUtils.trimToEmpty(path);
    File certFilePath;//from ww  w.j a  v  a  2 s.  c  om
    if (StringUtils.isNotBlank(correctedPath)) {
        certFilePath = new File(correctedPath);
        boolean pathExists = certFilePath.exists();
        if (!pathExists) {
            pathExists = certFilePath.mkdirs();
        }
        if (pathExists && !correctedPath.endsWith("/")) {
            correctedPath = correctedPath + "/";
        }
    }
    InputStream certInputStream = IOUtils.toInputStream(cert);
    X509Certificate trustedCert;
    try {
        trustedCert = (X509Certificate) CertificateFactory.getInstance("X.509")
                .generateCertificate(certInputStream);

        certFilePath = new File(
                correctedPath + trustedCert.getSubjectDN().getName().split(",")[0].substring(2) + ".crt");
        if (!certFilePath.exists()) {
            certFilePath.createNewFile();
            FileWriter writer = new FileWriter(certFilePath, true);
            writer.write(cert);
            writer.flush();
            writer.close();
            return certFilePath.getAbsolutePath();
        } else {
            logger.error("File allready exists!");
        }
    } catch (IOException e) {
        logger.error("An IOException occurred: ", e);
    } catch (CertificateException e1) {
        logger.error("A CertificateException occurred: ", e1);
    }
    return null;
}

From source file:org.codice.ddf.security.filter.login.LoginFilter.java

private void validateHolderOfKeyConfirmation(SamlAssertionWrapper assertion, X509Certificate[] x509Certs)
        throws SecurityServiceException {
    List<String> confirmationMethods = assertion.getConfirmationMethods();
    boolean hasHokMethod = false;
    for (String method : confirmationMethods) {
        if (OpenSAMLUtil.isMethodHolderOfKey(method)) {
            hasHokMethod = true;/*from www  .j a  va 2s  .  co  m*/
        }
    }

    if (hasHokMethod) {
        if (x509Certs != null && x509Certs.length > 0) {
            List<SubjectConfirmation> subjectConfirmations = assertion.getSaml2().getSubject()
                    .getSubjectConfirmations();
            for (SubjectConfirmation subjectConfirmation : subjectConfirmations) {
                if (OpenSAMLUtil.isMethodHolderOfKey(subjectConfirmation.getMethod())) {
                    Element dom = subjectConfirmation.getSubjectConfirmationData().getDOM();
                    Node keyInfo = dom.getFirstChild();
                    Node x509Data = keyInfo.getFirstChild();
                    Node dataNode = x509Data.getFirstChild();
                    Node dataText = dataNode.getFirstChild();

                    X509Certificate tlsCertificate = x509Certs[0];
                    if (dataNode.getLocalName().equals("X509Certificate")) {
                        String textContent = dataText.getTextContent();
                        byte[] byteValue = Base64.getMimeDecoder().decode(textContent);
                        try {
                            CertificateFactory cf = CertificateFactory.getInstance("X.509");
                            X509Certificate cert = (X509Certificate) cf
                                    .generateCertificate(new ByteArrayInputStream(byteValue));
                            //check that the certificate is still valid
                            cert.checkValidity();

                            //HoK spec section 2.5:
                            //relying party MUST ensure that the certificate bound to the assertion matches the X.509 certificate in its possession.
                            //Matching is done by comparing the base64-decoded certificates, or the hash values of the base64-decoded certificates, byte-for-byte.
                            //if the certs aren't the same, verify
                            if (!tlsCertificate.equals(cert)) {
                                //verify that the cert was signed by the same private key as the TLS cert
                                cert.verify(tlsCertificate.getPublicKey());
                            }
                        } catch (CertificateException | NoSuchAlgorithmException | InvalidKeyException
                                | SignatureException | NoSuchProviderException e) {
                            throw new SecurityServiceException(
                                    "Unable to validate Holder of Key assertion with certificate.");
                        }

                    } else if (dataNode.getLocalName().equals("X509SubjectName")) {
                        String textContent = dataText.getTextContent();
                        //HoK spec section 2.5:
                        //relying party MUST ensure that the subject distinguished name (DN) bound to the assertion matches the DN bound to the X.509 certificate.
                        //If, however, the relying party does not trust the certificate issuer to issue such a DN, the attesting entity is not confirmed and the relying party SHOULD disregard the assertion.
                        if (!tlsCertificate.getSubjectDN().getName().equals(textContent)) {
                            throw new SecurityServiceException(
                                    "Unable to validate Holder of Key assertion with subject DN.");
                        }

                    } else if (dataNode.getLocalName().equals("X509IssuerSerial")) {
                        //we have no way to support this confirmation type so we have to throw an error
                        throw new SecurityServiceException(
                                "Unable to validate Holder of Key assertion with issuer serial. NOT SUPPORTED");
                    } else if (dataNode.getLocalName().equals("X509SKI")) {
                        String textContent = dataText.getTextContent();
                        byte[] tlsSKI = tlsCertificate.getExtensionValue("2.5.29.14");
                        byte[] assertionSKI = Base64.getMimeDecoder().decode(textContent);
                        if (tlsSKI != null && tlsSKI.length > 0) {
                            ASN1OctetString tlsOs = ASN1OctetString.getInstance(tlsSKI);
                            ASN1OctetString assertionOs = ASN1OctetString.getInstance(assertionSKI);
                            SubjectKeyIdentifier tlsSubjectKeyIdentifier = SubjectKeyIdentifier
                                    .getInstance(tlsOs.getOctets());
                            SubjectKeyIdentifier assertSubjectKeyIdentifier = SubjectKeyIdentifier
                                    .getInstance(assertionOs.getOctets());
                            //HoK spec section 2.5:
                            //relying party MUST ensure that the value bound to the assertion matches the Subject Key Identifier (SKI) extension bound to the X.509 certificate.
                            //Matching is done by comparing the base64-decoded SKI values byte-for-byte. If the X.509 certificate does not contain an SKI extension,
                            //the attesting entity is not confirmed and the relying party SHOULD disregard the assertion.
                            if (!Arrays.equals(tlsSubjectKeyIdentifier.getKeyIdentifier(),
                                    assertSubjectKeyIdentifier.getKeyIdentifier())) {
                                throw new SecurityServiceException(
                                        "Unable to validate Holder of Key assertion with subject key identifier.");
                            }
                        } else {
                            throw new SecurityServiceException(
                                    "Unable to validate Holder of Key assertion with subject key identifier.");
                        }
                    }
                }
            }
        } else {
            throw new SecurityServiceException("Holder of Key assertion, must be used with 2-way TLS.");
        }
    }
}

From source file:org.eclipse.smarthome.binding.digitalstrom.internal.lib.serverconnection.impl.HttpTransportImpl.java

private SSLSocketFactory generateSSLContextFromPEMCertString(String pemCert) {
    if (StringUtils.isNotBlank(pemCert) && pemCert.startsWith(BEGIN_CERT)) {
        try {/*  w  w w.j av  a2s . c  o m*/
            InputStream certInputStream = IOUtils.toInputStream(pemCert);
            final X509Certificate trustedCert = (X509Certificate) CertificateFactory.getInstance("X.509")
                    .generateCertificate(certInputStream);

            final TrustManager[] trustManager = new TrustManager[] { new X509TrustManager() {

                @Override
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                @Override
                public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType)
                        throws CertificateException {
                    if (!certs[0].equals(trustedCert)) {
                        throw new CertificateException();
                    }
                }

                @Override
                public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType)
                        throws CertificateException {
                    if (!certs[0].equals(trustedCert)) {
                        throw new CertificateException();
                    }
                }
            } };

            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustManager, new java.security.SecureRandom());
            return sslContext.getSocketFactory();
        } catch (NoSuchAlgorithmException e) {
            logger.error("A NoSuchAlgorithmException occurred: ", e);
        } catch (KeyManagementException e) {
            logger.error("A KeyManagementException occurred: ", e);
        } catch (CertificateException e) {
            logger.error("A CertificateException occurred: ", e);
        }
    } else {
        logger.error("Cert is empty");
    }
    return null;
}

From source file:com.vmware.bdd.manager.SoftwareManagerCollector.java

/**
 * TODO this method has to be reverted:// ww w  .j a  v  a 2  s.  co m
 * because if the target path is not accessible, it will load cert from the default keystore in java home,
 * but still try to write it to the non accessible path.
 * @param certificate
 * @param keyStorePath
 */
protected static void saveSslCertificate(String certificate, String keyStorePath) {
    Certificate[] certs;
    //parse certificates
    try {
        if (CommonUtil.isBlank(certificate)) {
            throw SoftwareManagerCollectorException.BAD_CERT(null);
        }

        byte[] certBytes = Base64.decodeBase64(certificate.replaceAll("-----BEGIN CERTIFICATE-----", "")
                .replaceAll("-----END CERTIFICATE-----", "").getBytes());

        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        Collection c = cf.generateCertificates(new ByteArrayInputStream(certBytes));
        certs = new Certificate[c.toArray().length];

        if (c.size() == 0) {
            throw SoftwareManagerCollectorException.BAD_CERT(null);
        } else if (c.size() == 1) {
            certs[0] = cf.generateCertificate(new ByteArrayInputStream(certBytes));
        } else {
            certs = (Certificate[]) c.toArray(certs);
        }
    } catch (CertificateException e) {
        throw SoftwareManagerCollectorException.BAD_CERT(e);
    }

    //load & save keystore
    OutputStream out = null;
    try {
        KeyStore keyStore = CommonUtil.loadAppMgrKeyStore(keyStorePath);
        if (keyStore == null) {
            logger.error(Messages.getString("SW_MGR_COLLECTOR.CANNT_READ_KEYSTORE"));
            throw new SWMgrCollectorInternalException(
                    Messages.getString("SW_MGR_COLLECTOR.CANNT_READ_KEYSTORE"));
        }

        MessageDigest md5 = MessageDigest.getInstance("MD5");
        String md5Fingerprint = "";
        for (Certificate cert : certs) {
            md5.update(cert.getEncoded());
            md5Fingerprint = CommonUtil.toHexString(md5.digest());
            logger.debug("md5 finger print: " + md5Fingerprint);
            logger.debug("added cert: " + cert);
            keyStore.setCertificateEntry(md5Fingerprint, cert);
        }
        out = new FileOutputStream(keyStorePath + Constants.APPMANAGER_KEYSTORE_FILE);
        keyStore.store(new BufferedOutputStream(out), Constants.APPMANAGER_KEYSTORE_PASSWORD);
    } catch (CertificateException | NoSuchAlgorithmException | IOException | KeyStoreException e) {
        logger.error(Messages.getString("SW_MGR_COLLECTOR.FAIL_SAVE_CERT"), e);
        throw new SWMgrCollectorInternalException(e, Messages.getString("SW_MGR_COLLECTOR.FAIL_SAVE_CERT"));
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                logger.warn("Output stream of appmanagers.jks close failed.");
            }
        }
    }
}

From source file:edu.uiuc.ncsa.myproxy.MyProxyLogon.java

public void getCredentials(byte[] derEncodedCertRequest) throws IOException, GeneralSecurityException {
    try {//from   w  ww.  j  a va  2 s  . c  o  m

        if (this.state != State.LOGGEDON) {
            this.logon();
        }

        this.socketOut.write(derEncodedCertRequest);
        this.socketOut.flush();
        int numCertificates = this.socketIn.read();
        if (numCertificates == -1) {
            System.err.println("connection aborted");
            throw new IOException("Error: connection aborted");
        } else if (numCertificates == 0 || numCertificates < 0) {
            System.err.print("bad number of certificates sent by server: ");
            System.err.println(Integer.toString(numCertificates));
            throw new GeneralSecurityException("Error: bad number of certificates sent by server");
        }
        CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
        this.certificateChain = (Collection<X509Certificate>) certFactory.generateCertificates(this.socketIn);
        this.state = State.DONE;
    } catch (Throwable t) {
        handleException(t, getClass().getSimpleName() + " failure getting the credential.");
    }
}