No peer certificate

393 views
Skip to first unread message

Jefferson Delgado Pérez

unread,
May 17, 2013, 5:32:35 AM5/17/13
to desarrollad...@googlegroups.com
Buenos días!

Me encuentro haciendo la última parte de la aplicación (después de mas de 2 meses..), y consiste en conectar con una web para sincronizar datos y demás.
El problema está que al intentar realizar la conexión, me da el siguiente error:

Error in http connection javax.net.ssl.SSLPeerUnverifiedException: No peer certificate

He leído en bastantes hilos, que el problema está en el certificado de la web (cuando se accede por navegador, dice que no es segura, que si quieres confirmar excepción de seguridad y demás para poder acceder)

El asunto es que he visto varias soluciones, pero a mi no me funciona ninguna y ya no sé dónde más buscar.
La opción de almacenar el certificado en la app la descarto, ya que al intentar buscarlo en el navegador, no aparece la opción de "exportar" ni nada por el estilo, por lo que no puedo obtenerlo.

¿Alguna idea de como poder evitar dicho certificado u obtenerlo y tratarlo cada vez que realice la conexión?

La clase que uso para la conexión es la siguiente:

Introducir código aquí...public class Post {
private InputStream is = null;
private String respuesta = "";
@SuppressWarnings({ "unchecked", "rawtypes" })
private void conectaPost(ArrayList parametros, String URL) {
ArrayList nameValuePairs;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpGet  = new HttpGet(URL);
byte[] data = ("user" + "pass").getBytes("UTF-8");
String nombreyclave = Base64.encodeToString(data, Base64.DEFAULT);
httpGet.addHeader("content-type", "mijson/json");
httpGet.addHeader("Authorization", nombreyclave);
httpGet.addHeader("User-Agent", "agente");
httpGet.addHeader("Cookie", "MiCookie");
nameValuePairs = new ArrayList<String>();

if (parametros != null) {
for (int i = 0; i < parametros.size() - 1; i += 2) {
nameValuePairs.add(new BasicNameValuePair(
(String) parametros.get(i), (String) parametros
.get(i + 1)));
}
// httpGet.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//Buscar cabeceras en api
//httppost.setHeaders(headers)
}
HttpResponse response = httpclient.execute(httpGet);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {

Log.e("log_tag", "Error in http connection " + e.toString());

} finally {

}
}
public String getRespuesta (){
return respuesta;
}

public void getRespuestaPost() {
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
//Log.e("log_tag", "Cadena JSon " + sb );
}
is.close();
respuesta = sb.toString();
} catch (Exception e) {

//Log.e("log_tag", "Error converting result " + e.toString());

}
}

@SuppressWarnings("finally")
public JSONArray getJsonArray() {
JSONArray jArray = null;
try {

jArray = new JSONArray(respuesta);

} catch (Exception e) {

} finally {
return jArray;
}
}

@SuppressWarnings("rawtypes")
public JSONArray getServerData(ArrayList parametros, String URL) {
try {
conectaPost(parametros, URL);
} catch (Exception e) {
// TODO: handle exception
}

if (is != null) {
getRespuestaPost();
}
if (respuesta != null && respuesta.trim() != "") {
return getJsonArray();
} else {
return null;
}
}

Y la llamada al método con:

post.getServerData(parametros,"https://www.miweb.com");


Muchas gracias.


Un saludo

Jefferson Delgado Pérez

unread,
May 24, 2013, 6:35:45 AM5/24/13
to desarrollad...@googlegroups.com
Buenas!

¿Alguno podría ayudarme?

Sigo con la misma pelea..actualmente he conseguido guardar el certificado de la web como bks e importarlo a la app, pero me sigue dando el error "No peer certificate"

Pongo el código que estoy usando ahora, por si alguno sabe

Introducir código aquí...

                       
HttpClient client = new MyHttpClient(context);

HttpGet get = new HttpGet(posturl);
String clave = md5("clave");
String user = "user";

byte[] data = (user + ":" + clave).getBytes("UTF-8");
String nombreyclave = Base64.encodeToString(data, Base64.DEFAULT);
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(
user, clave);
BasicScheme scheme = new BasicScheme();
Header authorizationHeader = scheme.authenticate(credentials,
get);
get.addHeader(authorizationHeader);

get.setHeader("content-type", "application");
// httppost.setHeader("Authorization", nombreyclave);
get.setHeader("User-Agent", "Mozilla");
get.setHeader("Cookie", "COOKIE");


HttpResponse resp = client.execute(get);  //AQUÍ ES DONDE DA EL ERROR

HttpEntity ent = resp.getEntity();/* y obtenemos una respuesta */

String text = EntityUtils.toString(ent);

return text;


public class MyHttpClient extends DefaultHttpClient {
 
   final Context context;
 
   public MyHttpClient(Context context) {
       this.context = context;
   }
 
   @Override
   protected ClientConnectionManager createClientConnectionManager() {
       SchemeRegistry registry = new SchemeRegistry();
       registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
       // Register for port 443 our SSLSocketFactory with our keystore
       // to the ConnectionManager
       registry.register(new Scheme("https", newSslSocketFactory(), 443));
       return new SingleClientConnManager(getParams(), registry);
   }
 
   private SSLSocketFactory newSslSocketFactory() {
       try {
           // Get an instance of the Bouncy Castle KeyStore format
           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(R.raw.certificado);
           try {
               // Initialize the keystore with the provided trusted certificates
               // Also provide the password of the keystore
               trusted.load(in, "clave".toCharArray());
           } finally {
               in.close();
           }
           // Pass the keystore to the SSLSocketFactory. The factory is responsible
           // for the verification of the server certificate.
           SSLSocketFactory sf = new SSLSocketFactory(trusted);
           // Hostname verification from certificate
           sf.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
           return sf;
       } catch (Exception e) {
           throw new AssertionError(e);
       }
   }
}

Muchas gracias.


Un saludo

Jefferson Delgado P.

unread,
Jun 30, 2013, 12:45:07 PM6/30/13
to desarrollad...@googlegroups.com
Buenas,

Al final lo resolví del peor modo posible, que es aceptando todos los certificados, pero bueno, para salir del paso me valió.

Un saludo
Reply all
Reply to author
Forward
0 new messages