android 无法验证证书签名?

sg3maiej  于 2022-11-20  发布在  Android
关注(0)|答案(6)|浏览(410)

我使用SSL套接字和信任管理器从这一边Self signed SSL
但我一直得到以下错误:
2009年9月28日19时52分41秒警告/系统错误(10101):javax.net.ssl.SSLHandshakeException:异常。外部证书路径验证器异常:无法验证证书签名。
怎么了?我已经检查了不同的stackoverflow的帖子,但我似乎不能让它工作。
我的代码:

SchemeRegistry schemeRegistry = new SchemeRegistry();

// http scheme

schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

// https scheme

schemeRegistry.register(new Scheme("https", new EasySSLSocketFactory(), 443));
params = new BasicHttpParams();
params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 1);
params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(1));
params.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, false);
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, "utf8");
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(new AuthScope("www.example.com", AuthScope.ANY_PORT),
    new UsernamePasswordCredentials("user", "password"));
clientConnectionManager = new ThreadSafeClientConnManager(params, schemeRegistry);
context = new BasicHttpContext();
context.setAttribute("http.auth.credentials-provider", credentialsProvider);

DefaultHttpClient client = new DefaultHttpClient(clientConnectionManager, params);

HttpGet get = new HttpGet("https://www.example.com/web/restricted/form/formelement=512663");
HttpResponse response = client.execute(get, context);

Log.w("Response ","Status line : "+ response.toString());
ycl3bljg

ycl3bljg1#

正如Michael Levy提到的,我遇到这个异常的原因是我让我的Android模拟器打开了几天,时钟变得非常不同步。一旦我重新启动模拟器,异常就消失了。

yqlxgs2m

yqlxgs2m2#

很可能是服务器返回的证书链中包含您不信任的颁发机构。(意味着:您的设备不知道授权证书是否可信)解决方案:仔细检查来自HTTPS网站的证书,并将相应的授权添加到您的信任库中-但这部分似乎很棘手
(这里有些解释:(第10页)

k2fxgqgv

k2fxgqgv3#

更新
我还在API 16模拟器上遇到了另一个错误:
程序:SSL23_GET_SERVER_HELLO:tlsv 1警报协议版本(外部/openssl/ssl/s23_clnt.c:741)。
在阅读12时,我更改了代码:

val okHttpClient = getOkHttpBuilder().build()

private fun getOkHttpBuilder(): OkHttpClient.Builder {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
        Security.insertProviderAt(Conscrypt.newProvider(), 1)
    }
    return OkHttpClient().newBuilder()
}

// build.gradle:
implementation 'org.conscrypt:conscrypt-android:2.5.1'

但是library增加了3.4Mb的apk。
我还从MyApplication中删除了以下行:

try {
    ProviderInstaller.installIfNeeded(applicationContext)
    val sslContext = SSLContext.getInstance("TLSv1.2")
    sslContext.init(null, null, null)
    sslContext.createSSLEngine()
} catch (e: GooglePlayServicesRepairableException) {
    Timber.e(e.stackTraceToString())
    // Prompt the user to install/update/enable Google Play services.
    GoogleApiAvailability.getInstance().showErrorNotification(this, e.connectionStatusCode)
} catch (e: GooglePlayServicesNotAvailableException) {
    Timber.e(e.stackTraceToString())
    // Prompt the user to install/update/enable Google Play services.
    // GoogleApiAvailability.getInstance().showErrorNotification(this, e.errorCode)
} catch (e: NoSuchAlgorithmException) {
    Timber.e(e.stackTraceToString())
} catch (e: KeyManagementException) {
    Timber.e(e.stackTraceToString())
}

===旧答案===
在我的例子中,在Android 4和5上出现了以下错误:
导致的错误:无法验证证书:证书于2020年5月30日星期六10:48:38 GMT+00:00过期(与2020年8月13日星期四11:47:00 GMT+00:00相比)
...
原因:java.security.cert.证书过期异常:证书于2020年5月30日星期六10:48:38 GMT+00:00过期(与2020年8月13日星期四11:47:00 GMT+00:00相比)
服务器有证书错误(可能已过期)。
对于Retrofit,请参见https://stackoverflow.com/a/60507560/2914140。如果将Fuel用作REST库,请参见kotlin library that can do httpS connection without certificate verification (like curl --insecure)
您可以信任所有证书,但这很危险。

import java.security.SecureRandom
import java.security.cert.X509Certificate
import javax.net.ssl.*
import javax.security.cert.CertificateException

companion object {

    private val gson: Gson
    private val retrofit: Retrofit

    init {

        val okHttpClient = getOkHttpBuilder().build()

        gson = GsonBuilder().setLenient().create()

        retrofit = Retrofit.Builder()
            .baseUrl(BASE_URL)
            .client(okHttpClient)
            .addConverterFactory(GsonConverterFactory.create(gson))
            .build()
    }

    private fun getOkHttpBuilder(): OkHttpClient.Builder =
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            OkHttpClient().newBuilder()
        } else {
            getUnsafeOkHttpClient()
        }

    private fun getUnsafeOkHttpClient(): OkHttpClient.Builder =
        try {
            // Create a trust manager that does not validate certificate chains
            val trustAllCerts: Array<TrustManager> = arrayOf(
                object : X509TrustManager {
                    @Throws(CertificateException::class)
                    override fun checkClientTrusted(chain: Array<X509Certificate?>?,
                                                    authType: String?) = Unit

                    @Throws(CertificateException::class)
                    override fun checkServerTrusted(chain: Array<X509Certificate?>?,
                                                    authType: String?) = Unit

                    override fun getAcceptedIssuers(): Array<X509Certificate> = arrayOf()
                }
            )
            // Install the all-trusting trust manager
            val sslContext: SSLContext = SSLContext.getInstance("SSL")
            sslContext.init(null, trustAllCerts, SecureRandom())
            // Create an ssl socket factory with our all-trusting manager
            val sslSocketFactory: SSLSocketFactory = sslContext.socketFactory
            val builder = OkHttpClient.Builder()
            builder.sslSocketFactory(sslSocketFactory,
                trustAllCerts[0] as X509TrustManager)
            builder.hostnameVerifier { _, _ -> true }
            builder
        } catch (e: Exception) {
            throw RuntimeException(e)
        }
}

另请参阅https://stackoverflow.com/a/60507560/2914140了解Android版本检查和Glide连接。

ulydmbyx

ulydmbyx4#

顺便说一句,我们可以很容易地重现这个错误--只要把手机的日期改为几年后。
注意:错误可能在不同的手机上会有一点不同。有些可能会显示证书已经过期。

4szc88ey

4szc88ey5#

检查设备的时间,更正后再次检查。

j8ag8udp

j8ag8udp6#

看起来器械的日期/时间错误

相关问题