From 03a33fe8d70a4dab0dffdeb7b27c250ad239562a Mon Sep 17 00:00:00 2001 From: Simon Rozsival Date: Mon, 15 Jan 2024 15:45:39 +0100 Subject: [PATCH] Fix ServerCertificateCustomValidator on API 21-23 --- .../ServerCertificateCustomValidator.cs | 38 ++++++++++++++----- 1 file changed, 29 insertions(+), 9 deletions(-) diff --git a/src/Mono.Android/Xamarin.Android.Net/ServerCertificateCustomValidator.cs b/src/Mono.Android/Xamarin.Android.Net/ServerCertificateCustomValidator.cs index fdcec5d33e7..77427cfea10 100644 --- a/src/Mono.Android/Xamarin.Android.Net/ServerCertificateCustomValidator.cs +++ b/src/Mono.Android/Xamarin.Android.Net/ServerCertificateCustomValidator.cs @@ -5,6 +5,8 @@ using System.Net.Security; using System.Security.Cryptography.X509Certificates; +using Android.OS; +using Android.Runtime; using Javax.Net.Ssl; using JavaCertificateException = Java.Security.Cert.CertificateException; @@ -25,9 +27,9 @@ public ServerCertificateCustomValidator (Func (); + } + } } throw new InvalidOperationException($"Could not find {nameof(IX509TrustManager)} in {nameof(ITrustManager)} array."); + + static bool IsTrustManagerImpl (ITrustManager trustManager) + { + var javaClassName = JNIEnv.GetClassNameFromInstance (trustManager.Handle); + return javaClassName.Equals ("com/android/org/conscrypt/TrustManagerImpl", StringComparison.Ordinal); + } } - private static ITrustManager[] ModifyTrustManagersArray (ITrustManager[] trustManagers, IX509TrustManager original, IX509TrustManager replacement) + private static ITrustManager[] ModifyTrustManagersArray (ITrustManager[] trustManagers, int originalTrustManagerIndex, IX509TrustManager replacement) { var modifiedTrustManagersArray = new ITrustManager [trustManagers.Length]; for (int i = 0; i < trustManagers.Length; i++) { - if (trustManagers [i] == original) { + if (i == originalTrustManagerIndex) { modifiedTrustManagersArray [i] = replacement; } else { modifiedTrustManagersArray [i] = trustManagers [i]; } - } return modifiedTrustManagersArray;