Created
April 13, 2023 02:58
-
-
Save sheepyang2022/53066b7de3dfdef8635829d4703bf307 to your computer and use it in GitHub Desktop.
WifiUtil
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.seuic.seuicoemconfig.Util; | |
import android.annotation.SuppressLint; | |
import android.content.Context; | |
import android.net.wifi.WifiConfiguration; | |
import android.net.wifi.WifiEnterpriseConfig; | |
import android.net.wifi.WifiManager; | |
import android.os.Build; | |
import android.text.TextUtils; | |
import android.util.Log; | |
import android.net.wifi.WifiEnterpriseConfig.Eap; | |
import android.net.wifi.WifiEnterpriseConfig.Phase2; | |
import com.seuic.seuicoemconfig.BaseApplication; | |
import java.lang.reflect.Field; | |
import java.util.List; | |
public class WifiUtil { | |
private static final String TAG = "WifiUtil"; | |
private static final String SYSTEM_CA_STORE_PATH = "/system/etc/security/cacerts"; | |
private static final String WIFI_CA_NOT_VALIDATE = "Do not validate"; | |
private static final String WIFI_CA_USE_SYSTEM = "Use system Certificates"; | |
private static final String WIFI_CA_UNSPECIFIED = "Use system Certificates"; | |
private static final int WAPI_PSK_TYPE_ASCII = 0; | |
private static final int WAPI_PSK_TYPE_HEX = 1; | |
private static volatile WifiUtil instance; | |
private Context mContext; | |
private WifiManager wifiManager; | |
public static WifiUtil getInstance() { | |
if (instance == null) { | |
synchronized (WifiUtil.class) { | |
if (instance == null) | |
instance = new WifiUtil(); | |
} | |
} | |
return instance; | |
} | |
private WifiUtil() { | |
mContext = BaseApplication.application; | |
wifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE); | |
} | |
@SuppressLint("MissingPermission") | |
public boolean addWifi(String ssid, String securityStr, String eapMethodStr, String phase2MethodStr, String caCert, String certificateStatusStr, String domain, String clientCert, String wapiCert, String identity, String anonymousIdentity, String wapiPskTypeStr, String password, boolean default_wifi, String privacy) { | |
WifiConfiguration config = new WifiConfiguration(); | |
if (StringUtil.isBlank(ssid)) { | |
Log.e(TAG, "ssid cannot be empty!"); | |
return false; | |
} | |
ssid = "\"" + ssid + "\""; | |
config.SSID = ssid; | |
config.priority = 40;//设置优先级 | |
config.hiddenSSID = true;//假设网络是隐藏的 | |
int security = StringUtil.parseInt(securityStr, -1); | |
if (security == -1) { | |
Log.e(TAG, "Invalid \"security\" field! security:" + securityStr); | |
return false; | |
} | |
int privacyValue; | |
if (!TextUtils.isEmpty(privacy)) { | |
privacyValue = Integer.parseInt(privacy); | |
if (privacyValue != -1) { | |
setMacRandomizationSetting(config, privacyValue); | |
} | |
} | |
switch (security) { | |
case WifiEntry.SECURITY_NONE: | |
setSecurityParams(config, WifiConfiguration.SECURITY_TYPE_OPEN); | |
break; | |
case WifiEntry.SECURITY_WEP: | |
setSecurityParams(config, WifiConfiguration.SECURITY_TYPE_WEP); | |
if (StringUtil.isNotBlank(password)) { | |
int length = password.length(); | |
// WEP-40, WEP-104, and 256-bit WEP (WEP-232?) | |
if ((length == 10 || length == 26 || length == 58) | |
&& password.matches("[0-9A-Fa-f]*")) { | |
config.wepKeys[0] = password; | |
} else { | |
config.wepKeys[0] = '"' + password + '"'; | |
} | |
} | |
break; | |
case WifiEntry.SECURITY_PSK: | |
setSecurityParams(config, WifiConfiguration.SECURITY_TYPE_PSK); | |
if (StringUtil.isNotBlank(password)) { | |
if (password.matches("[0-9A-Fa-f]{64}")) { | |
config.preSharedKey = password; | |
} else { | |
config.preSharedKey = '"' + password + '"'; | |
} | |
} | |
break; | |
case WifiEntry.SECURITY_EAP:// WPA/WPA2/WPA3-Enterprise | |
case WifiEntry.SECURITY_EAP_SUITE_B: | |
if (security == WifiEntry.SECURITY_EAP_SUITE_B) { | |
// allowedSuiteBCiphers will be set according to certificate type | |
setSecurityParams(config, WifiConfiguration.SECURITY_TYPE_EAP_SUITE_B); | |
} else { | |
setSecurityParams(config, WifiConfiguration.SECURITY_TYPE_EAP); | |
} | |
config.enterpriseConfig = new WifiEnterpriseConfig(); | |
int eapMethod = StringUtil.parseInt(eapMethodStr, -1); | |
int phase2Method = StringUtil.parseInt(phase2MethodStr, -1); | |
if (eapMethod == -1) { | |
Log.e(TAG, "Unknown eapMethod method:[" + eapMethodStr + "]"); | |
return false; | |
} | |
config.enterpriseConfig.setEapMethod(eapMethod); | |
switch (eapMethod) { | |
case Eap.PEAP: | |
// PEAP supports limited phase2 values | |
// Map the index from the mPhase2PeapAdapter to the one used | |
// by the API which has the full list of PEAP methods. | |
if (phase2Method == Phase2.MSCHAPV2 | |
|| phase2Method == Phase2.GTC | |
|| phase2Method == Phase2.SIM | |
|| phase2Method == Phase2.AKA | |
|| phase2Method == Phase2.AKA_PRIME) { | |
config.enterpriseConfig.setPhase2Method(phase2Method); | |
} else { | |
Log.e(TAG, "Unknown phase2 method" + phase2MethodStr); | |
return false; | |
} | |
break; | |
case Eap.TTLS: | |
// The default index from mPhase2TtlsAdapter maps to the API | |
if (phase2Method == Phase2.PAP | |
|| phase2Method == Phase2.MSCHAP | |
|| phase2Method == Phase2.MSCHAPV2 | |
|| phase2Method == Phase2.GTC) { | |
config.enterpriseConfig.setPhase2Method(phase2Method); | |
} else { | |
Log.e(TAG, "Unknown phase2 method" + phase2MethodStr); | |
return false; | |
} | |
break; | |
case Eap.SIM: | |
case Eap.AKA: | |
case Eap.AKA_PRIME: | |
// selectedSimCardNumber = 0; | |
// config.enterpriseConfig.setSimNum(selectedSimCardNumber); | |
break; | |
default: | |
Log.e(TAG, "Unknow e"); | |
break; | |
} | |
// if (config.enterpriseConfig.isAuthenticationSimBased() | |
// && mActiveSubscriptionInfos.size() > 0) { | |
// config.carrierId = mActiveSubscriptionInfos | |
// .get(mEapSimSpinner.getSelectedItemPosition()).getCarrierId(); | |
// } | |
if (StringUtil.isBlank(caCert)) { | |
caCert = WIFI_CA_UNSPECIFIED; | |
} | |
setCaCertificateAliases(config.enterpriseConfig, null); | |
setCaPath(config.enterpriseConfig, null); | |
if (StringUtil.isBlank(domain)) { | |
Log.e(TAG, "\"Domin\" should not be taken as empty"); | |
return false; | |
} | |
config.enterpriseConfig.setDomainSuffixMatch(domain); | |
if (caCert.equals(WIFI_CA_NOT_VALIDATE) | |
|| caCert.equals(WIFI_CA_UNSPECIFIED)) { | |
// ca_cert already set to null, so do nothing. | |
} else if (caCert.equals(WIFI_CA_USE_SYSTEM)) { | |
setCaPath(config.enterpriseConfig, SYSTEM_CA_STORE_PATH); | |
} else { | |
setCaCertificateAliases(config.enterpriseConfig, new String[]{caCert}); | |
} | |
// Only set OCSP option if there is a valid CA certificate. | |
if (caCert.equals(WIFI_CA_NOT_VALIDATE) | |
|| caCert.equals(WIFI_CA_UNSPECIFIED)) { | |
setOcsp(config.enterpriseConfig, 0);//WifiEnterpriseConfig.OCSP_NONE | |
} else { | |
int certificateStatus = StringUtil.parseInt(certificateStatusStr, -1); | |
if (certificateStatus == -1) { | |
Log.e(TAG, "Unknown eapMethod certificateStatus:[" + certificateStatusStr + "]"); | |
return false; | |
} | |
setOcsp(config.enterpriseConfig, certificateStatus); | |
} | |
if (StringUtil.isBlank(clientCert) || clientCert.equals(WIFI_CA_UNSPECIFIED) | |
|| clientCert.equals(WIFI_CA_NOT_VALIDATE)) { | |
// Note: |clientCert| should not be able to take the value |unspecifiedCert|, | |
// since we prevent such configurations from being saved. | |
clientCert = ""; | |
} | |
setClientCertificateAlias(config.enterpriseConfig, clientCert); | |
if (eapMethod == Eap.SIM || eapMethod == Eap.AKA || eapMethod == Eap.AKA_PRIME) { | |
config.enterpriseConfig.setIdentity(""); | |
config.enterpriseConfig.setAnonymousIdentity(""); | |
} else if (eapMethod == Eap.PWD) { | |
config.enterpriseConfig.setIdentity(identity); | |
config.enterpriseConfig.setAnonymousIdentity(""); | |
} else { | |
config.enterpriseConfig.setIdentity(identity); | |
config.enterpriseConfig.setAnonymousIdentity(anonymousIdentity); | |
} | |
config.enterpriseConfig.setPassword(password); | |
break; | |
case WifiEntry.SECURITY_SAE: | |
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { | |
setSecurityParams(config, WifiConfiguration.SECURITY_TYPE_SAE); | |
} | |
config.preSharedKey = '"' + password + '"'; | |
break; | |
case WifiEntry.SECURITY_OWE: | |
setSecurityParams(config, WifiConfiguration.SECURITY_TYPE_OWE); | |
break; | |
case WifiEntry.SECURITY_WAPI_PSK: | |
config.allowedProtocols.set(WifiConfiguration.Protocol.WAPI); | |
config.allowedKeyManagement.set(13);//WifiConfiguration.KeyMgmt.WAPI_PSK | |
if (StringUtil.isNotBlank(password)) { | |
int wapiPskType = StringUtil.parseInt(wapiPskTypeStr, 0); | |
if (wapiPskType == WAPI_PSK_TYPE_ASCII) | |
config.preSharedKey = '"' + password + '"'; | |
else | |
config.preSharedKey = password; | |
} | |
break; | |
case WifiEntry.SECURITY_WAPI_CERT: | |
config.allowedProtocols.set(WifiConfiguration.Protocol.WAPI); | |
config.allowedKeyManagement.set(14);//WifiConfiguration.KeyMgmt.WAPI_CERT | |
config.enterpriseConfig.setEapMethod(Eap.WAPI_CERT); | |
//if auto select wapi cert | |
if (StringUtil.isBlank(wapiCert)) { | |
wapiCert = "auto"; | |
} | |
setWapiCertSuite(config.enterpriseConfig, wapiCert); | |
break; | |
default: | |
return false; | |
} | |
int netId = -1; | |
removeWifi(ssid);//删除旧的wifi | |
netId = wifiManager.addNetwork(config); | |
if (default_wifi) { | |
wifiManager.enableNetwork(netId, true); | |
} | |
if (netId == -1) { | |
Log.w(TAG, "add net work failed. netId == -1"); | |
return false; | |
} | |
return true; | |
} | |
@SuppressLint("MissingPermission") | |
public boolean removeWifi(String ssid) { | |
boolean r = true; | |
List<WifiConfiguration> wifiConfigurationList = wifiManager.getConfiguredNetworks(); | |
for (WifiConfiguration wifiConfiguration : wifiConfigurationList) { | |
if (StringUtil.equal(ssid, wifiConfiguration.SSID)) { | |
r = r && wifiManager.removeNetwork(wifiConfiguration.networkId); | |
} | |
} | |
return r; | |
} | |
@SuppressLint("MissingPermission") | |
private WifiConfiguration getExitsWifiConfig(String SSID) { | |
List<WifiConfiguration> wifiConfigurationList = wifiManager.getConfiguredNetworks(); | |
for (WifiConfiguration wifiConfiguration : wifiConfigurationList) { | |
if (wifiConfiguration.SSID.equals("\"" + SSID + "\"")) { | |
return wifiConfiguration; | |
} | |
} | |
return null; | |
} | |
/* 设置添加WiFi高级 - 隐私(随机MAC)*/ | |
private void setMacRandomizationSetting(WifiConfiguration config, int privacy) { | |
Field[] fields = config.getClass().getDeclaredFields(); | |
if (null != fields) { | |
for (Field field : fields) { | |
try { | |
if (field.getName().equals("macRandomizationSetting")) { | |
field.set(config, privacy); | |
} | |
} catch (Exception e) { | |
e.printStackTrace(); | |
Log.w(TAG, "addWifi macRandomizationSetting -->error:" + e); | |
} | |
} | |
} | |
} | |
public void setCaCertificateAliases(WifiEnterpriseConfig config, String[] aliases) { | |
try { | |
ReflectionTool.invokeDynamicVoidMethod(config, "setCaCertificateAliases", new Class[]{String[].class}, new Object[]{aliases}); | |
} catch (Exception e) { | |
Log.w(TAG, "setCaCertificateAliases falied.", e); | |
} | |
} | |
private void setCaPath(WifiEnterpriseConfig config, String path) { | |
try { | |
ReflectionTool.invokeDynamicVoidMethod(config, "setCaPath", new Class[]{String.class}, new Object[]{path}); | |
} catch (Exception e) { | |
Log.w(TAG, "setCaPath falied.", e); | |
} | |
} | |
/** | |
* 设置在线证书状态 | |
* | |
* @param config | |
* @param ocsp | |
*/ | |
private void setOcsp(WifiEnterpriseConfig config, int ocsp) { | |
try { | |
ReflectionTool.invokeDynamicVoidMethod(config, "setOcsp", new Class[]{int.class}, new Object[]{ocsp}); | |
} catch (Exception e) { | |
Log.w(TAG, "setOcsp falied.", e); | |
} | |
} | |
private void setSecurityParams(WifiConfiguration config, int securityType) { | |
try { | |
ReflectionTool.invokeDynamicVoidMethod(config, "setSecurityParams", new Class[]{int.class}, new Object[]{securityType}); | |
} catch (Exception e) { | |
Log.w(TAG, "setSecurityParams falied.", e); | |
} | |
} | |
private void setClientCertificateAlias(WifiEnterpriseConfig config, String alias) { | |
try { | |
ReflectionTool.invokeDynamicVoidMethod(config, "setClientCertificateAlias", new Class[]{String.class}, new Object[]{alias}); | |
} catch (Exception e) { | |
Log.w(TAG, "setClientCertificateAlias falied.", e); | |
} | |
} | |
private void setWapiCertSuite(WifiEnterpriseConfig config, String wapiCertSuite) { | |
try { | |
ReflectionTool.invokeDynamicVoidMethod(config, "setWapiCertSuite", new Class[]{String.class}, new Object[]{wapiCertSuite}); | |
} catch (Exception e) { | |
Log.w(TAG, "setWapiCertSuite falied.", e); | |
} | |
} | |
private class WifiEntry { | |
public static final int SECURITY_NONE = 0; | |
public static final int SECURITY_WEP = 1; | |
public static final int SECURITY_PSK = 2; | |
public static final int SECURITY_EAP = 3; | |
public static final int SECURITY_OWE = 4; | |
public static final int SECURITY_SAE = 5; | |
public static final int SECURITY_EAP_SUITE_B = 6; | |
public static final int SECURITY_DPP = 7; | |
public static final int SECURITY_WAPI_PSK = 8; | |
public static final int SECURITY_WAPI_CERT = 9; | |
public static final int NUM_SECURITY_TYPES = 10; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment