The authentication or decryption has failed. in the web request

I'm using 'webclient' inorder to downloading info from my website and showing them on my android application, but in some devices I face with this error:

Exception in Class: WebClient
Line : 0
and Method:DownloadDataCore
with message Error getting response stream (Write: The authentication or decryption has failed.): SendFailure
Stack Trace: at System.Net.HttpWebRequest.EndGetResponse (IAsyncResult asyncResult) [0x00000] in :0
at System.Net.HttpWebRequest.GetResponse () [0x00000] in :0
at System.Net.WebClient.GetWebResponse (System.Net.WebRequest request) [0x00000] in :0
at System.Net.WebClient.ReadAll (System.Net.WebRequest request, System.Object userToken) [0x00000] in :0
at System.Net.WebClient.DownloadDataCore (System.Uri address, System.Object userToken) [0x00000] in :0

I searched about this and do not find any suitable answers. Just http://www.mono-project.com/UsingTrustedRootsRespectfully that I do not know how can be usefull for monondroid. Do any body faced with this error too?

«1

Posts

  • SKallSKall USMember ✭✭✭✭

    If the server is using secure HTTP, have you tried adding a handler for the callback handler?

    ServicePointManager.ServerCertificateValidationCallback += (o, certificate, chain, errors) => true;

  • JohnSRadJohnSRad FRMember ✭✭

    Thanks SKall, I do not not use the handler. Can you introduce me a sample in how to use it or a tutorial also can be helpful.
    Actually I do not know how can I use above line that you posted on muy application.

    Thanks

  • SKallSKall USMember ✭✭✭✭

    It is a static class so pretty much anywhere in the code as long as its in the scope of the web request.

    If you want to be sure just tag it inside Application:OnCreate override. If this fixes the issue then you should also look into the certificate info a little closer if you plan to release the application (I only use this to debug my local server which does not have a valid certification).

        [Application(Debuggable = true,
                     Label = "MyApp",
                     ManageSpaceActivity = typeof(Activity))]
        public class MyApp : Application
        {
            /// <summary>
            /// Initializes a new instance of the <see cref="DeviceApp"/> class.
            /// </summary>
            /// <param name="javaReference">
            /// The java reference.
            /// </param>
            /// <param name="transfer">
            /// The transfer.
            /// </param>
            public DeviceApp(IntPtr javaReference, JniHandleOwnership transfer)
                : base(javaReference, transfer)
            {
    
            }
    
            /// <summary>
            /// The on create.
            /// </summary>
            public override void OnCreate ()
            {
                System.Net.ServicePointManager.ServerCertificateValidationCallback += (o, certificate, chain, errors) => true;
                base.OnCreate ();
            }
        }
    
  • GerryHighGerryHigh USBeta ✭✭✭

    You might be seeing this error: https://bugzilla.xamarin.com/show_bug.cgi?id=13998

    I am seeing it is the alpha channel build 4.11.0 when running in release mode with link SDK assemblies.

    The hack workaround was to add System.Security.Cryptography.AesCryptoServiceProvider b = new System.Security.Cryptography.AesCryptoServiceProvider();

    so that the linker doesn't optimize it away.

  • OldRedthOldRedth USMember, Insider ✭✭✭

    Thanks @GerryHigh this workaround got me through the bug...

  • @GerryHigh can you please tell me where and how should I use this:
    System.Security.Cryptography.AesCryptoServiceProvider b = new System.Security.Cryptography.AesCryptoServiceProvider();

    I'm new to xamarin.android, so maybe I didn't catch what you said

    Regards

  • GerryHighGerryHigh USBeta ✭✭✭

    @alejandrowinkler I threw it in my MainApplication class but you can really put it anywhere so the linker doesn't remove it.

  • @GerryHigh, thanks for your reply, it still doesn't work for me. I'm trying to make a registration with Azure using NotificationHub, have you done something like this?

    here is the code where the app throw the exception

            try
            {
                var businessHubRegistration = await BusinessNotificationHub.RegisterNativeAsync(registrationId);
            }
            catch (Exception ex)
            {
                createNotification("businessHubRegistration", ex.Message);
            }
    
  • Ok, as nobody answer this I'm going to answer it myself: apparently Xamarin + Windows Azure doesn't work with Android API level 8.
    I tested the same code with API levels 10 and 18 and it works fine.

  • MelbourneDeveloperMelbourneDeveloper AUMember ✭✭✭

    I don't really see what this has to do with the exception being thrown.

    I'm getting this exception at the moment as well. Can we please change the question to: has anyone actually gotten WCF authentication to work with Xamarin?

  • BhimaniBhimani INMember
    edited March 2014

    Well I added both the code
    System.Net.ServicePointManager.ServerCertificateValidationCallback += (o, certificate, chain, errors) => true;
    and
    System.Security.Cryptography.AesCryptoServiceProvider b = new System.Security.Cryptography.AesCryptoServiceProvider();

    but no success.

    Here is my code. This code is part of a different project of type class library and its dll is reference into the main project.

    public void RequestChannelData(string url) { WebClient channelClient = new WebClient(); channelClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(channelClient_DownloadStringCompleted); System.Net.ServicePointManager.ServerCertificateValidationCallback += (o, certificate, chain, errors) => true; System.Security.Cryptography.AesCryptoServiceProvider b = new System.Security.Cryptography.AesCryptoServiceProvider(); channelClient.DownloadStringAsync(new System.Uri(url)); }
    void channelClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) { if (e != null) { if (e.Error == null) { OnDownloadCompanyCompletedAsync (ProcessCompanyXML (e.Result)); } else { OnDownloadError (e.Error); } } }

    I am using "https://www.googleapis.com/youtube/v3/channels?part=snippet,contentDetails,statistics,brandingSettings&amp;id=UC55IWqFLDH1Xp7iu1_xknRA,UC6-F5tO8uklgE9Zy8IvbdFw,UCpEhnqL0y41EpW2TvWAHD7Q,UC-LPIU24bQXVljUXivKEeRQ" as my url. Not sure where and what am I doing wrong. The link will return error in JSON data but that should not be the reason for exception since the URL did returned data.

    And here is the exception I am getting

    e.Error {System.Net.WebException: Error getting response stream (Write: The authentication or decryption has failed.): SendFailure ---> System.IO.IOException: The authentication or decryption has failed. ---> Mono.Security.Protocol.Tls.TlsException: The server stopped the handshake. at Mono.Security.Protocol.Tls.SslClientStream.SafeReceiveRecord (System.IO.Stream s, Boolean ignoreEmpty) [0x00000] in <filename unknown>:0 at Mono.Security.Protocol.Tls.SslClientStream.OnNegotiateHandshakeCallback (IAsyncResult asyncResult) [0x00000] in <filename unknown>:0 at Mono.Security.Protocol.Tls.SslStreamBase.AsyncHandshakeCallback (IAsyncResult asyncResult) [0x00000] in <filename unknown>:0 --- End of inner exception stack trace --- at Mono.Security.Protocol.Tls.SslStreamBase.AsyncHandshakeCallback (IAsyncResult asyncResult) [0x00000] in <filename unknown>:0 --- End of inner exception stack trace --- at System.Net.HttpWebRequest.EndGetResponse (IAsyncResult asyncResult) [0x00000] in <filename unknown>:0 at System.Net.HttpWebRequest.GetResponse () [0x00000] in <filename unknown>:0 at System.Net.WebClient.GetWebResponse (System.Net.WebRequest request) [0x00000] in <filename unknown>:0 at System.Net.WebClient.ReadAll (System.Net.WebRequest request, System.Object userToken) [0x00000] in <filename unknown>:0 at System.Net.WebClient.DownloadDataCore (System.Uri address, System.Object userToken) [0x00000] in <filename unknown>:0 } System.Net.WebException

  • RonitAhujaRonitAhuja INMember

    I am getting the same issue. Please reply the solution if you guys have fixed this. Will really appreciate any effort.

  • Sn3bSn3b BEMember

    Sorry I know this post is old but it just helped me fix my problem.

    For the ones who still don't have it working, maybe do this: change the first line to:

    ServicePointManager.ServerCertificateValidationCallback += CertificateValidationCallBack;

    And copy the method from this page: http://msdn.microsoft.com/en-us/library/office/dd633677(v=exchg.80).aspx

    Maybe you'll find more info :)

  • Hi Sn3b. I've had the same issue. I am new to Xamarin and Android, but I think the principle issue may be that the X509 Certificate needs to be approved/authenticated by a Google Play authorised body (whatever the correct wording is) for it to be accepted without complaint by Android.

    My temporary work-around was to accept the particular error thrown, but this compromises security. In my case this didn't matter too much as the App has no financial security function and was for a control system customer demo only.

  • EdHubbellEdHubbell USMember ✭✭

    FYI - I got this same error when initializing http client like this:

    HttpClient client = new HttpClient();
    

    but when I init like this, it works just fine:

    HttpClient client = new HttpClient(new NativeMessageHandler());
    
  • Sample code : still not working

    ServicePointManager.ServerCertificateValidationCallback += (o, certificate, chain, errors) => true; System.Security.Cryptography.AesCryptoServiceProvider b = new System.Security.Cryptography.AesCryptoServiceProvider(); WebRequest request = WebRequest.Create("https://some.server.com/"); HttpWebResponse response = (HttpWebResponse) request.GetResponse();

    System.Net.WebException: Error: SendFailure (Error writing headers) ---> System.Exception: Error writing headers ---> System.Exception: The authentication or decryption has failed. ---> System.Exception: The authentication or decryption has failed. at Mono.Security.Protocol.Tls.RecordProtocol.ProcessAlert (AlertLevel alertLevel, AlertDescription alertDesc) [0x00000] in <filename unknown>:0 at Mono.Security.Protocol.Tls.RecordProtocol.InternalReceiveRecordCallback (IAsyncResult asyncResult) [0x00000] in <filename unknown>:0 --- End of inner exception stack trace ---

    Need help please, i've tried every possible answer the internet has to offer.

  • amberamber USMember

    Hi,

    I am getting same error in mine monodroid application for following code,

    try {
    System.Net.ServicePointManager.ServerCertificateValidationCallback = (a, b, c, d) => { return true; };
    System.Net.WebRequest request = System.Net.HttpWebRequest.Create("https://realtime.built.io/");
    System.Net.HttpWebResponse response = (System.Net.HttpWebResponse) request.GetResponse();
    System.IO.Stream stream = response.GetResponseStream();
    System.IO.StreamReader sr = new System.IO.StreamReader(stream);
    strResponse = sr.ReadToEnd();
    sr.Close();
    sr.Dispose();
    stream.Dispose();
    } catch (System.IO.IOException ex) {
    throw ex;
    } catch (System.UriFormatException ex) {
    throw ex;
    }

    But, if I run same code to get "https://google.com" it is working fine. Anyone clue for this?

  • ThomasHuijzer.0458ThomasHuijzer.0458 USMember
    edited June 2015

    This isn't an answer, but know that if you are going to use
    ServicePointManager.ServerCertificateValidationCallback += (o, certificate, chain, errors) => true;
    your https connection will be just as insecure as a http connection.

  • For me the source of the problem was that the server certificate was not accepted by Android.
    I tried to fix it by installing the certificate but that did not work.
    Only after I installed the root certificate the problem was solved.

    So if your Root CA list on your Android device is not up to date go to you security settings and install the root certificate from your SD card.

    Note that Firefox uses it's own certificate store. So if you test a secure connection in Firefox you might get different results than testing it in the Android browser.

  • Taimoor.JanjuaTaimoor.Janjua DEMember ✭✭

    If I can access my Rest service through my mobile browser, than I should be able to consume my SSL based Rest service through my android phone. I am also getting the same error. Is this a bug in xamarin.forms? Help needed!

    InnerException {System.Net.WebException: Error writing headers ---> System.IO.IOException: Error while sending TLS Alert (Fatal:InternalError): System.IO.IOException: The authentication or decryption has failed. ---> System.IO.IOException: EndRead failure ---> System.Net.Sockets.SocketException: Connection reset by peer at System.Net.Sockets.Socket.EndReceive (IAsyncResult result) [0x00033] in <filename unknown>:0 at System.Net.Sockets.NetworkStream.EndRead (IAsyncResult ar) [0x0002f] in <filename unknown>:0 --- End of inner exception stack trace --- at System.Net.Sockets.NetworkStream.EndRead (IAsyncResult ar) [0x00048] in <filename unknown>:0 at Mono.Security.Protocol.Tls.RecordProtocol.InternalReceiveRecordCallback (IAsyncResult asyncResult) [0x00019] in <filename unknown>:0 --- End of inner exception stack trace --- at Mono.Security.Protocol.Tls.SslClientStream.EndNegotiateHandshake (IAsyncResult result) [0x0003b] in <filename unknown>:0 at Mono.Security.Protocol.Tls.SslStreamBase.AsyncHandshakeCallback (IAsyncResult asyncResult) [0x0000c] in <filename unknown>:0 ---> System.IO.IOException: The authentication or decryption has failed. ---> System.IO.IOException: EndRead failure ---> System.Net.Sockets.SocketException: Connection reset by peer at System.Net.Sockets.Socket.EndReceive (IAsyncResult result) [0x00033] in <filename unknown>:0 at System.Net.Sockets.NetworkStream.EndRead (IAsyncResult ar) [0x0002f] in <filename unknown>:0 --- End of inner exception stack trace --- at System.Net.Sockets.NetworkStream.EndRead (IAsyncResult ar) [0x00048] in <filename unknown>:0 at Mono.Security.Protocol.Tls.RecordProtocol.InternalReceiveRecordCallback (IAsyncResult asyncResult) [0x00019] in <filename unknown>:0 --- End of inner exception stack trace --- at Mono.Security.Protocol.Tls.SslClientStream.EndNegotiateHandshake (IAsyncResult result) [0x0003b] in <filename unknown>:0 at Mono.Security.Protocol.Tls.SslStreamBase.AsyncHandshakeCallback (IAsyncResult asyncResult) [0x0000c] in <filename unknown>:0 --- End of inner exception stack trace --- at System.Net.WebConnection.EndWrite (System.Net.HttpWebRequest request, Boolean throwOnError, IAsyncResult result) [0x000a7] in <filename unknown>:0 at System.Net.WebConnectionStream+<SetHeadersAsync>c__AnonStorey1.<>m__0 (IAsyncResult r) [0x00000] in <filename unknown>:0 --- End of inner exception stack trace ---} System.Net.WebException

  • Taimoor.JanjuaTaimoor.Janjua DEMember ✭✭

    that's my code for the rest service call,

    try {
    
                    if (!await IsConnected ())
                        throw new Exception ("");
    
                    var client = new HttpClient ();
                    var CancellationTokenSrc = new CancellationTokenSource (15000);
                    var token = CancellationTokenSrc.Token;
                    var serializedContent = JsonConvert.SerializeObject (Wrapper);
                    HttpContent httpContent = new StringContent (serializedContent, Encoding.UTF8, "application/json");
    
                    //IignoreCertificateError CertError = DependencyService.Get<IignoreCertificateError>();
                    //CertError.IgnoreCertError();
    
                    var response = await client.PostAsync(url, httpContent, token);
                    var responseString = await response.Content.ReadAsStringAsync ();
    
                    return await Task<DeviceResult>.Factory.StartNew (() => JsonConvert.DeserializeObject<DeviceResult> (responseString));
                }
                catch (Exception ex) {
                    throw new Exception ("Server konnte nicht erreicht werden. Bitte überprüfen Sie Ihre Einstellungen.");
                }
    
  • Taimoor.JanjuaTaimoor.Janjua DEMember ✭✭

    Hello All,

    Thanks for the help. I have solved my problem on my own. I wasn't generating the key properly for the encipherment and was using the wrong provider.

    Regards, Taimoor Janjua

  • FBATFBAT CAMember

    The solution provided by snb3 worked for me. Basically the web server was using a self-signed certificate and my application was not handling it properly. The code pointed by snb3 made it possible to accept the self-signed certificate.

  • MichaelHarenMichaelHaren USMember
    edited November 2015

    In my case I was seeing this issue when hitting a legit site. I found that that executing this on my box worked for me, via http://stackoverflow.com/a/11451213/29:
    mozroots --import --ask-remove

    This adds the root certs that most sites are chained to, which preserves security more than just accepting whatever cert you get.

  • Ross_BRoss_B USMember ✭✭

    I just starting getting this error all of a sudden...anyone else?

  • MarkLarterMarkLarter USMember

    Yep, same here. Stable channel, no updates recently.

  • tanujtanuj USMember

    @pierreshiraziefard have solved the problem

  • reshmapopupreshmapopup USUniversity

    Hi
    I am facing same kind of issues while integrating payment gateway & passing post params to webview. Xamarin.droid always throw me error Failed to Decrypt the application request. I tried each & every solution in this thread but nothing worked. I tried the same way in native android I am able to see the successs in transaction till last step.

    can anyone guide me on right path for this?Thanks in advance

  • ikiuxikiux USMember

    hi @ThomasHuijzer.0458

    I tried to make a HttpWebRequest with the following code, but does not work.
    Apparently when it used
    ServicePointManager.ServerCertificateValidationCallback + = delegate {return true; };
    works but I think it is not the way to implement it.
    and that any certificate I can put although not the same as the server and still works.
    I want to know if you know what my mistake or I need to implement the request as mobile certificate and the server is the same. thanks

    the certificate that i use is signed by CA

    X509Certificate2 cert;
    using (var s = Assets.Open("certificate.pfx"))
    {
    byte[] d = new byte[20480];
    s.Read(d, 0, d.Length);
    cert = new X509Certificate2(d, "test");
    }
    var request = WebRequest.Create(httpUrl) as HttpWebRequest;
    request.ClientCertificates.Add(cert);
    request.Method = "GET";
    request.ContentType = "application/json";

            try
            {
                using (var response = request.GetResponse())
                {
                    using (var reader = new StreamReader(response.GetResponseStream()))
                    {
                        string content = reader.ReadToEnd();
                    }
                }
            }
            catch(Exception ex)
            {
                string error = ex.ToString();
                throw ex;
            }
    

    Errror:

    System.Net.WebException: Error writing headers ---> System.IO.IOException: The authentication or decryption has failed. ---> Mono.Security.Protocol.Tls.TlsException: The authentication or decryption has failed.
    at Mono.Security.Protocol.Tls.RecordProtocol.EndReceiveRecord (IAsyncResult asyncResult) [0x0003a] in /Users/builder/data/lanes/3053/a94a03b5/source/mono/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/RecordProtocol.cs:430
    at Mono.Security.Protocol.Tls.SslClientStream.SafeEndReceiveRecord (IAsyncResult ar, Boolean ignoreEmpty) [0x00000] in /Users/builder/data/lanes/3053/a94a03b5/source/mono/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/SslClientStream.cs:285
    at Mono.Security.Protocol.Tls.SslClientStream.NegotiateAsyncWorker (IAsyncResult result) [0x00071] in /Users/builder/data/lanes/3053/a94a03b5/source/mono/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/SslClientStream.cs:447

  • SimoneAgostiniSimoneAgostini ITMember ✭✭

    Hello, did anyone find a solution?
    I get the same exact error.

    Thank you

  • MattCarterMattCarter USMember

    Also getting this issue using Microsoft.IdentityModel.Clients.ActiveDirectory

  • Patil2421Patil2421 USMember ✭✭✭

    @AlexanderGolde
    Solved the problem for me also - thank you !

  • @AdrienPadol Thank you so much your a life saver your solution worked like a charm

  • DylanLiuDylanLiu USUniversity ✭✭
    edited November 2016

    @EdHubbell said:
    FYI - I got this same error when initializing http client like this:

    HttpClient client = new HttpClient();
    

    but when I init like this, it works just fine:

    HttpClient client = new HttpClient(new NativeMessageHandler());
                
    

    var httpClient = new HttpClient(new NativeMessageHandler())
    Worked for me for a while, but now it's giving me this error:

    java.security.cert.CertPathValidatorException: Trust anchor for certification path not found

  • WilliamOrrWilliamOrr GBMember

    Having just spent four hours trawling for a solution to this problem, I finally noticed (and I feel like an idiot, but for the benefit of anyone making such a simple mistake)... I was using UriBuilder and passing port 80 for https scheme. It should of course be 443 for Secure HTTP.

  • ranjitrranjitr USMember ✭✭
    edited January 2017

    @DylanLiu I using modernhttpclient in my application and i am also facing the same error "Trust anchor for certification path not found" how did you mange to fix this I am stuck with it for days.

  • VetaLioSTVVetaLioSTV USMember ✭✭

    @ranjitr said:
    @DylanLiu I using modernhttpclient in my application and i am also facing the same error "Trust anchor for certification path not found" how did you mange to fix this I am stuck with it for days.

    Read this article.

    By the way,at first i have installed ModernHttpClient and problem was resolved.
    Than i have tried this snippet(from article) :
    HttpClient Request = new HttpClient(new Xamarin.Android.Net.AndroidClientHandler())
    Plus i have changed in options "HttpClient implementation" to => Managed(HttpClientHandler) , works great.
    Try it :smile: .

  • MSalihMSalih TRMember

    @AdrienPadol said:
    This is quite an old post, but for people still getting this, know that the answer of EdHubbel is correct.

    If you encounter this issue using the HttpClient class like this HttpClient client = new HttpClient();

    then install the "modernhttpclient" nuget package to your project (both PCL, and native projects), and then change your HttpClient class initialization to this:

    HttpClient client = new HttpClient(new NativeMessageHandler());

    The NativeMessageHandler class will handle for you these certificates issues

    "the authentication or decryption has failed." error is solved thanks

Sign In or Register to comment.