Android上のXamarinアプリでSSL接続できない
XamarinというかMonoの問題?
XamarinはC#でAndroid/iOS向けアプリを作れて(Windows 10 mobileは死にました)、ライブラリも.NET Standardに対応させておけばWindowsデスクトップアプリとも共通化できる素晴らしいテクノロジー。
もっと流行ってほしい。
しかし、サーバーとSSLで通信するアプリを作ったところ問題が出た。
こんなコード:
try { using (var client = new TcpClient()) { client.Connect(hostName, port); using (var sslStream = new SslStream(client.GetStream(), false, (o, cert, chain, err) => true)) { sslStream.AuthenticateAsClient(hostName); Debug.WriteLine(sslStream.SslProtocol); } } } catch (Exception e) { Debug.WriteLine(e); if (e.InnerException != null) { Debug.WriteLine(e.InnerException); } }
sslStream.AuthenticateAsClientで例外。
System.IO.IOException: The authentication or decryption has failed. ---> System.IO.IOException: The authentication or decryption has failed. ---> Mono.Security.Protocol.Tls.TlsException: The authentication or decryption has failed.
new SslStreamの第三引数には本来は証明書を検証する関数を渡す必要があるんだけど、その関数を実行する前に落ちる。
Windowsだと普通に動く。
調べてみるとMonoのSSLの実装が古いとかTLSに未対応とかなんとか…?
forums.xamarin.com
いずれにせよAndroidプロジェクトの設定を変えれば良さげ。
プロジェクトの設定からAndroidオプション→詳細設定で
HttpClient実装とSSL/TLSの実装を変更。
これでOK。