SSL handshake error on self-signed cert in Flutter

18,865

Solution 1

I used HttpClient.badCertificateCallback
Here is a code to accept any cert:

_client = new HttpClient();
_client.badCertificateCallback = (X509Certificate cert, String host, int port) => true;

Solution 2

You can get a valid SSL certificate for free from https://letsencrypt.org/

Solution 3

In my case I got this error message, because I did not specify hostname when asked for Common Name, when creating self signed certificate (localhost is OK for simple tests):

$ openssl req -x509 -sha256 -nodes -days 365 -newkey rsa:2048 -keyout privateKey.key -out certificate.pem

Country Name (2 letter code) [AU]:SI
State or Province Name (full name) [Some-State]:
Locality Name (eg, city) []:
Organization Name (eg, company) [Internet Widgits Pty Ltd]:
Organizational Unit Name (eg, section) []:
Common Name (e.g. server FQDN or YOUR name) []:localhost
Email Address []:
Share:
18,865

Related videos on Youtube

Armen Kh.
Author by

Armen Kh.

Updated on September 15, 2022

Comments

  • Armen Kh.
    Armen Kh. over 1 year

    I'm trying to connect server with self-signed cert, but I take error:
    E/flutter ( 3781): HandshakeException: Handshake error in client (OS Error:
    E/flutter ( 3781): CERTIFICATE_VERIFY_FAILED: Hostname mismatch(ssl_cert.c:345))
    Code, where I set cert:

    String path = '/storage/sdcard0/server.crt';
    SecurityContext context = new SecurityContext();
    context.setTrustedCertificates(path, password: 'hello');
    _client = new HttpClient(context: context);
    

    What I'm doing wrong?

    If I don't set SecurityContext, I get SSL handshake error.

  • Armen Kh.
    Armen Kh. over 6 years
    Thanks. Is there any variant to set something like "trust to all certificates" like in java?
  • Collin Jackson
    Collin Jackson over 6 years
    See the other answer. I do wonder, why encrypt if you don't want security -- I can think of a few reasons, but can't tell from your question.
  • Armen Kh.
    Armen Kh. over 6 years
    I'm using self-signed cert for development and in this moment no need to use real certs. HttpClient works with sites with valid certs, I have no problem with them.
  • tylkonachwile
    tylkonachwile over 5 years
    @ArmenKH. which web server you use?
  • Dmitrii Bocharov
    Dmitrii Bocharov over 5 years
    It works, but it doesn't reply to the original question. Accepting all certificates is a bad choice. I bumped into the same problem, and can't understand why setting "setTrustedCertificates" doesn't work.
  • Aashutosh Rathi
    Aashutosh Rathi about 3 years
    certbot is such an underrate tool.
  • wamae
    wamae over 2 years
    I agree with @DmitriiBocharov