java jsp servlets twitter4j
https://github.com/lmenezes/elasticsearch-kopf/archive/master.zip

java - “Falló la creación de la ruta PKIX” y “no se pudo encontrar la ruta de certificación válida para el objetivo solicitado”



jsp servlets (22)

1. Comprobar el certificado.

Intente cargar la URL de destino en el navegador y ver el certificado del sitio (generalmente se puede acceder por el ícono con el signo de bloqueo. Está en el lado izquierdo o derecho de la barra de direcciones del navegador) ya sea que esté vencido o no sea confiable por otra razón.

2. Instalar las últimas versiones de JRE y JDK

Las nuevas versiones suelen venir con el conjunto actualizado de los certificados de confianza.

También si es posible, desinstala versiones antiguas. Esto hará que los errores de configuración incorrecta sean explícitos.

3. Revise su configuración:

  • Compruebe dónde apunta su variable de entorno JAVA_HOME.
  • Compruebe qué versión de Java utiliza para ejecutar el programa. En el cheque de IntelliJ:
    • Archivo -> Estructura del proyecto ... -> Configuración del proyecto -> Proyecto -> SDK del proyecto:
    • Archivo -> Estructura del proyecto ... -> Configuración de plataforma -> SDK

4. Copie todo el almacén de claves de la nueva versión de Java.

Si desarrolla bajo el JDK que no sea el último disponible, intente reemplazar el archivo %JAVA_HOME%/jre/lib/security/cacerts con el nuevo del último JRE instalado (haga una copia de respaldo primero) como sugiere @ jeremy-goodell en su answer

5. Agregue certificado (s) a su almacén de claves

Si nada de lo anterior resuelve su problema, use keytool para guardar los certificados en el almacén de claves de Java:

keytool -trustcacerts -keystore "%JAVA_HOME%jre/lib/security/cacerts" -storepass changeit -importcert -alias <alias_name> -file <path_to_crt_file>

El archivo con el certificado se puede obtener en el navegador como sugiere @MagGGG en su answer .

Nota 1: es posible que deba repetir esto para cada certificado de la cadena al certificado de su sitio. Empezar desde la raíz.

Nota 2: <alias_name> debe ser único entre las claves en la tienda o keytool mostrará un error.

Para obtener una lista de todos los certificados en la tienda, puede ejecutar:

keytool -list -trustcacerts -keystore "%JAVA_HOME%jre/lib/security/cacerts" -storepass changeit

En caso de que algo salga mal, esto le ayudará a eliminar el certificado de la tienda:

keytool -delete -alias <alias_name> -keystore "%JAVA_HOME%jre/lib/security/cacerts" -storepass changeit

Estoy tratando de obtener tweets utilizando la biblioteca twitter4j para mi proyecto Java. En mi primera ejecución recibí un error sobre el certificado sun.security.validator.ValidatorException y sun.security.provider.certpath.SunCertPathBuilderException . Luego agregué el certificado de twitter por:

C:/Program Files/Java/jdk1.7.0_45/jre/lib/security>keytool -importcert -trustcacerts -file PathToCert -alias ca_alias -keystore "C:/Program Files/Java/jdk1.7.0_45/jre/lib/security/cacerts"

Pero sin éxito. Aquí está el procedimiento para obtener twitters:

public static void main(String[] args) throws TwitterException { ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setDebugEnabled(true) .setOAuthConsumerKey("myConsumerKey") .setOAuthConsumerSecret("myConsumerSecret") .setOAuthAccessToken("myAccessToken") .setOAuthAccessTokenSecret("myAccessTokenSecret"); TwitterFactory tf = new TwitterFactory(cb.build()); Twitter twitter = tf.getInstance(); try { Query query = new Query("iphone"); QueryResult result; result = twitter.search(query); System.out.println("Total amount of tweets: " + result.getTweets().size()); List<Status> tweets = result.getTweets(); for (Status tweet : tweets) { System.out.println("@" + tweet.getUser().getScreenName() + " : " + tweet.getText()); } } catch (TwitterException te) { te.printStackTrace(); System.out.println("Failed to search tweets: " + te.getMessage()); }

Y aquí está el error:

sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target Relevant discussions can be found on the Internet at: http://www.google.co.jp/search?q=d35baff5 or http://www.google.co.jp/search?q=1446302e TwitterException{exceptionCode=[d35baff5-1446302e 43208640-747fd158 43208640-747fd158 43208640-747fd158], statusCode=-1, message=null, code=-1, retryAfter=-1, rateLimitStatus=null, version=3.0.5} at twitter4j.internal.http.HttpClientImpl.request(HttpClientImpl.java:177) at twitter4j.internal.http.HttpClientWrapper.request(HttpClientWrapper.java:61) at twitter4j.internal.http.HttpClientWrapper.get(HttpClientWrapper.java:81) at twitter4j.TwitterImpl.get(TwitterImpl.java:1929) at twitter4j.TwitterImpl.search(TwitterImpl.java:306) at jku.cc.servlets.TweetsAnalyzer.main(TweetsAnalyzer.java:38) Caused by: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target at sun.security.ssl.Alerts.getSSLException(Unknown Source) at sun.security.ssl.SSLSocketImpl.fatal(Unknown Source) at sun.security.ssl.Handshaker.fatalSE(Unknown Source) at sun.security.ssl.Handshaker.fatalSE(Unknown Source) at sun.security.ssl.ClientHandshaker.serverCertificate(Unknown Source) at sun.security.ssl.ClientHandshaker.processMessage(Unknown Source) at sun.security.ssl.Handshaker.processLoop(Unknown Source) at sun.security.ssl.Handshaker.process_record(Unknown Source) at sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source) at sun.security.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source) at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source) at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source) at sun.net.www.protocol.https.HttpsClient.afterConnect(Unknown Source) at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source) at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source) at java.net.HttpURLConnection.getResponseCode(Unknown Source) at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(Unknown Source) at twitter4j.internal.http.HttpResponseImpl.<init>(HttpResponseImpl.java:34) at twitter4j.internal.http.HttpClientImpl.request(HttpClientImpl.java:141) ... 5 more Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target at sun.security.validator.PKIXValidator.doBuild(Unknown Source) at sun.security.validator.PKIXValidator.engineValidate(Unknown Source) at sun.security.validator.Validator.validate(Unknown Source) at sun.security.ssl.X509TrustManagerImpl.validate(Unknown Source) at sun.security.ssl.X509TrustManagerImpl.checkTrusted(Unknown Source) at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(Unknown Source) ... 20 more Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(Unknown Source) at java.security.cert.CertPathBuilder.build(Unknown Source) ... 26 more Failed to search tweets: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target


  1. Vaya a la URL en su navegador Firefox, haga clic en la cadena de certificados HTTPS (junto a la dirección URL). Haga clic en "more info" > "security" > "show certificate" > "details" > "export.." . Recoge el nombre y elige el tipo de archivo example.cer. Ahora tiene un archivo con keystore y debe agregarlo a su JVM

  2. Determine la ubicación de los archivos cacerts, por ejemplo. C:/Program Files (x86)/Java/jre1.6.0_22/lib/security/cacerts.

  3. A continuación, importe el archivo example.cer en cacerts en la línea de comando:

keytool -import -alias example -keystore C:/Program Files (x86)/Java/jre1.6.0_22/lib/security/cacerts -file example.cer

Se le pedirá la contraseña, que por defecto es changeit

Reinicie su JVM / PC.

fuente: http://magicmonster.com/kb/prg/java/ssl/pkix_path_building_failed.html


Agregar cacerts no funcionó para mí. Después de habilitar el registro con el indicador -Djavax.net.debug=all , luego jssecacerts lectura de Java desde jssecacerts .

La importación a jssecacerts finalmente funcionó.


Después de muchas horas tratando de crear archivos de certificados para que mi instalación de Java 6 funcionara con los nuevos certificados de Twitter, finalmente me topé con una solución increíblemente simple que se encuentra en un comentario en uno de los paneles de mensajes. Simplemente copie el archivo cacerts de una instalación de Java 7 y sobrescriba el de su instalación de Java 6. Probablemente sea mejor hacer una copia de seguridad del archivo cacerts primero, ¡pero luego simplemente copie el nuevo en BOOM! simplemente funciona

Tenga en cuenta que en realidad copié un archivo de Windows cacerts en una instalación de Linux y funcionó bien.

El archivo se encuentra en jre/lib/security/cacerts en las instalaciones de Java jdk antiguas y nuevas.

Espero que esto le ahorre a alguien más horas de agravación.


Enfoque de MI UI:

  1. Descargar http://www.keystore-explorer.org/
  2. Abra $ JAVA_HOME / jre / lib / security / cacerts
  3. enter PW: changeit (puede ser changeme en Mac)
  4. Importa tu archivo .crt

CMD-Line:

  1. keytool -importcert -file jetty.crt -alias jetty -keystore $ JAVA_HOME / jre / lib / security / cacerts
  2. enter PW: changeit (puede ser changeme en Mac)

Esta no es una respuesta específica de Twitter, pero esta es la pregunta que surge cuando busca este error. Si su sistema recibe este error al conectarse a un sitio web que parece tener un certificado válido cuando se ve en un navegador web , eso probablemente significa que el sitio web tiene una cadena de certificados incompleta .

Para un breve resumen del problema: las autoridades de certificación no usan su certificado raíz para firmar cualquier certificado antiguo. En su lugar, (generalmente) firman certificados intermedios que también tienen el indicador de Autoridad de certificación establecido (es decir, se les permite firmar certificados). Luego, cuando compra un certificado de una CA, ellos firman su CSR con uno de estos certificados intermedios.

Lo más probable es que su almacén de confianza de Java solo tenga el certificado raíz, no los intermedios.

Un sitio mal configurado puede devolver solo su certificado firmado. Problema: se firmó con un certificado intermedio que no está en su almacén de confianza. Los navegadores manejarán este problema mediante la descarga o el uso de un certificado intermedio en caché; esto maximiza la compatibilidad del sitio web. Java y herramientas como OpenSSL, sin embargo, no lo harán. Y eso causará el error en la pregunta.

Puede verificar esta sospecha usando la prueba SSL de Qualys . Si lo ejecutas contra un sitio y dice

La cadena de certificados de este servidor está incompleta.

entonces eso lo confirma. También puede ver esto mirando las rutas de certificación y viendo el texto Extra Download .

Cómo solucionarlo: el administrador del servidor debe configurar el servidor web para devolver también los certificados intermedios. Para Comodo, por ejemplo, aquí es donde el archivo .ca-bundle es útil. Por ejemplo, en una configuración de Apache con mod_ssl, usaría la configuración de configuración SSLCertificateChainFile . Para nginx, debe concatenar los certificados intermedios y el certificado firmado y usarlo en la configuración del certificado SSL. Puede encontrar más buscando "Cadena de certificados incompletos" en línea.


La razón por la que obtenemos el error anterior es que JDK está empaquetado con una gran cantidad de certificados de Autoridad de Certificación (CA) confiables en un archivo llamado ''cacerts'' pero este archivo no tiene idea de nuestro certificado autofirmado. En otras palabras, el archivo cacerts no tiene nuestro certificado autofirmado importado y, por lo tanto, no lo trata como una entidad confiable y, por lo tanto, da el error anterior.

Cómo solucionar el error anterior

Para corregir el error anterior, todo lo que necesitamos es importar el certificado autofirmado en el archivo cacerts.

Primero, localice el archivo cacerts. Tendremos que averiguar la ubicación JDK. Si está ejecutando su aplicación a través de uno de los IDE como Eclipse o IntelliJ Idea, vaya a la configuración del proyecto y averigüe cuál es la ubicación de JDK. Por ejemplo, en una ubicación típica de Mac OS del archivo cacerts estaría en esta ubicación / Library / Java / JavaVirtualMachines / {{JDK_version}} / Contents / Home / jre / lib / security en la máquina de Windows estaría en {{Installation_directory} } / {{JDK_version}} / jre / lib / security

Una vez que haya localizado el archivo cacerts, ahora necesitamos importar nuestro certificado autofirmado a este archivo cacerts. Verifique el último artículo, si no sabe cómo generar correctamente el certificado autofirmado.

Si no tiene un archivo de certificado (.crt) y solo tiene un archivo .jks, puede generar un archivo .crt usando el siguiente comando. En caso de que ya tenga un archivo .crt / .pem, puede ignorar el siguiente comando

## Para generar un certificado desde el almacén de claves (archivo .jks) ####

keytool -export -keystore keystore.jks -alias selfsigned -file selfsigned.crt

El paso anterior generará un archivo llamado selfsigned.crt.Now Importe el certificado a cacerts

Ahora agregue el certificado a JRE / lib / security / cacerts (trustore)

keytool -importcert -file selfsigned.crt -alias selfsigned -keystore {{cacerts path}} Ahora agregue el certificado a JRE / lib / security / cacerts (trustore)

keytool -importcert -file selfsigned.crt -alias selfsigned -keystore {{cacerts path}}

por ejemplo

keytool -importcert -file selfsigned.nextgen.crt -alias selfsigned.nextgen -keystore /Library/Java/JavaVirtualMachines/jdk1.8.0_171.jdk/Contents/Home/jre/lib/security/cacerts

Eso es todo, reinicie su aplicación y debería funcionar bien. Si todavía no funciona y obtener una excepción de protocolo de enlace SSL. Probablemente significa que está usando un dominio diferente y luego registrado en el certificado.

El enlace con una explicación detallada y una resolución paso a paso se encuentra aquí.


Me encontré con esta pregunta al tratar de instalar el complemento Cucumber-Eclipse en Eclipse a través de su sitio de actualización. Recibí el mismo error SunCertPathBuilderException:

Unable to read repository at http://cucumber.io/cucumber-eclipse/update-site/content.xml. Unable to read repository at http://cucumber.io/cucumber-eclipse/update-site/content.xml. sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

Si bien algunas de las otras respuestas son apropiadas y útiles para la situación dada de esta pregunta, no obstante, fueron inútiles y engañosas para mi problema.

En mi caso, el problema fue que la URL proporcionada para su sitio de actualización es:

https://cucumber.io/cucumber-eclipse/update-site

Sin embargo, al navegar a través de un navegador, se redirigió a (tenga en cuenta el " .github añadido"):

http://cucumber.github.io/cucumber-eclipse/update-site/

Por lo tanto, la resolución es simplemente usar la versión redirigida de la URL del sitio de actualización al agregar el sitio de actualización en eclipse.


Me he topado con este problema que requirió muchas horas de investigación para solucionarlo, especialmente con los certificados generados automáticamente, que a diferencia de los Oficiales, son bastante difíciles y a Java no les gustan mucho.

Por favor revise el siguiente enlace: Solucionar problemas con certificados en Java

Básicamente, debe agregar el certificado del servidor a los certificados de inicio de Java.

  1. Genere u obtenga su certificado y configure Tomcat para usarlo en Servers.xml
  2. Descargue el código fuente de Java de la clase InstallCert y ejecútelo mientras el servidor se está ejecutando, proporcionando el siguiente server[:port] argumentos server[:port] . No se necesita contraseña, ya que la contraseña original funciona para los certificados Java ("changeit").
  3. El Programa se conectará al servidor y Java emitirá una excepción, analizará el certificado proporcionado por el servidor y le permitirá crear un archivo jssecerts dentro del directorio donde ejecutó el Programa (si se ejecuta desde Eclipse, asegúrese de configurar el Directorio de trabajo en Run -> Configurations ).
  4. Copie manualmente ese archivo a $JAVA_HOME/jre/lib/security

Después de seguir estos pasos, las conexiones con el certificado ya no generarán excepciones dentro de Java.

El siguiente código fuente es importante y desapareció de los blogs de (Sun) Oracle, la única página que encontré en el enlace provisto, por lo tanto, lo adjunto en la respuesta para cualquier referencia.

/* * Copyright 2006 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Sun Microsystems nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * Originally from: * http://blogs.sun.com/andreas/resource/InstallCert.java * Use: * java InstallCert hostname * Example: *% java InstallCert ecc.fedora.redhat.com */ import javax.net.ssl.*; import java.io.*; import java.security.KeyStore; import java.security.MessageDigest; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; /** * Class used to add the server''s certificate to the KeyStore * with your trusted certificates. */ public class InstallCert { public static void main(String[] args) throws Exception { String host; int port; char[] passphrase; if ((args.length == 1) || (args.length == 2)) { String[] c = args[0].split(":"); host = c[0]; port = (c.length == 1) ? 443 : Integer.parseInt(c[1]); String p = (args.length == 1) ? "changeit" : args[1]; passphrase = p.toCharArray(); } else { System.out.println("Usage: java InstallCert [:port] [passphrase]"); return; } File file = new File("jssecacerts"); if (file.isFile() == false) { char SEP = File.separatorChar; File dir = new File(System.getProperty("java.home") + SEP + "lib" + SEP + "security"); file = new File(dir, "jssecacerts"); if (file.isFile() == false) { file = new File(dir, "cacerts"); } } System.out.println("Loading KeyStore " + file + "..."); InputStream in = new FileInputStream(file); KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(in, passphrase); in.close(); SSLContext context = SSLContext.getInstance("TLS"); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(ks); X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0]; SavingTrustManager tm = new SavingTrustManager(defaultTrustManager); context.init(null, new TrustManager[]{tm}, null); SSLSocketFactory factory = context.getSocketFactory(); System.out.println("Opening connection to " + host + ":" + port + "..."); SSLSocket socket = (SSLSocket) factory.createSocket(host, port); socket.setSoTimeout(10000); try { System.out.println("Starting SSL handshake..."); socket.startHandshake(); socket.close(); System.out.println(); System.out.println("No errors, certificate is already trusted"); } catch (SSLException e) { System.out.println(); e.printStackTrace(System.out); } X509Certificate[] chain = tm.chain; if (chain == null) { System.out.println("Could not obtain server certificate chain"); return; } BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); System.out.println(); System.out.println("Server sent " + chain.length + " certificate(s):"); System.out.println(); MessageDigest sha1 = MessageDigest.getInstance("SHA1"); MessageDigest md5 = MessageDigest.getInstance("MD5"); for (int i = 0; i < chain.length; i++) { X509Certificate cert = chain[i]; System.out.println (" " + (i + 1) + " Subject " + cert.getSubjectDN()); System.out.println(" Issuer " + cert.getIssuerDN()); sha1.update(cert.getEncoded()); System.out.println(" sha1 " + toHexString(sha1.digest())); md5.update(cert.getEncoded()); System.out.println(" md5 " + toHexString(md5.digest())); System.out.println(); } System.out.println("Enter certificate to add to trusted keystore or ''q'' to quit: [1]"); String line = reader.readLine().trim(); int k; try { k = (line.length() == 0) ? 0 : Integer.parseInt(line) - 1; } catch (NumberFormatException e) { System.out.println("KeyStore not changed"); return; } X509Certificate cert = chain[k]; String alias = host + "-" + (k + 1); ks.setCertificateEntry(alias, cert); OutputStream out = new FileOutputStream("jssecacerts"); ks.store(out, passphrase); out.close(); System.out.println(); System.out.println(cert); System.out.println(); System.out.println ("Added certificate to keystore ''jssecacerts'' using alias ''" + alias + "''"); } private static final char[] HEXDIGITS = "0123456789abcdef".toCharArray(); private static String toHexString(byte[] bytes) { StringBuilder sb = new StringBuilder(bytes.length * 3); for (int b : bytes) { b &= 0xff; sb.append(HEXDIGITS[b >> 4]); sb.append(HEXDIGITS[b & 15]); sb.append('' ''); } return sb.toString(); } private static class SavingTrustManager implements X509TrustManager { private final X509TrustManager tm; private X509Certificate[] chain; SavingTrustManager(X509TrustManager tm) { this.tm = tm; } public X509Certificate[] getAcceptedIssuers() { throw new UnsupportedOperationException(); } public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { throw new UnsupportedOperationException(); } public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { this.chain = chain; tm.checkServerTrusted(chain, authType); } } }


Quería importar certificado para smtp.gmail.com

La única solución que me funcionó es 1. Ingrese el comando para ver este certificado

D: / openssl / bin / openssl.exe s_client -connect smtp.gmail.com:465

  1. Copie y guarde las líneas entre "----- BEGIN CERTIFICATE -----" y "----- END CERTIFICATE -----" en un archivo, gmail.cer

  2. correr

    keytool -import -alias smtp.gmail.com -keystore "% JAVA_HOME% / jre / lib / security / cacerts" -file C: / Users / Admin / Desktop / gmail.cer

  3. Introduzca la contraseña chageit

  4. Haga clic en Sí para importar el certificado.

  5. Reiniciar java

Ahora ejecuta el comando y ya está bueno para ir


Tuve una situación ligeramente diferente, cuando tanto JDK como JRE 1.8.0_112 estaban presentes en mi sistema.

[JDK_FOLDER]/jre/lib/security/cacerts los nuevos certificados de CA en [JDK_FOLDER]/jre/lib/security/cacerts usando el comando ya conocido:

keytool -import -trustcacerts -keystore cacerts -alias <new_ca_alias> -file <path_to_ca_cert_file>

Sin embargo, seguí recibiendo el mismo error de creación de ruta PKIX fallido .

Agregué información de depuración a la CLI de java, usando java -Djavax.net.debug=all ... > debug.log . En el archivo debug.log, la línea que comienza con trustStore es: en realidad apunta al almacén de cacerts que se encuentra en [JRE_FOLDER]/lib/security/cacerts .

En mi caso, la solución fue copiar el archivo de cacerts utilizado por JDK (al que se agregaron las nuevas CAs) sobre el utilizado por el JRE y que solucionó el problema.


Antecedentes del tema:

Recibí el siguiente error cuando trato de ejecutar la instalación de mvn clean en mi proyecto y a través de la opción de compilación y limpieza de Netbeans IDE. Este problema se debe a que el certificado no está disponible cuando descargamos a través de NET beans IDE / a través del símbolo del sistema, pero podemos descargar los archivos a través del navegador.

Error :

Caused by: org.eclipse.aether.transfer.ArtifactTransferException: Could not transfer artifact com.java.project:product:jar:1.0.32 from/to repo-local (https://url/local-repo): sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

Resolución:

1. Descargar el certificado de la url en cuestión:

  • Inicie IE por "ejecutar como administrador" (de lo contrario, no podremos descargar el certificado)
  • Ingrese la url en IE-> https://url/local-repo (en mi caso, esta url tenía un certificado no confiable .)
  • Descargue el certificado haciendo clic en Error de certificado -> ver certificado
  • Seleccione la pestaña Detalles -> copiar en archivo -> siguiente -> seleccione "DER binario codificado X.509 (.CER)
  • guarde el certificado en alguna ubicación, por ejemplo: c: /user/sheldon/desktop/product.cer
  • Felicidades Usted ha descargado exitosamente el certificado para el sitio.

2. Ahora instale el almacén de claves para solucionar el problema.

  • Ejecute el comando keytool para agregar el almacén de claves descargado al archivo de certificado existente.
  • Comando: debajo del comando en la carpeta bin de jdk (JAVA_HOME) .

C: / Archivos de programa / Java / jdk1.8.0_141 / jre / bin> keytool -importcert -file "C: /user/sheldon/desktop/product.cer" -alias product -keystore "C: / Program Files / Java / jdk1.8.0_141 / jre / lib / security / cacerts ".

  • Se le pedirá que introduzca la contraseña. Introduzca la contraseña del almacén de claves: ingrese "changeit" nuevamente para "¿Confiar en este certificado? [No]:", ingrese "sí"

Ejemplo de comandos de línea de comandos / salida:

keytool -importcert -file "C:/Users/sheldon/Desktop/product.cer" -alias product -keystore "C:/Program iles/Java/jdk1.8.0_141/jre/lib/security/cacerts" Enter keystore password: Trust this certificate? [no]: yes Certificate was added to keystore

  • Felicidades ahora debería haber eliminado el error "PKIX path building: sun.security.provider.certpath.SunCertPathBuilderException" en su IDE de Netbeans.

Arreglé esto usando el siguiente método

  1. Copia url que tiene problema de conexión
  2. Ir a Android Studio-> Configuración-> Configuración Http
  3. En ''Test Connection'', pega esa URL y presiona OK
  4. Al hacer clic en Aceptar, Android Studio solicitará importar el certificado de esa url, importarlo
  5. Eso es.Nada más por hacer y mi problema se había ido. No hay necesidad de reiniciar el estudio también.

Estaba enfrentando el mismo problema y lo resolví usando los sencillos pasos a continuación:

1) Descargue el InstallCert.java de google

2) Compílalo utilizando javac InstallCert.java

3) Ejecute InstallCert.java usando java InstallCert.java , con el nombre de host y el puerto https, y presione "1" cuando solicite una entrada. Agregará el "localhost" como un almacén de claves de confianza y generará un archivo llamado "jssecacerts" como se muestra a continuación:

java InstallCert localhost: 443

4) copie los jssecacerts en la carpeta $ JAVA_HOME / jre / lib / security

La fuente principal para resolver el problema aquí es:

https://ankurjain26.blogspot.in/2017/11/javaxnetsslsslhandshakeexception.html


metas:

  1. usar conexiones https
  2. verificar las cadenas SSL
  3. no lidiar con cacerts
  4. agregar certificado en tiempo de ejecución
  5. No pierdas certificados de cacerts.

Cómo hacerlo:

  1. definir propio almacén de claves
  2. poner el certificado en el almacén de claves
  3. redefinir el contexto predeterminado de SSL con nuestra clase personalizada
  4. ???
  5. lucro

Mi archivo de contenedor de almacén de claves:

public class CertificateManager { private final static Logger logger = Logger.getLogger(CertificateManager.class); private String keyStoreLocation; private String keyStorePassword; private X509TrustManager myTrustManager; private static KeyStore myTrustStore; public CertificateManager(String keyStoreLocation, String keyStorePassword) throws Exception { this.keyStoreLocation = keyStoreLocation; this.keyStorePassword = keyStorePassword; myTrustStore = createKeyStore(keyStoreLocation, keyStorePassword); } public void addCustomCertificate(String certFileName, String certificateAlias) throws Exception { TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init((KeyStore) null); Certificate certificate = myTrustStore.getCertificate(certificateAlias); if (certificate == null) { logger.info("Certificate not exists"); addCertificate(certFileName, certificateAlias); } else { logger.info("Certificate exists"); } tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(myTrustStore); for (TrustManager tm : tmf.getTrustManagers()) { if (tm instanceof X509TrustManager) { setMytrustManager((X509TrustManager) tm); logger.info("Trust manager found"); break; } } } private InputStream fullStream(String fname) throws IOException { ClassLoader classLoader = getClass().getClassLoader(); InputStream resource = classLoader.getResourceAsStream(fname); try { if (resource != null) { DataInputStream dis = new DataInputStream(resource); byte[] bytes = new byte[dis.available()]; dis.readFully(bytes); return new ByteArrayInputStream(bytes); } else { logger.info("resource not found"); } } catch (Exception e) { logger.error("exception in certificate fetching as resource", e); } return null; } public static KeyStore createKeyStore(String keystore, String pass) throws Exception { try { InputStream in = CertificateManager.class.getClass().getResourceAsStream(keystore); KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(in, pass.toCharArray()); logger.info("Keystore was created from resource file"); return keyStore; } catch (Exception e) { logger.info("Fail to create keystore from resource file"); } File file = new File(keystore); KeyStore keyStore = KeyStore.getInstance("JKS"); if (file.exists()) { keyStore.load(new FileInputStream(file), pass.toCharArray()); logger.info("Default keystore loaded"); } else { keyStore.load(null, null); keyStore.store(new FileOutputStream(file), pass.toCharArray()); logger.info("New keystore created"); } return keyStore; } private void addCertificate(String certFileName, String certificateAlias) throws CertificateException, IOException, KeyStoreException, NoSuchAlgorithmException { CertificateFactory cf = CertificateFactory.getInstance("X.509"); InputStream certStream = fullStream(certFileName); Certificate certs = cf.generateCertificate(certStream); myTrustStore.setCertificateEntry(certificateAlias, certs); FileOutputStream out = new FileOutputStream(getKeyStoreLocation()); myTrustStore.store(out, getKeyStorePassword().toCharArray()); out.close(); logger.info("Certificate pushed"); } public String getKeyStoreLocation() { return keyStoreLocation; } public String getKeyStorePassword() { return keyStorePassword; } public X509TrustManager getMytrustManager() { return myTrustManager; } public void setMytrustManager(X509TrustManager myTrustManager) { this.myTrustManager = myTrustManager; } }

Esta clase creará un almacén de claves si es necesario, y podrá administrar certificados dentro de ella. Ahora clase para contexto SSL:

public class CustomTrustManager implements X509TrustManager { private final static Logger logger = Logger.getLogger(CertificateManager.class); private static SSLSocketFactory socketFactory; private static CustomTrustManager instance = new CustomTrustManager(); private static List<CertificateManager> register = new ArrayList<>(); public static CustomTrustManager getInstance() { return instance; } private X509TrustManager defaultTm; public void register(CertificateManager certificateManager) { for(CertificateManager manager : register) { if(manager == certificateManager) { logger.info("Certificate manager already registered"); return; } } register.add(certificateManager); logger.info("New Certificate manager registered"); } private CustomTrustManager() { try { String algorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm); tmf.init((KeyStore) null); boolean found = false; for (TrustManager tm : tmf.getTrustManagers()) { if (tm instanceof X509TrustManager) { defaultTm = (X509TrustManager) tm; found = true; break; } } if(found) { logger.info("Default trust manager found"); } else { logger.warn("Default trust manager was not found"); } SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, new TrustManager[]{this}, null); SSLContext.setDefault(sslContext); socketFactory = sslContext.getSocketFactory(); HttpsURLConnection.setDefaultSSLSocketFactory(socketFactory); logger.info("Custom trust manager was set"); } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) { logger.warn("Custom trust manager can''t be set"); e.printStackTrace(); } } @Override public X509Certificate[] getAcceptedIssuers() { List<X509Certificate> out = new ArrayList<>(); if (defaultTm != null) { out.addAll(Arrays.asList(defaultTm.getAcceptedIssuers())); } int defaultCount = out.size(); logger.info("Default trust manager contain " + defaultCount + " certficates"); for(CertificateManager manager : register) { X509TrustManager customTrustManager = manager.getMytrustManager(); X509Certificate[] issuers = customTrustManager.getAcceptedIssuers(); out.addAll(Arrays.asList(issuers)); } logger.info("Custom trust managers contain " + (out.size() - defaultCount) + " certficates"); X509Certificate[] arrayOut = new X509Certificate[out.size()]; return out.toArray(arrayOut); } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { for(CertificateManager certificateManager : register) { X509TrustManager customTrustManager = certificateManager.getMytrustManager(); try { customTrustManager.checkServerTrusted(chain, authType); logger.info("Certificate chain (server) was aproved by custom trust manager"); return; } catch (Exception e) { } } if (defaultTm != null) { defaultTm.checkServerTrusted(chain, authType); logger.info("Certificate chain (server) was aproved by default trust manager"); } else { logger.info("Certificate chain (server) was rejected"); throw new CertificateException("Can''t check server trusted certificate."); } } @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { try { if (defaultTm != null) { defaultTm.checkClientTrusted(chain, authType); logger.info("Certificate chain (client) was aproved by default trust manager"); } else { throw new NullPointerException(); } } catch (Exception e) { for(CertificateManager certificateManager : register) { X509TrustManager customTrustManager = certificateManager.getMytrustManager(); try { customTrustManager.checkClientTrusted(chain, authType); logger.info("Certificate chain (client) was aproved by custom trust manager"); return; } catch (Exception e1) { } } logger.info("Certificate chain (client) was rejected"); throw new CertificateException("Can''t check client trusted certificate."); } } public SSLSocketFactory getSocketFactory() { return socketFactory; } }

Esta clase se hizo como singleton, porque solo se permite un contexto por defecto de SSL. Entonces, ahora usa:

CertificateManager certificateManager = new CertificateManager("C://myapplication//mykeystore.jks", "changeit"); String certificatePath = "C://myapplication//public_key_for_your_ssl_service.crt"; try { certificateManager.addCustomCertificate(certificatePath, "alias_for_public_key_for_your_ssl_service"); } catch (Exception e) { log.error("Can''t add custom certificate"); e.printStackTrace(); } CustomTrustManager.getInstance().register(certificateManager);

Posiblemente, no funcionará con esta configuración, porque mantengo el archivo de certificado dentro de la carpeta de recursos, por lo que mi ruta no es absoluta. Pero en general, funciona perfectamente.


Aquí normalmente este tipo de excepción ocurre cuando no hay coincidencia en el PATH del certificado de confianza. Verifique la configuración o la ruta donde se requiere este certificado de servidor para una comunicación segura.


Cuando tiene un error anterior con el software atlassian ej. jira

2018-08-18 11:35:00,312 Caesium-1-4 WARN anonymous Default Mail Handler [c.a.mail.incoming.mailfetcherservice] Default Mail Handler[10001]: javax.mail.MessagingException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target while connecting to host ''imap.xyz.pl'' as user ''[email protected]'' via protocol ''imaps, caused by: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

puede agregar certificados a su almacén de claves de confianza (cambie missing_ca al nombre correcto del certificado):

keytool -importcert -file missing_ca.crt -alias missing_ca -keystore /opt/atlassian/jira/jre/lib/security/cacerts

Si se le pide poner contraseña changeity confirmary

Después de eso simplemente reinicie jira.


Es una adición a la respuesta https://.com/a/36427118/1491414 . Gracias @MagGGG

  • Por favor, asegúrese de que tiene permiso de administrador
  • Utilice comillas dobles para la ruta del almacén de claves (-keystore C: / Archivos de programa (x86) / Java / jre1.6.0_22 / lib / seguridad / cacerts ") porque en el sistema operativo Windows la ubicación de instalación predeterminada será Archivos de programa y obtendrá un error debido al espacio entre los archivos de programa.

Para mí, apareció un error de certificado porque tenía fiddler ejecutándose en segundo plano y eso se confunde con el certificado. Actúa como un proxy tan cercano y reinicia el eclipse.


Si la URL de su repositorio también funciona en HTTP y la seguridad no es una preocupación, puede ir a settings.xml (a menudo, pero no siempre, ubicado en %USERPROFILE%/.m2) y reemplazar HTTPS con HTTP para <repository>y <pluginRepository>URL.

Por ejemplo, esto:

<repository> <snapshots> <enabled>false</enabled> </snapshots> <id>central</id> <name>libs-release</name> <url>https://<artifactory>/libs-release</url> </repository>

debe ser reemplazado por este:

<repository> <snapshots> <enabled>false</enabled> </snapshots> <id>central</id> <name>libs-release</name> <url>https://<artifactory>/libs-release</url> </repository>


Tengo el mismo problema en Ubuntu 15.10. Intente descargar el plugin localmente, por ejemplo, https://github.com/lmenezes/elasticsearch-kopf/archive/master.zip e instale con este comando:

sudo /usr/share/elasticsearch/bin/plugin install file:/home/dev/Downloads/elasticsearch-kopf-master.zip

El camino puede ser diferente dependiendo de su entorno.

Saludos.


-Dmaven.wagon.http.ssl.insecure=true -Dmaven.wagon.http.ssl.allowall=true

Se utiliza para saltar la validación del certificado.