Flutter handshakeexception handshake error in client (os error certificate_verify_failed

Explanation:

The error message “HandshakeException: Handshake error in client (OS Error: certificate_verify_failed)” usually occurs in Flutter when there is an issue verifying the SSL certificate of the server you are trying to connect to. This error commonly happens when the SSL certificate of the server is self-signed or not trusted by the device or system where the Flutter app is running.

To fix this issue, you can either disable the certificate verification temporarily (not recommended for production use) or add the necessary trusted certificates to your Flutter app’s trusted certificate store.

Option 1: Disable Certificate Verification


  import 'dart:io';

  void main() {
    // ...

    // Add this line before making the HTTP request
    HttpOverrides.global = new MyHttpOverrides();

    // Make the HTTP request
    // ...
  }

  class MyHttpOverrides extends HttpOverrides {
    @override
    HttpClient createHttpClient(SecurityContext? context) {
      return super.createHttpClient(context)
        ..badCertificateCallback = (X509Certificate cert, String host, int port) => true;
    }
  }
  

Please note that disabling certificate verification is not secure and should only be done for testing or debugging purposes.

Option 2: Add Trusted Certificates

To add trusted certificates, you need to obtain the server’s SSL certificate and add it to your app’s trusted certificate store.

  • Download the server’s SSL certificate.
  • Create a folder named “certificates” in your Flutter project (next to lib/ and android/ folders).
  • Copy the SSL certificate file to the “certificates” folder (e.g., server.crt).
  • Update your Flutter project’s pubspec.yaml file to include the certificate file:

  flutter:
    assets:
      - certificates/server.crt
  

Use the SSL certificate in your HTTP request code:


  import 'dart:io';

  void main() async {
    // ...

    // Load the SSL certificate
    SecurityContext securityContext = new SecurityContext();
    securityContext.setTrustedCertificates('certificates/server.crt');

    // Make the HTTP request
    HttpClient httpClient = new HttpClient(context: securityContext);
    HttpClientRequest request = await httpClient.getUrl(Uri.parse('https://example.com/api'));
    HttpClientResponse response = await request.close();

    // Handle the response
    String responseBody = await response.transform(utf8.decoder).join();
    print(responseBody);

    // ...
  }
  

Replace ‘https://example.com/api’ with the actual URL of the server you are trying to connect to.

By adding the SSL certificate to your Flutter app’s trusted certificate store, you are instructing Flutter to trust the specified certificate, and the handshake error should be resolved.

Leave a comment