public void checkCertTrusted(X509Certificate[] chain, String authType, boolean isServer) throws CertificateException { Log.d(TAG, "checkCertTrusted(" + chain + ", " + authType + ", " + isServer + ")"); try { Log.d(TAG, "checkCertTrusted: trying appTrustManager"); if (isServer) appTrustManager.checkServerTrusted(chain, authType); else appTrustManager.checkClientTrusted(chain, authType); } catch (CertificateException ae) { // if the cert is stored in our appTrustManager, we ignore expiredness ae.printStackTrace(); if (isExpiredException(ae)) { Log.i(TAG, "checkCertTrusted: accepting expired certificate from keystore"); return; } if (isCertKnown(chain[0])) { Log.i(TAG, "checkCertTrusted: accepting cert already stored in keystore"); return; } try { Log.d(TAG, "checkCertTrusted: trying defaultTrustManager"); if (isServer) defaultTrustManager.checkServerTrusted(chain, authType); else defaultTrustManager.checkClientTrusted(chain, authType); } catch (CertificateException e) { e.printStackTrace(); interact(chain, authType, e); } } }
/** * Validate the server's certificate chain is trusted. * * @param certChain The ASN.1 DER encoded bytes for certificates. * @param authType The key exchange algorithm name (e.g. RSA) * @return true if the server is trusted * @throws CertificateException,KeyStoreException,NoSuchAlgorithmException on error initializing * the TrustManager or reading the certChain */ @CalledByNativeUnchecked public static boolean verifyServerCertificates(byte[][] certChain, String authType) throws CertificateException, KeyStoreException, NoSuchAlgorithmException { if (certChain == null || certChain.length == 0 || certChain[0] == null) { throw new IllegalArgumentException( "Expected non-null and non-empty certificate " + "chain passed as |certChain|. |certChain|=" + certChain); } ensureInitialized(); X509Certificate[] serverCertificates = new X509Certificate[certChain.length]; for (int i = 0; i < certChain.length; ++i) { serverCertificates[i] = (X509Certificate) sCertificateFactory.get().generateCertificate(new ByteArrayInputStream(certChain[i])); } try { sDefaultTrustManager.get().checkServerTrusted(serverCertificates, authType); return true; } catch (CertificateException e) { Log.i(TAG, "failed to validate the certificate chain, error: " + e.getMessage()); } return false; }
private searchMenuMgr() { try { KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); MySSLSocketFactory socketFactory = new MySSLSocketFactory(trustStore); socketFactory.setHostnameVerifier(MySSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); client = new AsyncHttpClient(); client.setSSLSocketFactory(socketFactory); client.setCookieStore(new PersistentCookieStore(Login_Main.getContext())); client.setTimeout(10000); } catch (KeyStoreException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (CertificateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (UnrecoverableKeyException e) { e.printStackTrace(); } }
private KeyManager[] prepareKeyManager(InputStream bksFile, String password) { try { if (bksFile == null || password == null) return null; KeyStore clientKeyStore = KeyStore.getInstance("BKS"); clientKeyStore.load(bksFile, password.toCharArray()); KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(clientKeyStore, password.toCharArray()); return keyManagerFactory.getKeyManagers(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnrecoverableKeyException e) { e.printStackTrace(); } catch (CertificateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return null; }
public void checkCertTrusted( X509Certificate[] chain, String authType, boolean isServer, boolean interactive) throws CertificateException { LOGGER.log(Level.FINE, "checkCertTrusted(" + chain + ", " + authType + ", " + isServer + ")"); try { LOGGER.log(Level.FINE, "checkCertTrusted: trying appTrustManager"); if (isServer) appTrustManager.checkServerTrusted(chain, authType); else appTrustManager.checkClientTrusted(chain, authType); } catch (CertificateException ae) { LOGGER.log(Level.FINER, "checkCertTrusted: appTrustManager failed", ae); // if the cert is stored in our appTrustManager, we ignore expiredness if (isExpiredException(ae)) { LOGGER.log(Level.INFO, "checkCertTrusted: accepting expired certificate from keystore"); return; } if (isCertKnown(chain[0])) { LOGGER.log(Level.INFO, "checkCertTrusted: accepting cert already stored in keystore"); return; } try { if (defaultTrustManager == null) throw ae; LOGGER.log(Level.FINE, "checkCertTrusted: trying defaultTrustManager"); if (isServer) defaultTrustManager.checkServerTrusted(chain, authType); else defaultTrustManager.checkClientTrusted(chain, authType); } catch (CertificateException e) { e.printStackTrace(); if (interactive) { interactCert(chain, authType, e); } else { throw e; } } } }
/** * ִ��http���á�true:�ɹ� false:ʧ�� * * @return boolean */ public boolean call() { boolean isRet = false; // http if (null == this.caFile && null == this.certFile) { try { this.callHttp(); isRet = true; } catch (IOException e) { this.errInfo = e.getMessage(); } return isRet; } // https try { this.callHttps(); isRet = true; } catch (UnrecoverableKeyException e) { this.errInfo = e.getMessage(); } catch (KeyManagementException e) { this.errInfo = e.getMessage(); } catch (CertificateException e) { this.errInfo = e.getMessage(); } catch (KeyStoreException e) { this.errInfo = e.getMessage(); } catch (NoSuchAlgorithmException e) { this.errInfo = e.getMessage(); } catch (IOException e) { this.errInfo = e.getMessage(); } return isRet; }
public void checkServerTrusted(X509Certificate[] certs, String authType) throws CertificateException { // verify the cert chain verify(certs, authType); final TrustEngine[] engines = getTrustEngines(); Certificate foundCert = null; for (int i = 0; i < engines.length; i++) { try { foundCert = engines[i].findTrustAnchor(certs); if (null != foundCert) return; // cert chain is trust } catch (final IOException e) { final CertificateException ce = new ECFCertificateException( "Error occurs when finding trust anchor in the cert chain", certs, authType); //$NON-NLS-1$ ce.initCause(ce); throw ce; } } if (null == foundCert) throw new ECFCertificateException( "Valid cert chain, but no trust certificate found!", certs, authType); // $NON-NLS-1$ }
private static SSLSocketFactory getSocketFactory(Boolean d) { // Enable debug mode to ignore all certificates if (DEBUG) { KeyStore trustStore; try { trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); SSLSocketFactory sf = new DebugSSLSocketFactory(trustStore); sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); return sf; } catch (KeyStoreException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } catch (NoSuchAlgorithmException e3) { // TODO Auto-generated catch block e3.printStackTrace(); } catch (CertificateException e3) { // TODO Auto-generated catch block e3.printStackTrace(); } catch (IOException e3) { // TODO Auto-generated catch block e3.printStackTrace(); } catch (KeyManagementException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } catch (UnrecoverableKeyException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } } return SSLSocketFactory.getSocketFactory(); }
private static Certificate loadCertificate(File f) { X509Certificate cert = null; Logger.I(TAG, "Loading SSL certificate from PEM file: " + f.getAbsolutePath()); try { byte[] fileBuf = fileToBytes(f); byte[] certBytes = parseDERFromPEM(fileBuf, "-----BEGIN CERTIFICATE-----", "-----END CERTIFICATE-----"); cert = generateCertificateFromDER(certBytes); Logger.I(TAG, "SSL certificate loaded successfully"); } catch (IOException e) { Logger.E( TAG, "Reading certificate file failed: " + e.getClass().getSimpleName() + ": " + e.getMessage()); } catch (CertificateException e) { Logger.E( TAG, "Certificate generation failed: " + e.getClass().getSimpleName() + ": " + e.getMessage()); } return cert; }
/** * Gets a KeyStore containing the Certificate * * @param cert InputStream of the Certificate * @return KeyStore */ public static KeyStore getKeystoreOfCA(InputStream cert) { // Load CAs from an InputStream InputStream caInput = null; Certificate ca = null; try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); caInput = new BufferedInputStream(cert); ca = cf.generateCertificate(caInput); } catch (CertificateException e1) { e1.printStackTrace(); } finally { try { if (caInput != null) { caInput.close(); } } catch (IOException e) { e.printStackTrace(); } } // Create a KeyStore containing our trusted CAs String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = null; try { keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); keyStore.setCertificateEntry("ca", ca); } catch (Exception e) { e.printStackTrace(); } return keyStore; }
/* * Delegate to the default trust manager. */ public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { try { pkixTrustManager.checkClientTrusted(chain, authType); } catch (CertificateException excep) { Logger.error(this.getClass(), excep.getMessage()); Logger.debug(this.getClass(), excep.getMessage(), excep); } }
static { CertificateFactory cf = null; try { cf = CertificateFactory.getInstance("X.509"); } catch (CertificateException ce) { ce.printStackTrace(System.out); } finally { CF = cf; } }
/* */ private void readObject(ObjectInputStream paramObjectInputStream) /* */ throws IOException, ClassNotFoundException /* */ { /* 553 */ Hashtable localHashtable = null; /* */ /* 555 */ paramObjectInputStream.defaultReadObject(); /* */ /* 557 */ if (this.type == null) { /* 558 */ throw new NullPointerException("type can't be null"); /* */ } /* */ /* 561 */ int i = paramObjectInputStream.readInt(); /* 562 */ if (i > 0) /* */ { /* 565 */ localHashtable = new Hashtable(3); /* 566 */ this.certs = new Certificate[i]; /* */ } /* */ /* 569 */ for (int j = 0; j < i; j++) /* */ { /* 572 */ String str = paramObjectInputStream.readUTF(); /* */ CertificateFactory localCertificateFactory; /* 573 */ if (localHashtable.containsKey(str)) /* */ { /* 575 */ localCertificateFactory = (CertificateFactory) localHashtable.get(str); /* */ } /* */ else { /* */ try { /* 579 */ localCertificateFactory = CertificateFactory.getInstance(str); /* */ } catch (CertificateException localCertificateException1) { /* 581 */ throw new ClassNotFoundException( "Certificate factory for " + str + " not found"); /* */ } /* */ /* 585 */ localHashtable.put(str, localCertificateFactory); /* */ } /* */ /* 588 */ byte[] arrayOfByte = null; /* */ try { /* 590 */ arrayOfByte = new byte[paramObjectInputStream.readInt()]; /* */ } catch (OutOfMemoryError localOutOfMemoryError) { /* 592 */ throw new IOException("Certificate too big"); /* */ } /* 594 */ paramObjectInputStream.readFully(arrayOfByte); /* 595 */ ByteArrayInputStream localByteArrayInputStream = new ByteArrayInputStream(arrayOfByte); /* */ try { /* 597 */ this.certs[j] = localCertificateFactory.generateCertificate(localByteArrayInputStream); /* */ } catch (CertificateException localCertificateException2) { /* 599 */ throw new IOException(localCertificateException2.getMessage()); /* */ } /* 601 */ localByteArrayInputStream.close(); /* */ } /* */ }
private Subject createSubject() throws IOException { try { Certificate[] chain = engine.getSession().getPeerCertificates(); CertPath certPath = cf.generateCertPath(asList(chain)); return new Subject(false, Collections.<Principal>emptySet(), singleton(certPath), emptySet()); } catch (SSLPeerUnverifiedException e) { throw new IOException("Failed to establish identity of SSL peer: " + e.getMessage(), e); } catch (CertificateException e) { throw new IOException("Certificate failure: " + e.getMessage(), e); } }
/** * Permanently accepts a certificate for the INCOMING or OUTGOING direction by adding it to the * local key store. * * @param certificate */ private void acceptCertificate(X509Certificate certificate) { try { mAccount.addCertificate(mDirection, certificate); } catch (CertificateException e) { showErrorDialog( R.string.account_setup_failed_dlg_certificate_message_fmt, e.getMessage() == null ? "" : e.getMessage()); } AccountSetupCheckSettings.actionCheckSettings( AccountSetupCheckSettings.this, mAccount, mDirection); }
private void testIt() { String https_url = requestURL; URL url; SSLSocketFactory socketFactory = null; try { try { socketFactory = createSSLContext().getSocketFactory(); } catch (UnrecoverableKeyException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (KeyManagementException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (KeyStoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (CertificateException e) { // TODO Auto-generated catch block e.printStackTrace(); } url = new URL(https_url); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setDoInput(true); // Allow Inputs conn.setDoOutput(true); // Allow Outputs conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("ENCTYPE", "multipart/form-data"); conn.setSSLSocketFactory(socketFactory); DataOutputStream dos = new DataOutputStream(conn.getOutputStream()); conn.addRequestProperty("app_id", app_id); conn.addRequestProperty("app_key", app_key); // dump all cert info // print_https_cert(con); // dump all the content print_content(conn); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
public static X509Certificate getCaCert() { try { CertificateFactory cf = CertificateFactory.getInstance("X509"); X509Certificate x509Cert = (X509Certificate) cf.generateCertificate(new FileInputStream(publicCert)); return x509Cert; } catch (CertificateException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } return null; }
private PKIXCertPathBuilderResult buildCertPath( boolean searchAllCertStores, List<List<Vertex>> adjList) throws CertPathBuilderException { // Init shared variables and build certification path pathCompleted = false; trustAnchor = null; finalPublicKey = null; policyTreeResult = null; LinkedList<X509Certificate> certPathList = new LinkedList<>(); try { buildForward(adjList, certPathList, searchAllCertStores); } catch (GeneralSecurityException | IOException e) { if (debug != null) { debug.println("SunCertPathBuilder.engineBuild() exception in " + "build"); e.printStackTrace(); } throw new SunCertPathBuilderException( "unable to find valid " + "certification path to requested target", e, new AdjacencyList(adjList)); } // construct SunCertPathBuilderResult try { if (pathCompleted) { if (debug != null) debug.println("SunCertPathBuilder.engineBuild() " + "pathCompleted"); // we must return a certpath which has the target // as the first cert in the certpath - i.e. reverse // the certPathList Collections.reverse(certPathList); return new SunCertPathBuilderResult( cf.generateCertPath(certPathList), trustAnchor, policyTreeResult, finalPublicKey, new AdjacencyList(adjList)); } } catch (CertificateException e) { if (debug != null) { debug.println("SunCertPathBuilder.engineBuild() exception " + "in wrap-up"); e.printStackTrace(); } throw new SunCertPathBuilderException( "unable to find valid " + "certification path to requested target", e, new AdjacencyList(adjList)); } return null; }
@Transient public X509Certificate getServerCertificate() { if (null == this.encodedServerCertificate) { return null; } try { CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); InputStream certificateStream = new ByteArrayInputStream(this.encodedServerCertificate); return (X509Certificate) certificateFactory.generateCertificate(certificateStream); } catch (CertificateException e) { throw new RuntimeException("cert factory error: " + e.getMessage()); } }
public static CertPathEntry decode(DataInputStream in) throws IOException { CertPathEntry entry = new CertPathEntry(); entry.properties.decode(in); entry.makeCreationDate(); int len = in.readInt(); MeteredInputStream in2 = new MeteredInputStream(in, len); try { CertificateFactory fact = CertificateFactory.getInstance("X.509"); entry.path = (Certificate[]) fact.generateCertificates(in2).toArray(new Certificate[0]); } catch (CertificateException ce) { throw new MalformedKeyringException(ce.toString()); } return entry; }
/** * Create a new X.509 certificate from the encoded data. The input data are expected to be the * ASN.1 DER encoding of the certificate. * * @param encoded The encoded certificate data. * @throws IOException If the certificate cannot be read, possibly from a formatting error. * @throws CertificateException If the data read is not an X.509 certificate. */ public X509CertificateImpl(InputStream encoded) throws CertificateException, IOException { super(); extensions = new HashMap(); try { parse(encoded); } catch (IOException ioe) { debug(ioe); throw ioe; } catch (Exception e) { debug(e); CertificateException ce = new CertificateException(e.getMessage()); ce.initCause(e); throw ce; } }
private void sslFileTransfer(String filename) { try { KeyStore trusted = KeyStore.getInstance("BKS"); // Get the raw resource, which contains the keystore with // your trusted certificates (root and any intermediate certs) InputStream in = context.getResources().openRawResource(tracker.springversion1.R.raw.mykeystore); trusted.load(in, "mysecret".toCharArray()); String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(trusted); // Create an SSLContext that uses our TrustManager SSLContext context = SSLContext.getInstance("TLS"); context.init(null, tmf.getTrustManagers(), null); URL url = new URL(host); HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection(); urlConnection.setSSLSocketFactory(context.getSocketFactory()); transfer(urlConnection, filename); // 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); // // Socket sslsocket = sf.createSocket(); // sslsocket.setKeepAlive(true); // // InetSocketAddress address = new InetSocketAddress(host, 443); // sslsocket.connect(address); // // OutputStream sout = sslsocket.getOutputStream(); } catch (KeyStoreException e) { Log.v("mark", "KeyStoreException:" + e.getMessage()); } catch (NoSuchAlgorithmException e) { Log.v("mark", "NoSuchAlgorithmException:" + e.getMessage()); } catch (CertificateException e) { Log.v("mark", "CertificateException:" + e.getMessage()); } catch (IOException e) { Log.v("mark", "IOException:" + e.getMessage()); } catch (KeyManagementException e) { Log.v("mark", "KeyManagementException:" + e.getMessage()); } }
private KeyStore getKeyStore() throws CertificateException, IOException { KeyStore ks = null; try { ks = KeyStore.getInstance("PKCS12"); ks.load(new FileInputStream(this.pathSignature), this.passSignature.toCharArray()); } catch (KeyStoreException e) { throw new IOException("Error: " + e.getMessage()); } catch (NoSuchAlgorithmException e) { throw new IOException("Error: " + e.getMessage()); } catch (CertificateException e) { throw new IOException("Error: " + e.getMessage()); } catch (IOException e) { throw new IOException("Error: " + e.getMessage()); } return ks; }
private Certificate[] readCertArray(StrictLineReader reader) throws IOException { int length = reader.readInt(); if (length == -1) { return null; } try { CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); Certificate[] result = new Certificate[length]; for (int i = 0; i < result.length; i++) { String line = reader.readLine(); byte[] bytes = Base64.decode(line, Base64.DEFAULT); result[i] = certificateFactory.generateCertificate(new ByteArrayInputStream(bytes)); } return result; } catch (CertificateException e) { throw new IOException(e.getMessage()); } }
private byte[] getCertFingerprint(X509Certificate cert) { MessageDigest md; byte[] fingerprint = null; try { md = MessageDigest.getInstance("SHA1"); md.update(cert.getEncoded()); fingerprint = md.digest(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (CertificateException e) { e.printStackTrace(); } return fingerprint; }
private List<Certificate> readCertificateList(BufferedSource source) throws IOException { int length = readInt(source); if (length == -1) return Collections.emptyList(); // OkHttp v1.2 used -1 to indicate null. try { CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); List<Certificate> result = new ArrayList<>(length); for (int i = 0; i < length; i++) { String line = source.readUtf8LineStrict(); Buffer bytes = new Buffer(); bytes.write(ByteString.decodeBase64(line)); result.add(certificateFactory.generateCertificate(bytes.inputStream())); } return result; } catch (CertificateException e) { throw new IOException(e.getMessage()); } }
/** * Get java.security.Kestore instance from JKS * * @return */ private KeyStore loadKeyStore() { File keySF = new File(keyStorePath); KeyStore keystore = null; try { FileInputStream is = new FileInputStream(keySF); keystore = KeyStore.getInstance(KeyStore.getDefaultType()); keystore.load(is, keyStorePassword.toCharArray()); } catch (KeyStoreException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (CertificateException e) { e.printStackTrace(); } return keystore; }
static void disableCertificateValidation(Context context, OkHttpClient.Builder builder) { try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); InputStream caInput = context.getResources().openRawResource(R.raw.ca); Certificate ca; try { ca = cf.generateCertificate(caInput); System.out.println("ca=" + ((X509Certificate) ca).getSubjectDN()); } finally { caInput.close(); } String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); keyStore.setCertificateEntry("ca", ca); String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keyStore); SSLContext sc = SSLContext.getInstance("TLS"); sc.init(null, tmf.getTrustManagers(), null); HostnameVerifier hv = new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } }; sc.init(null, tmf.getTrustManagers(), null); builder.sslSocketFactory(sc.getSocketFactory()); builder.hostnameVerifier(hv); } catch (CertificateException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
/** * Retrieves the Certificate Revocation List * * @return a String object * @throws CRLException if there is issue generating the CRL * @throws IOException if there is a problem serializing the CRL * @httpcode 200 */ @GET @Produces({MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN}) public String getCurrentCrl(@Context Principal principal) throws CRLException, IOException { String filePath = getCrlFilePath(); File crlFile = new File(filePath); byte[] encoded = null; try { X509CRL crl = crlFileUtil.readCRLFile(crlFile); crl = crlGenerator.syncCRLWithDB(crl); encoded = crlFileUtil.writeCRLFile(crlFile, crl); } catch (CertificateException e) { throw new IseException(e.getMessage(), e); } return new String(encoded); }
public static void initEncryptCert() { CertificateFactory cf = null; FileInputStream in = null; try { cf = CertificateFactory.getInstance("X.509"); in = new FileInputStream(UPMPConstant.encryptCertPath); encryptCert = (X509Certificate) cf.generateCertificate(in); } catch (CertificateException e) { logger.error(e.getMessage()); } catch (FileNotFoundException e) { logger.error(e.getMessage()); } finally { if (null != in) try { in.close(); } catch (IOException e) { logger.error(e.getMessage()); } } }