Iam有这个奇怪的问题,其中改装不断抛弃我
“SSL握手中止:ssl = 0x618d9c18:系统调用期间的I / O错误, 连接由同行重置“
在kitkat中,而相同的代码在棒棒糖设备中正常工作。我使用OkHttpClient客户端,如下所示
public OkHttpClient getUnsafeOkHttpClient() {
try {
final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
@Override
public void checkClientTrusted(
java.security.cert.X509Certificate[] chain,
String authType) {
}
@Override
public void checkServerTrusted(
java.security.cert.X509Certificate[] chain,
String authType) {
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[0];
}
} };
int cacheSize = 10 * 1024 * 1024; // 10 MB
Cache cache = new Cache(getCacheDir(), cacheSize);
final SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
sslContext.init(null, trustAllCerts,
new java.security.SecureRandom());
final SSLSocketFactory sslSocketFactory = sslContext
.getSocketFactory();
OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient = okHttpClient.newBuilder()
.cache(cache)
.sslSocketFactory(sslSocketFactory)
.hostnameVerifier(org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER).build();
return okHttpClient;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
我在这样的改造中使用这个客户端
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(URL)
.client(getUnsafeOkHttpClient())
.addConverterFactory(GsonConverterFactory.create())
.build();
编辑:添加getUnsafeOkHttpClient()
在此处无效,并且根本不建议使用getUnsafeOkHttpClient()
仅供参考:问题是因为api端点仅支持 TLS 1.2
,默认情况下已在Android设备 16<device<20
上停用。因此,对于 16<device<20
,请创建自定义SSLSocketFactory
答案 0 :(得分:20)
最后找到了解决这个问题的方法,它不是一个完整的解决方案,因为它是来自 okhttp,square Jesse Wilson的here提到的黑客攻击。正如我所提到的,这是一个简单的黑客,我必须将我的 SSLSocketFactory 变量重命名为
private SSLSocketFactory delegate;
请注意,如果您提供除委托之外的任何名称,则会抛出错误。我在下面发布完整的解决方案
这是我的 TLSSocketFactory 类
public class TLSSocketFactory extends SSLSocketFactory {
private SSLSocketFactory delegate;
public TLSSocketFactory() throws KeyManagementException, NoSuchAlgorithmException {
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, null, null);
delegate = context.getSocketFactory();
}
@Override
public String[] getDefaultCipherSuites() {
return delegate.getDefaultCipherSuites();
}
@Override
public String[] getSupportedCipherSuites() {
return delegate.getSupportedCipherSuites();
}
@Override
public Socket createSocket() throws IOException {
return enableTLSOnSocket(delegate.createSocket());
}
@Override
public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException {
return enableTLSOnSocket(delegate.createSocket(s, host, port, autoClose));
}
@Override
public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
return enableTLSOnSocket(delegate.createSocket(host, port));
}
@Override
public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException, UnknownHostException {
return enableTLSOnSocket(delegate.createSocket(host, port, localHost, localPort));
}
@Override
public Socket createSocket(InetAddress host, int port) throws IOException {
return enableTLSOnSocket(delegate.createSocket(host, port));
}
@Override
public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException {
return enableTLSOnSocket(delegate.createSocket(address, port, localAddress, localPort));
}
private Socket enableTLSOnSocket(Socket socket) {
if(socket != null && (socket instanceof SSLSocket)) {
((SSLSocket)socket).setEnabledProtocols(new String[] {"TLSv1.1", "TLSv1.2"});
}
return socket;
}
}
这就是我用okhttp和改装
的方式 OkHttpClient client=new OkHttpClient();
try {
client = new OkHttpClient.Builder()
.sslSocketFactory(new TLSSocketFactory())
.build();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build();
您也可以查看this for more info
答案 1 :(得分:3)
我在这里获得了api.data.gov.in的SSL / TLS信息 - https://www.ssllabs.com/ssltest/analyze.html?d=api.data.gov.in
它看起来只支持TLSv1.2。旧的Android版本确实存在最新TLS版本的问题。在&#34;握手模拟&#34;在ssllabs页面上你甚至可以看到你的问题。
有关可用的解决方案,请参阅How to enable TLS 1.2 support in an Android application (running on Android 4.1 JB)。
答案 2 :(得分:3)
我修改了@Navneet Krishna答案,因为方法OkHttpClient.Builder。 builder.sslSocketFactory(tlsSocketFactory)现在已弃用。
public class TLSSocketFactory extends SSLSocketFactory {
private final SSLSocketFactory delegate;
private TrustManager[] trustManagers;
@Inject
public TLSSocketFactory() throws KeyStoreException, KeyManagementException, NoSuchAlgorithmException {
generateTrustManagers();
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, trustManagers, null);
delegate = context.getSocketFactory();
}
private void generateTrustManagers() throws KeyStoreException, NoSuchAlgorithmException {
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init((KeyStore) null);
TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
throw new IllegalStateException("Unexpected default trust managers:"
+ Arrays.toString(trustManagers));
}
this.trustManagers = trustManagers;
}
@Override
public String[] getDefaultCipherSuites() {
return delegate.getDefaultCipherSuites();
}
@Override
public String[] getSupportedCipherSuites() {
return delegate.getSupportedCipherSuites();
}
@Override
public Socket createSocket() throws IOException {
return enableTLSOnSocket(delegate.createSocket());
}
@Override
public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException {
return enableTLSOnSocket(delegate.createSocket(s, host, port, autoClose));
}
@Override
public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
return enableTLSOnSocket(delegate.createSocket(host, port));
}
@Override
public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException, UnknownHostException {
return enableTLSOnSocket(delegate.createSocket(host, port, localHost, localPort));
}
@Override
public Socket createSocket(InetAddress host, int port) throws IOException {
return enableTLSOnSocket(delegate.createSocket(host, port));
}
@Override
public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException {
return enableTLSOnSocket(delegate.createSocket(address, port, localAddress, localPort));
}
private Socket enableTLSOnSocket(Socket socket) {
if (socket instanceof SSLSocket) {
((SSLSocket) socket).setEnabledProtocols(new String[]{"TLSv1.1", "TLSv1.2"});
}
return socket;
}
@Nullable
public X509TrustManager getTrustManager() {
return (X509TrustManager) trustManagers[0];
}
}
您需要这样分配:
TLSSocketFactory tlsTocketFactory = new TLSSocketFactory();
client = new OkHttpClient.Builder()
.sslSocketFactory(tlsSocketFactory, tlsSocketFactory.getTrustManager());
.build();
答案 3 :(得分:2)
除了Navneet Krishna,我必须在我的应用程序课程中进行下一步:
ProviderInstaller.installIfNeededAsync
根据https://developer.android.com/training/articles/security-gms-provider,这是因为我需要更新安全提供程序以防止SSL攻击。
我的应用类:
public class AppClass extends MultiDexApplication {
private static final String TAG = AppClass.class.getName();
private static Context context;
private static AuthAPI authAPI;
private static RestAPI buyersAPI;
@Override
public void onCreate() {
super.onCreate();
/* enable SSL compatibility in pre-lollipop devices */
upgradeSecurityProvider();
createAuthAPI();
createRestAPI();
}
private void upgradeSecurityProvider() {
try{
ProviderInstaller.installIfNeededAsync(this, new ProviderInstaller.ProviderInstallListener() {
@Override
public void onProviderInstalled() {
Log.e(TAG, "New security provider installed.");
}
@Override
public void onProviderInstallFailed(int errorCode, Intent recoveryIntent) {
GooglePlayServicesUtil.showErrorNotification(errorCode, BuyersApp.this);
Log.e(TAG, "New security provider install failed.");
}
});
}catch (Exception ex){
Log.e(TAG, "Unknown issue trying to install a new security provider", ex);
}
}
private void createAuthAPI() {
OkHttpClient.Builder authAPIHttpClientBuilder = new OkHttpClient.Builder();
Retrofit retrofit = new Retrofit.Builder()
.client(enableTls12OnPreLollipop(authAPIHttpClientBuilder).build())
.baseUrl(DomainLoader.getInstance(context).getAuthDomain())
.addConverterFactory(GsonConverterFactory.create())
.build();
authAPI = retrofit.create(AuthAPI.class);
}
private static OkHttpClient.Builder enableTls12OnPreLollipop(OkHttpClient.Builder client) {
if (Build.VERSION.SDK_INT >= 19 && Build.VERSION.SDK_INT < 22) {
try {
SSLContext sc = SSLContext.getInstance("TLSv1.2");
sc.init(null, null, null);
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(
TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init((KeyStore) null);
TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
throw new IllegalStateException("Unexpected default trust managers:"
+ Arrays.toString(trustManagers));
}
X509TrustManager trustManager = (X509TrustManager) trustManagers[0];
client.sslSocketFactory(new Tls12SocketFactory(sc.getSocketFactory()), trustManager);
ConnectionSpec cs = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
.tlsVersions(TlsVersion.TLS_1_2)
.build();
List<ConnectionSpec> specs = new ArrayList<>();
specs.add(cs);
specs.add(ConnectionSpec.COMPATIBLE_TLS);
specs.add(ConnectionSpec.CLEARTEXT);
client.connectionSpecs(specs);
} catch (Exception exc) {
Log.e("OkHttpTLSCompat", "Error while setting TLS 1.2", exc);
}
}
return client;
}
private void createRestAPI() {
OkHttpClient.Builder restAPIHttpClientBuilder = new OkHttpClient.Builder();
buyersAPIHttpClientBuilder.readTimeout(60, TimeUnit.SECONDS);
buyersAPIHttpClientBuilder.connectTimeout(60, TimeUnit.SECONDS);
buyersAPIHttpClientBuilder.writeTimeout(600, TimeUnit.SECONDS);
buyersAPIHttpClientBuilder.addInterceptor(new NetworkErrorInterceptor());
buyersAPIHttpClientBuilder.addInterceptor(new TokenVerificationInterceptor());
Retrofit retrofit = new Retrofit.Builder()
.client(enableTls12OnPreLollipop(restAPIHttpClientBuilder).build())
.baseUrl(DomainLoader.getInstance(context).getDomain())
.addConverterFactory(GsonConverterFactory.create(new GsonBuilder().setLenient().create()))
.addConverterFactory(ScalarsConverterFactory.create())
.build();
buyersAPI = retrofit.create(RestAPI.class);
}
}
和我的Tls12SocketFactory类:
public class Tls12SocketFactory extends SSLSocketFactory {
private static final String[] TLS_V12_ONLY = {"TLSv1.2"};
final SSLSocketFactory delegate;
public Tls12SocketFactory(SSLSocketFactory base) {
this.delegate = base;
}
@Override
public String[] getDefaultCipherSuites() {
return delegate.getDefaultCipherSuites();
}
@Override
public String[] getSupportedCipherSuites() {
return delegate.getSupportedCipherSuites();
}
@Override
public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException {
return patch(delegate.createSocket(s, host, port, autoClose));
}
@Override
public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
return patch(delegate.createSocket(host, port));
}
@Override
public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException, UnknownHostException {
return patch(delegate.createSocket(host, port, localHost, localPort));
}
@Override
public Socket createSocket(InetAddress host, int port) throws IOException {
return patch(delegate.createSocket(host, port));
}
@Override
public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException {
return patch(delegate.createSocket(address, port, localAddress, localPort));
}
private Socket patch(Socket s) {
if (s instanceof SSLSocket) {
((SSLSocket) s).setEnabledProtocols(TLS_V12_ONLY);
}
return s;
}
}
它在KitKat及以上版本的所有设备上都像魅力一样。
答案 4 :(得分:0)
我认为我的解决方案可能会对某人有所帮助。
在我的项目中,我需要在较旧的Android(4.4)上通过SSL进行JSON请求,并且一直遇到线程顶部提到的问题。
要解决此问题,我要做的就是完全像上面那样添加Tls12SocketFactory类。
但是,我在项目类中添加了修改后的代码
我将此添加到了oncreate
upgradeSecurityProvider();
并如下修改上下文的功能,仅此而已。不再有SSL连接问题
private void upgradeSecurityProvider() {
try{
ProviderInstaller.installIfNeededAsync(this, new ProviderInstaller.ProviderInstallListener() {
@Override
public void onProviderInstalled() {
Log.e("SSLFix", "New security provider installed.");
}
@Override
public void onProviderInstallFailed(int errorCode, Intent recoveryIntent) {
// GooglePlayServicesUtil.showErrorNotification(errorCode, BuyersApp.this);
Log.e("SSLFix", "New security provider install failed.");
}
});
}catch (Exception ex){
Log.e("SSLFix", "Unknown issue trying to install a new security provider", ex);
}
}
仅此而已,没有其他问题。
答案 5 :(得分:0)
在我的案例中,我只是在build.gradle(模块应用程序)中添加了一个依赖项,并将代码添加到我的第一个活动中解决了我的问题。 依赖关系:
implementation 'com.google.android.gms:play-services-base:11.0.0'
我的代码:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN
&& Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
try {
ProviderInstaller.installIfNeeded(this);
} catch (GooglePlayServicesRepairableException e) {
GooglePlayServicesUtil.showErrorNotification(e.getConnectionStatusCode(), this);
return;
} catch (GooglePlayServicesNotAvailableException e) {
return;
}
}
此问题在以下棒棒糖版本中出现。默认情况下,TLS未启用,因此必须以编程方式启用。