¿Cómo crear y leer programáticamente configuraciones WEP / EAP WiFi en Android?

¿Cómo crear y leer programáticamente WEP/EAP WiFi configurations en Android?

He visto a varias personas luchando en esta misma pregunta en varios foros y en toda la comunidad. Sé que esto no es tan directo (especialmente EAP) para entender porque cuando quería lograr lo mismo, también me costaba bastante. Bueno, todo el trabajo duro del análisis de código y la búsqueda de varias implementaciones en Internet con I finalmente capaz de alcanzar el objective. Todo el mérito es para la cantidad de proyectos de código abierto y sus desarrolladores.

Me gustaría compartir este conocimiento con todos, ya que SO lo alienta : “También es perfectamente correcto preguntar y responder a su propia pregunta, siempre y cuando pretenda que está en Jeopardy: formémoslo en forma de pregunta”.

Parte 1: Crear una configuración WEP WiFi programáticamente.

Parte 2: lee una configuración WEP WiFi programáticamente.

Parte 3: lea una configuración WiFi de EAP programmatically.

Parte 4: Guarde una configuración WiFi de EAP programmatically.

    Parte 1: Crear una configuración WEP WiFi programáticamente

    Esto es bastante sencillo, WifiConfiguration expone la interfaz para crear la misma. Aquí está el código de ejemplo:

     void saveWepConfig() { WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE); WifiConfiguration wc = new WifiConfiguration(); wc.SSID = "\"SSID_NAME\""; //IMP! This should be in Quotes!! wc.hiddenSSID = true; wc.status = WifiConfiguration.Status.DISABLED; wc.priority = 40; wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); wc.allowedProtocols.set(WifiConfiguration.Protocol.RSN); wc.allowedProtocols.set(WifiConfiguration.Protocol.WPA); wc.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN); wc.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED); wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP); wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP); wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40); wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104); wc.wepKeys[0] = "\"aaabbb1234\""; //This is the WEP Password wc.wepTxKeyIndex = 0; WifiManager wifiManag = (WifiManager) this.getSystemService(WIFI_SERVICE); boolean res1 = wifiManag.setWifiEnabled(true); int res = wifi.addNetwork(wc); Log.d("WifiPreference", "add Network returned " + res ); boolean es = wifi.saveConfiguration(); Log.d("WifiPreference", "saveConfiguration returned " + es ); boolean b = wifi.enableNetwork(res, true); Log.d("WifiPreference", "enableNetwork returned " + b ); } 

    Siguiendo los permisos necesarios en AndroidManifest.xml

            

    Parte 2: lee una configuración WEP WiFi programáticamente
    De frente otra vez. Aquí está el código de ejemplo:

      void readWepConfig() { WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE); List item = wifi.getConfiguredNetworks(); int i = item.size(); Log.d("WifiPreference", "NO OF CONFIG " + i ); Iterator iter = item.iterator(); WifiConfiguration config = item.get(0); Log.d("WifiPreference", "SSID" + config.SSID); Log.d("WifiPreference", "PASSWORD" + config.preSharedKey); Log.d("WifiPreference", "ALLOWED ALGORITHMS"); Log.d("WifiPreference", "LEAP" + config.allowedAuthAlgorithms.get(AuthAlgorithm.LEAP)); Log.d("WifiPreference", "OPEN" + config.allowedAuthAlgorithms.get(AuthAlgorithm.OPEN)); Log.d("WifiPreference", "SHARED" + config.allowedAuthAlgorithms.get(AuthAlgorithm.SHARED)); Log.d("WifiPreference", "GROUP CIPHERS"); Log.d("WifiPreference", "CCMP" + config.allowedGroupCiphers.get(GroupCipher.CCMP)); Log.d("WifiPreference", "TKIP" + config.allowedGroupCiphers.get(GroupCipher.TKIP)); Log.d("WifiPreference", "WEP104" + config.allowedGroupCiphers.get(GroupCipher.WEP104)); Log.d("WifiPreference", "WEP40" + config.allowedGroupCiphers.get(GroupCipher.WEP40)); Log.d("WifiPreference", "KEYMGMT"); Log.d("WifiPreference", "IEEE8021X" + config.allowedKeyManagement.get(KeyMgmt.IEEE8021X)); Log.d("WifiPreference", "NONE" + config.allowedKeyManagement.get(KeyMgmt.NONE)); Log.d("WifiPreference", "WPA_EAP" + config.allowedKeyManagement.get(KeyMgmt.WPA_EAP)); Log.d("WifiPreference", "WPA_PSK" + config.allowedKeyManagement.get(KeyMgmt.WPA_PSK)); Log.d("WifiPreference", "PairWiseCipher"); Log.d("WifiPreference", "CCMP" + config.allowedPairwiseCiphers.get(PairwiseCipher.CCMP)); Log.d("WifiPreference", "NONE" + config.allowedPairwiseCiphers.get(PairwiseCipher.NONE)); Log.d("WifiPreference", "TKIP" + config.allowedPairwiseCiphers.get(PairwiseCipher.TKIP)); Log.d("WifiPreference", "Protocols"); Log.d("WifiPreference", "RSN" + config.allowedProtocols.get(Protocol.RSN)); Log.d("WifiPreference", "WPA" + config.allowedProtocols.get(Protocol.WPA)); Log.d("WifiPreference", "WEP Key Strings"); String[] wepKeys = config.wepKeys; Log.d("WifiPreference", "WEP KEY 0" + wepKeys[0]); Log.d("WifiPreference", "WEP KEY 1" + wepKeys[1]); Log.d("WifiPreference", "WEP KEY 2" + wepKeys[2]); Log.d("WifiPreference", "WEP KEY 3" + wepKeys[3]); } 

    Parte 3: Leer una configuración de WiFi EAP mediante progtwigción
    Ahora esto es complicado. Puede encontrar el código que guarda una configuración EAP WiFi a través de la interfaz de usuario de Android vanilla en WifiDialog.java . Es bastante fácil. Podemos usar el mismo código en nuestra aplicación. ¡Bueno, NO! Si prueba esto, obtendrá errores que eap no puede encontrar los símbolos eap , phase , client_cert , etc. Una pequeña investigación detallada nos dice que EnterpriseField is private dentro de la clase WiFiConfiguration y que todos los símbolos que no podemos encontrar son del tipo EnterpriseField . Bueno, hemos llegado a un obstáculo. Necesitamos estos campos para leer / guardar una configuración de EAP, ¡pero no tenemos acceso programático a ellos!

    Java Reflection API para el rescate Bueno, no soy un experto en Java, así que no entraré en los detalles de Reflection API como tal y puedes buscar tutoriales en Google u obtener más información aquí . Para mantenerlo corto y dulce, Reflection API le permite inspeccionar clases, interfaces, campos y métodos en tiempo de ejecución, sin conocer los nombres de las clases, métodos, etc. en tiempo de comstackción. También es posible crear instancias de objetos nuevos, invocar métodos y obtener / establecer valores de campo mediante la reflexión. Y, lo que es importante, Reflection puede ayudarlo a acceder a los miembros de datos privados dentro de una clase. Bueno, esto es lo que necesitamos, ¿no? 🙂

    Revisemos ahora el ejemplo del código que muestra cómo leer una configuración EAP WiFi usando Reflection Api. Como extra, el fragmento registrará la configuración en un archivo y lo guardará en la tarjeta SD … bastante elegante … bueno, un poco de información general sobre Reflection Api y estoy seguro de que captar el código a continuación es fácil.

      private static final String INT_PRIVATE_KEY = "private_key"; private static final String INT_PHASE2 = "phase2"; private static final String INT_PASSWORD = "password"; private static final String INT_IDENTITY = "identity"; private static final String INT_EAP = "eap"; private static final String INT_CLIENT_CERT = "client_cert"; private static final String INT_CA_CERT = "ca_cert"; private static final String INT_ANONYMOUS_IDENTITY = "anonymous_identity"; final String INT_ENTERPRISEFIELD_NAME = "android.net.wifi.WifiConfiguration$EnterpriseField"; 

    Este es el código para crear un archivo de registro en la tarjeta SD antes de llamar a la función readEapConfig() .

      BufferedWriter out = null; try { File root = Environment.getExternalStorageDirectory(); Toast toast = Toast.makeText(this, "SD CARD mounted and writable? " + root.canWrite(), 5000); toast.show(); if (root.canWrite()) { File gpxfile = new File(root, "ReadConfigLog.txt"); FileWriter gpxwriter = new FileWriter(gpxfile); out = new BufferedWriter(gpxwriter); out.write("Hello world"); //out.close(); } } catch (IOException e) { Toast toast = Toast.makeText(this, "Problem reading SD CARD", 3000); Toast toast2 = Toast.makeText(this, "Please take logs using Logcat", 5000); Log.e("< <<<<<<<<>>>>>>>>>>>", "Could not write file " + e.getMessage()); } 

    Ahora la función readEapConfig() misma:

      void readEapConfig(BufferedWriter out) { /*Get the WifiService */ WifiManager wifi = (WifiManager)getSystemService(WIFI_SERVICE); /*Get All WIfi configurations*/ List configList = wifi.getConfiguredNetworks(); /*Now we need to search appropriate configuration ie with name SSID_Name*/ for(int i = 0;i iter = configList.iterator(); WifiConfiguration config = configList.get(i); /*I dont think these fields have anything to do with EAP config but still will * print these to be on safe side*/ try { Log.d("< <<<<<<<<>>>>>>>>>>>", "[SSID]" + config.SSID); out.write("< <<<<<<<<>>>>>>>>>>>" + "[SSID]" + config.SSID); Log.d("< <<<<<<<<>>>>>>>>>>>", "[BSSID]" + config.BSSID); out.write("< <<<<<<<<>>>>>>>>>>>" +"[BSSID]" + config.BSSID); Log.d("< <<<<<<<<>>>>>>>>>>>", "[HIDDEN SSID]" + config.hiddenSSID); out.write("< <<<<<<<<>>>>>>>>>>>" + "[HIDDEN SSID]" + config.hiddenSSID); Log.d("< <<<<<<<<>>>>>>>>>>>", "[PASSWORD]" + config.preSharedKey); out.write("< <<<<<<<<>>>>>>>>>>>"+ "[PASSWORD]" + config.preSharedKey); Log.d("< <<<<<<<<>>>>>>>>>>>", "[ALLOWED ALGORITHMS]"); out.write("< <<<<<<<<>>>>>>>>>>>"+ "[ALLOWED ALGORITHMS]"); Log.d("< <<<<<<<<>>>>>>>>>>>", "[LEAP]" + config.allowedAuthAlgorithms.get(AuthAlgorithm.LEAP)); out.write("< <<<<<<<<>>>>>>>>>>>" + "[LEAP]" + config.allowedAuthAlgorithms.get(AuthAlgorithm.LEAP)); Log.d("< <<<<<<<<>>>>>>>>>>>", "[OPEN]" + config.allowedAuthAlgorithms.get(AuthAlgorithm.OPEN)); out.write("< <<<<<<<<>>>>>>>>>>>" + "[OPEN]" + config.allowedAuthAlgorithms.get(AuthAlgorithm.OPEN)); Log.d("< <<<<<<<<>>>>>>>>>>>", "[SHARED]" + config.allowedAuthAlgorithms.get(AuthAlgorithm.SHARED)); out.write("< <<<<<<<<>>>>>>>>>>>" + "[SHARED]" + config.allowedAuthAlgorithms.get(AuthAlgorithm.SHARED)); Log.d("< <<<<<<<<>>>>>>>>>>>", "[GROUP CIPHERS]"); out.write("< <<<<<<<<>>>>>>>>>>>" + "[GROUP CIPHERS]"); Log.d("< <<<<<<<<>>>>>>>>>>>", "[CCMP]" + config.allowedGroupCiphers.get(GroupCipher.CCMP)); out.write("< <<<<<<<<>>>>>>>>>>>" + "[CCMP]" + config.allowedGroupCiphers.get(GroupCipher.CCMP)); Log.d("< <<<<<<<<>>>>>>>>>>>" , "[TKIP]" + config.allowedGroupCiphers.get(GroupCipher.TKIP)); out.write("< <<<<<<<<>>>>>>>>>>>"+ "[TKIP]" + config.allowedGroupCiphers.get(GroupCipher.TKIP)); Log.d("< <<<<<<<<>>>>>>>>>>>", "[WEP104]" + config.allowedGroupCiphers.get(GroupCipher.WEP104)); out.write("< <<<<<<<<>>>>>>>>>>>" + "[WEP104]" + config.allowedGroupCiphers.get(GroupCipher.WEP104)); Log.d("< <<<<<<<<>>>>>>>>>>>", "[WEP40]" + config.allowedGroupCiphers.get(GroupCipher.WEP40)); out.write("< <<<<<<<<>>>>>>>>>>>" + "[WEP40]" + config.allowedGroupCiphers.get(GroupCipher.WEP40)); Log.d("< <<<<<<<<>>>>>>>>>>>", "[KEYMGMT]"); out.write("< <<<<<<<<>>>>>>>>>>>" + "[KEYMGMT]"); Log.d("< <<<<<<<<>>>>>>>>>>>", "[IEEE8021X]" + config.allowedKeyManagement.get(KeyMgmt.IEEE8021X)); out.write("< <<<<<<<<>>>>>>>>>>>"+ "[IEEE8021X]" + config.allowedKeyManagement.get(KeyMgmt.IEEE8021X)); Log.d("< <<<<<<<<>>>>>>>>>>>", "[NONE]" + config.allowedKeyManagement.get(KeyMgmt.NONE)); out.write("< <<<<<<<<>>>>>>>>>>>" + "[NONE]" + config.allowedKeyManagement.get(KeyMgmt.NONE)); Log.d("< <<<<<<<<>>>>>>>>>>>", "[WPA_EAP]" + config.allowedKeyManagement.get(KeyMgmt.WPA_EAP)); out.write("< <<<<<<<<>>>>>>>>>>>" + "[WPA_EAP]" + config.allowedKeyManagement.get(KeyMgmt.WPA_EAP)); Log.d("< <<<<<<<<>>>>>>>>>>>", "[WPA_PSK]" + config.allowedKeyManagement.get(KeyMgmt.WPA_PSK)); out.write("< <<<<<<<<>>>>>>>>>>>" + "[WPA_PSK]" + config.allowedKeyManagement.get(KeyMgmt.WPA_PSK)); Log.d("< <<<<<<<<>>>>>>>>>>>", "[PairWiseCipher]"); out.write("< <<<<<<<<>>>>>>>>>>>" + "[PairWiseCipher]"); Log.d("< <<<<<<<<>>>>>>>>>>>", "[CCMP]" + config.allowedPairwiseCiphers.get(PairwiseCipher.CCMP)); out.write("< <<<<<<<<>>>>>>>>>>>" + "[CCMP]" + config.allowedPairwiseCiphers.get(PairwiseCipher.CCMP)); Log.d("< <<<<<<<<>>>>>>>>>>>", "[NONE]" + config.allowedPairwiseCiphers.get(PairwiseCipher.NONE)); out.write("< <<<<<<<<>>>>>>>>>>>" + "[NONE]" + config.allowedPairwiseCiphers.get(PairwiseCipher.NONE)); Log.d("< <<<<<<<<>>>>>>>>>>>", "[TKIP]" + config.allowedPairwiseCiphers.get(PairwiseCipher.TKIP)); out.write("< <<<<<<<<>>>>>>>>>>>" + "[TKIP]" + config.allowedPairwiseCiphers.get(PairwiseCipher.TKIP)); Log.d("< <<<<<<<<>>>>>>>>>>>", "[Protocols]"); out.write("< <<<<<<<<>>>>>>>>>>>" + "[Protocols]"); Log.d("< <<<<<<<<>>>>>>>>>>>", "[RSN]" + config.allowedProtocols.get(Protocol.RSN)); out.write("< <<<<<<<<>>>>>>>>>>>" + "[RSN]" + config.allowedProtocols.get(Protocol.RSN)); Log.d("< <<<<<<<<>>>>>>>>>>>", "[WPA]" + config.allowedProtocols.get(Protocol.WPA)); out.write("< <<<<<<<<>>>>>>>>>>>" + "[WPA]" + config.allowedProtocols.get(Protocol.WPA)); Log.d("< <<<<<<<<>>>>>>>>>>>", "[PRE_SHARED_KEY]" + config.preSharedKey); out.write("< <<<<<<<<>>>>>>>>>>>" + "[PRE_SHARED_KEY]" + config.preSharedKey); Log.d("< <<<<<<<<>>>>>>>>>>>", "[WEP Key Strings]"); out.write("< <<<<<<<<>>>>>>>>>>>" + "[WEP Key Strings]"); String[] wepKeys = config.wepKeys; Log.d("< <<<<<<<<>>>>>>>>>>>", "[WEP KEY 0]" + wepKeys[0]); out.write("< <<<<<<<<>>>>>>>>>>>" + "[WEP KEY 0]" + wepKeys[0]); Log.d("< <<<<<<<<>>>>>>>>>>>", "[WEP KEY 1]" + wepKeys[1]); out.write("< <<<<<<<<>>>>>>>>>>>" + "[WEP KEY 1]" + wepKeys[1]); Log.d("< <<<<<<<<>>>>>>>>>>>", "[WEP KEY 2]" + wepKeys[2]); out.write("< <<<<<<<<>>>>>>>>>>>" + "[WEP KEY 2]" + wepKeys[2]); Log.d("< <<<<<<<<>>>>>>>>>>>", "[WEP KEY 3]" + wepKeys[3]); out.write("< <<<<<<<<>>>>>>>>>>>" + "[WEP KEY 3]" + wepKeys[3]); } catch(IOException e) { Toast toast1 = Toast.makeText(this, "Failed to write Logs to ReadConfigLog.txt", 3000); Toast toast2 = Toast.makeText(this, "Please take logs using Logcat", 5000); Log.e("< <<<<<<<<>>>>>>>>>>>", "Could not write to ReadConfigLog.txt" + e.getMessage()); } /*reflection magic*/ /*These are the fields we are really interested in*/ try { // Let the magic start Class[] wcClasses = WifiConfiguration.class.getClasses(); // null for overzealous java compiler Class wcEnterpriseField = null; for (Class wcClass : wcClasses) if (wcClass.getName().equals(INT_ENTERPRISEFIELD_NAME)) { wcEnterpriseField = wcClass; break; } boolean noEnterpriseFieldType = false; if(wcEnterpriseField == null) noEnterpriseFieldType = true; // Cupcake/Donut access enterprise settings directly Field wcefAnonymousId = null, wcefCaCert = null, wcefClientCert = null, wcefEap = null, wcefIdentity = null, wcefPassword = null, wcefPhase2 = null, wcefPrivateKey = null; Field[] wcefFields = WifiConfiguration.class.getFields(); // Dispatching Field vars for (Field wcefField : wcefFields) { if (wcefField.getName().trim().equals(INT_ANONYMOUS_IDENTITY)) wcefAnonymousId = wcefField; else if (wcefField.getName().trim().equals(INT_CA_CERT)) wcefCaCert = wcefField; else if (wcefField.getName().trim().equals(INT_CLIENT_CERT)) wcefClientCert = wcefField; else if (wcefField.getName().trim().equals(INT_EAP)) wcefEap = wcefField; else if (wcefField.getName().trim().equals(INT_IDENTITY)) wcefIdentity = wcefField; else if (wcefField.getName().trim().equals(INT_PASSWORD)) wcefPassword = wcefField; else if (wcefField.getName().trim().equals(INT_PHASE2)) wcefPhase2 = wcefField; else if (wcefField.getName().trim().equals(INT_PRIVATE_KEY)) wcefPrivateKey = wcefField; } Method wcefValue = null; if(!noEnterpriseFieldType) { for(Method m: wcEnterpriseField.getMethods()) //System.out.println(m.getName()); if(m.getName().trim().equals("value")){ wcefValue = m; break; } } /*EAP Method*/ String result = null; Object obj = null; if(!noEnterpriseFieldType) { obj = wcefValue.invoke(wcefEap.get(config), null); String retval = (String)obj; Log.d("< <<<<<<<<>>>>>>>>>>>", "[EAP METHOD]" + retval); out.write("< <<<<<<<<>>>>>>>>>>>" + "[EAP METHOD]" + retval); } else { obj = wcefEap.get(config); String retval = (String)obj; } /*phase 2*/ if(!noEnterpriseFieldType) { result = (String) wcefValue.invoke(wcefPhase2.get(config), null); Log.d("< <<<<<<<<>>>>>>>>>>>", "[EAP PHASE 2 AUTHENTICATION]" + result); out.write("< <<<<<<<<>>>>>>>>>>>" + "[EAP PHASE 2 AUTHENTICATION]" + result); } else { result = (String) wcefPhase2.get(config); } /*Anonymous Identity*/ if(!noEnterpriseFieldType) { result = (String) wcefValue.invoke(wcefAnonymousId.get(config),null); Log.d("< <<<<<<<<>>>>>>>>>>>", "[EAP ANONYMOUS IDENTITY]" + result); out.write("< <<<<<<<<>>>>>>>>>>>" + "[EAP ANONYMOUS IDENTITY]" + result); } else { result = (String) wcefAnonymousId.get(config); } /*CA certificate*/ if(!noEnterpriseFieldType) { result = (String) wcefValue.invoke(wcefCaCert.get(config), null); Log.d("< <<<<<<<<>>>>>>>>>>>", "[EAP CA CERTIFICATE]" + result); out.write("< <<<<<<<<>>>>>>>>>>>" + "[EAP CA CERTIFICATE]" + result); } else { result = (String)wcefCaCert.get(config); } /*private key*/ if(!noEnterpriseFieldType) { result = (String) wcefValue.invoke(wcefPrivateKey.get(config),null); Log.d("< <<<<<<<<>>>>>>>>>>>", "[EAP PRIVATE KEY]" + result); out.write("< <<<<<<<<>>>>>>>>>>>" + "[EAP PRIVATE KEY]" + result); } else { result = (String)wcefPrivateKey.get(config); } /*Identity*/ if(!noEnterpriseFieldType) { result = (String) wcefValue.invoke(wcefIdentity.get(config), null); Log.d("< <<<<<<<<>>>>>>>>>>>", "[EAP IDENTITY]" + result); out.write("< <<<<<<<<>>>>>>>>>>>" + "[EAP IDENTITY]" + result); } else { result = (String)wcefIdentity.get(config); } /*Password*/ if(!noEnterpriseFieldType) { result = (String) wcefValue.invoke(wcefPassword.get(config), null); Log.d("< <<<<<<<<>>>>>>>>>>>", "[EAP PASSWORD]" + result); out.write("< <<<<<<<<>>>>>>>>>>>" + "[EAP PASSWORD]" + result); } else { result = (String)wcefPassword.get(config); } /*client certificate*/ if(!noEnterpriseFieldType) { result = (String) wcefValue.invoke(wcefClientCert.get(config), null); Log.d("< <<<<<<<<>>>>>>>>>>>", "[EAP CLIENT CERT]" + result); out.write("< <<<<<<<<>>>>>>>>>>>" + "[EAP CLIENT CERT]" + result); Toast toast1 = Toast.makeText(this, "All config data logged to ReadConfigLog.txt", 3000); Toast toast2 = Toast.makeText(this, "Extract ReadConfigLog.txt from SD CARD", 5000); } else { result = (String)wcefClientCert.get(config); } out.close(); } catch(IOException e) { Toast toast1 = Toast.makeText(this, "Failed to write Logs to ReadConfigLog.txt", 3000); Toast toast2 = Toast.makeText(this, "Please take logs using Logcat", 5000); Log.e("< <<<<<<<<>>>>>>>>>>>", "Could not write to ReadConfigLog.txt" + e.getMessage()); } catch(Exception e) { e.printStackTrace(); } } } } 

    Ahh me quedé sin espacio de edición, agregando la parte restante aquí.

    Parte 4: Guarde una configuración WiFi EAP mediante progtwigción

    Si ya leíste la parte 3, ya entiendes la magia de Reflejo que funciona aquí. Si vas directamente a esta sección, lee la introducción antes del fragmento de código en la parte 3 y estarás al tanto de la velocidad del código. !

     void saveEapConfig(String passString, String userName) { /********************************Configuration Strings****************************************************/ final String ENTERPRISE_EAP = "TLS"; final String ENTERPRISE_CLIENT_CERT = "keystore://USRCERT_CertificateName"; final String ENTERPRISE_PRIV_KEY = "USRPKEY_CertificateName"; //CertificateName = Name given to the certificate while installing it /*Optional Params- My wireless Doesn't use these*/ final String ENTERPRISE_PHASE2 = ""; final String ENTERPRISE_ANON_IDENT = "ABC"; final String ENTERPRISE_CA_CERT = ""; // If required: "keystore://CACERT_CaCertificateName" /********************************Configuration Strings****************************************************/ /*Create a WifiConfig*/ WifiConfiguration selectedConfig = new WifiConfiguration(); /*AP Name*/ selectedConfig.SSID = "\"SSID_Name\""; /*Priority*/ selectedConfig.priority = 40; /*Enable Hidden SSID*/ selectedConfig.hiddenSSID = true; /*Key Mgmnt*/ selectedConfig.allowedKeyManagement.clear(); selectedConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.IEEE8021X); selectedConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP); /*Group Ciphers*/ selectedConfig.allowedGroupCiphers.clear(); selectedConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP); selectedConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP); selectedConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104); selectedConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40); /*Pairwise ciphers*/ selectedConfig.allowedPairwiseCiphers.clear(); selectedConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP); selectedConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP); /*Protocols*/ selectedConfig.allowedProtocols.clear(); selectedConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN); selectedConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA); // Enterprise Settings // Reflection magic here too, need access to non-public APIs try { // Let the magic start Class[] wcClasses = WifiConfiguration.class.getClasses(); // null for overzealous java compiler Class wcEnterpriseField = null; for (Class wcClass : wcClasses) if (wcClass.getName().equals(INT_ENTERPRISEFIELD_NAME)) { wcEnterpriseField = wcClass; break; } boolean noEnterpriseFieldType = false; if(wcEnterpriseField == null) noEnterpriseFieldType = true; // Cupcake/Donut access enterprise settings directly Field wcefAnonymousId = null, wcefCaCert = null, wcefClientCert = null, wcefEap = null, wcefIdentity = null, wcefPassword = null, wcefPhase2 = null, wcefPrivateKey = null, wcefEngine = null, wcefEngineId = null; Field[] wcefFields = WifiConfiguration.class.getFields(); // Dispatching Field vars for (Field wcefField : wcefFields) { if (wcefField.getName().equals(INT_ANONYMOUS_IDENTITY)) wcefAnonymousId = wcefField; else if (wcefField.getName().equals(INT_CA_CERT)) wcefCaCert = wcefField; else if (wcefField.getName().equals(INT_CLIENT_CERT)) wcefClientCert = wcefField; else if (wcefField.getName().equals(INT_EAP)) wcefEap = wcefField; else if (wcefField.getName().equals(INT_IDENTITY)) wcefIdentity = wcefField; else if (wcefField.getName().equals(INT_PASSWORD)) wcefPassword = wcefField; else if (wcefField.getName().equals(INT_PHASE2)) wcefPhase2 = wcefField; else if (wcefField.getName().equals(INT_PRIVATE_KEY)) wcefPrivateKey = wcefField; else if (wcefField.getName().equals("engine")) wcefEngine = wcefField; else if (wcefField.getName().equals("engine_id")) wcefEngineId = wcefField; } Method wcefSetValue = null; if(!noEnterpriseFieldType){ for(Method m: wcEnterpriseField.getMethods()) //System.out.println(m.getName()); if(m.getName().trim().equals("setValue")) wcefSetValue = m; } /*EAP Method*/ if(!noEnterpriseFieldType) { wcefSetValue.invoke(wcefEap.get(selectedConfig), ENTERPRISE_EAP); } else { wcefEap.set(selectedConfig, ENTERPRISE_EAP); } /*EAP Phase 2 Authentication*/ if(!noEnterpriseFieldType) { wcefSetValue.invoke(wcefPhase2.get(selectedConfig), ENTERPRISE_PHASE2); } else { wcefPhase2.set(selectedConfig, ENTERPRISE_PHASE2); } /*EAP Anonymous Identity*/ if(!noEnterpriseFieldType) { wcefSetValue.invoke(wcefAnonymousId.get(selectedConfig), ENTERPRISE_ANON_IDENT); } else { wcefAnonymousId.set(selectedConfig, ENTERPRISE_ANON_IDENT); } /*EAP CA Certificate*/ if(!noEnterpriseFieldType) { wcefSetValue.invoke(wcefCaCert.get(selectedConfig), ENTERPRISE_CA_CERT); } else { wcefCaCert.set(selectedConfig, ENTERPRISE_CA_CERT); } /*EAP Private key*/ if(!noEnterpriseFieldType) { wcefSetValue.invoke(wcefPrivateKey.get(selectedConfig), ENTERPRISE_PRIV_KEY); } else { wcefPrivateKey.set(selectedConfig, ENTERPRISE_PRIV_KEY); } /*EAP Identity*/ if(!noEnterpriseFieldType) { wcefSetValue.invoke(wcefIdentity.get(selectedConfig), userName); } else { wcefIdentity.set(selectedConfig, userName); } /*EAP Password*/ if(!noEnterpriseFieldType) { wcefSetValue.invoke(wcefPassword.get(selectedConfig), passString); } else { wcefPassword.set(selectedConfig, passString); } /*EAp Client certificate*/ if(!noEnterpriseFieldType) { wcefSetValue.invoke(wcefClientCert.get(selectedConfig), ENTERPRISE_CLIENT_CERT); } else { wcefClientCert.set(selectedConfig, ENTERPRISE_CLIENT_CERT); } /*Engine fields*/ if(!noEnterpriseFieldType) { wcefSetValue.invoke(wcefEngine.get(wifiConf), "1"); wcefSetValue.invoke(wcefEngineId.get(wifiConf), "keystore"); } // Adhoc for CM6 // if non-CM6 fails gracefully thanks to nested try-catch try{ Field wcAdhoc = WifiConfiguration.class.getField("adhocSSID"); Field wcAdhocFreq = WifiConfiguration.class.getField("frequency"); //wcAdhoc.setBoolean(selectedConfig, prefs.getBoolean(PREF_ADHOC, // false)); wcAdhoc.setBoolean(selectedConfig, false); int freq = 2462; // default to channel 11 //int freq = Integer.parseInt(prefs.getString(PREF_ADHOC_FREQUENCY, //"2462")); // default to channel 11 //System.err.println(freq); wcAdhocFreq.setInt(selectedConfig, freq); } catch (Exception e) { e.printStackTrace(); } } catch (Exception e) { // TODO Auto-generated catch block // FIXME As above, what should I do here? e.printStackTrace(); } WifiManager wifiManag = (WifiManager) getSystemService(Context.WIFI_SERVICE); boolean res1 = wifiManag.setWifiEnabled(true); int res = wifiManag.addNetwork(selectedConfig); Log.d("WifiPreference", "add Network returned " + res ); boolean b = wifiManag.enableNetwork(selectedConfig.networkId, false); Log.d("WifiPreference", "enableNetwork returned " + b ); boolean c = wifiManag.saveConfiguration(); Log.d("WifiPreference", "Save configuration returned " + c ); boolean d = wifiManag.enableNetwork(res, true); Log.d("WifiPreference", "enableNetwork returned " + d ); } 

    ¡Bueno, eso es todo! Y espero que esto ayude a algún desarrollador perdido, en algún lugar, alguna vez 🙂

    Android ha agregado una API a JellyBean 4.3. Debe usar esta opción si desea configurar WIFI en la API 18:

    http://developer.android.com/reference/android/net/wifi/WifiEnterpriseConfig.html

    ¡La Parte 4 me inició en el camino correcto! However i wanted to create a TTLS rather than TLS config here is how i did it!

      /********************************Configuration Strings****************************************************/ final String ENTERPRISE_EAP = "TTLS"; /*Optional Params- My wireless Doesn't use these*/ final String ENTERPRISE_PHASE2 = "PAP"; final String ENTERPRISE_ANON_IDENT = "ABC"; final String ENTERPRISE_CA_CERT = ""; /********************************Configuration Strings****************************************************/ /*Create a WifiConfig*/ WifiConfiguration selectedConfig = new WifiConfiguration(); /*AP Name*/ selectedConfig.SSID = "\"EAP_SSID_TEST_CONFIG\""; /*Priority*/ selectedConfig.priority = 40; /*Enable Hidden SSID*/ selectedConfig.hiddenSSID = false; /*Key Mgmnt*/ selectedConfig.allowedKeyManagement.clear(); selectedConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.IEEE8021X); selectedConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP); /*Group Ciphers*/ selectedConfig.allowedGroupCiphers.clear(); selectedConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP); selectedConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP); selectedConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104); selectedConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40); /*Pairwise ciphers*/ selectedConfig.allowedPairwiseCiphers.clear(); selectedConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP); selectedConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP); /*Protocols*/ selectedConfig.allowedProtocols.clear(); selectedConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN); selectedConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA); // Enterprise Settings // Reflection magic here too, need access to non-public APIs try { // Let the magic start Class[] wcClasses = WifiConfiguration.class.getClasses(); // null for overzealous java compiler Class wcEnterpriseField = null; for (Class wcClass : wcClasses) if (wcClass.getName().equals(INT_ENTERPRISEFIELD_NAME)) { wcEnterpriseField = wcClass; break; } boolean noEnterpriseFieldType = false; if(wcEnterpriseField == null) noEnterpriseFieldType = true; // Cupcake/Donut access enterprise settings directly Field wcefAnonymousId = null, wcefCaCert = null, wcefClientCert = null, wcefEap = null, wcefIdentity = null, wcefPassword = null, wcefPhase2 = null, wcefPrivateKey = null; Field[] wcefFields = WifiConfiguration.class.getFields(); // Dispatching Field vars for (Field wcefField : wcefFields) { if (wcefField.getName().equals(INT_ANONYMOUS_IDENTITY)) wcefAnonymousId = wcefField; else if (wcefField.getName().equals(INT_CA_CERT)) wcefCaCert = wcefField; else if (wcefField.getName().equals(INT_CLIENT_CERT)) wcefClientCert = wcefField; else if (wcefField.getName().equals(INT_EAP)) wcefEap = wcefField; else if (wcefField.getName().equals(INT_IDENTITY)) wcefIdentity = wcefField; else if (wcefField.getName().equals(INT_PASSWORD)) wcefPassword = wcefField; else if (wcefField.getName().equals(INT_PHASE2)) wcefPhase2 = wcefField; else if (wcefField.getName().equals(INT_PRIVATE_KEY)) wcefPrivateKey = wcefField; } Method wcefSetValue = null; if(!noEnterpriseFieldType){ for(Method m: wcEnterpriseField.getMethods()) //System.out.println(m.getName()); if(m.getName().trim().equals("setValue")) wcefSetValue = m; } /*EAP Method*/ if(!noEnterpriseFieldType){ wcefSetValue.invoke(wcefEap.get(selectedConfig), ENTERPRISE_EAP); } /*EAP Phase 2 Authentication*/ if(!noEnterpriseFieldType){ wcefSetValue.invoke(wcefPhase2.get(selectedConfig), ENTERPRISE_PHASE2); } /*EAP Anonymous Identity*/ if(!noEnterpriseFieldType){ wcefSetValue.invoke(wcefAnonymousId.get(selectedConfig), ENTERPRISE_ANON_IDENT); } /*EAP CA Certificate*/ if(!noEnterpriseFieldType){ wcefSetValue.invoke(wcefCaCert.get(selectedConfig), ENTERPRISE_CA_CERT); } /*EAP Identity*/ if(!noEnterpriseFieldType){ wcefSetValue.invoke(wcefIdentity.get(selectedConfig), "test user name"); } /*EAP Password*/ if(!noEnterpriseFieldType){ wcefSetValue.invoke(wcefPassword.get(selectedConfig), "test password"); } try{ } catch (Exception e) { e.printStackTrace(); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } WifiManager wifiManag = (WifiManager) getSystemService(Context.WIFI_SERVICE); boolean res1 = wifiManag.setWifiEnabled(true); int res = wifiManag.addNetwork(selectedConfig); Log.d("WifiPreference", "add Network returned " + res ); // boolean b = wifiManag.enableNetwork(selectedConfig.networkId, false); // Log.d("WifiPreference", "enableNetwork returned " + b ); // boolean c = wifiManag.saveConfiguration(); // Log.d("WifiPreference", "Save configuration returned " + c ); // boolean d = wifiManag.enableNetwork(res, true); // Log.d("WifiPreference", "enableNetwork returned " + d ); } 

    Hope this helps some one. @Android learner I removed the bit about adHocFrequency and SSID as they were causing crashes but my results were still good without them.

    The WEP keys are masked, so it is not possible to read them with the mentioned code

      Log.d("WifiPreference", "WEP KEY 0" + wepKeys[0]); Log.d("WifiPreference", "WEP KEY 1" + wepKeys[1]); Log.d("WifiPreference", "WEP KEY 2" + wepKeys[2]); Log.d("WifiPreference", "WEP KEY 3" + wepKeys[3]); 

    Is there any way to solve this in same way as the EAP solution? With reflection?