fluttersocketsmqttiotp12

Flutter setup MQTT with .p12 file


I am currently rebuilding an App using Flutter, in the old iOS and Android app, both would fetch the .p12 file from backend to setup the MQTT socket connection.

But the Flutter package I'm trying to use mqtt_client seems to require useCertificateChain, usePrivateKey and setClientAuthorities three files like this:

SecurityContext context = new SecurityContext()
  ..useCertificateChain('path/to/my_cert.pem')
  ..usePrivateKey('path/to/my_key.pem', password: 'key_password')
  ..setClientAuthorities('path/to/client.crt', password: 'password');
client.secure = true;
client.securityContext = context;

Code from: https://emqx.medium.com/using-mqtt-in-the-flutter-project-6a5d90179c8b

I keep studying the mqtt_client package, but the examples and documents they provide don't seem to have the option to use .p12 file to establish socket connection.

If I have to download the .p12 file to mobile then extract and resave three files again, it would not make sense to use Flutter.

Is there any way I can use .p12 file in the mqtt_client package, or is there any other option or package can achieve this?

Thanks for helping!


Solution

  • I figured it out that I could insert the p12 file using client.connect, but the package document never said anything about this. This suppose to be a very common way to build MQTT connection.

        _client = MqttServerClient.withPort(_host!, _identifier, _port);
        _client?.keepAlivePeriod = 60;
        _client?.logging(on: true);
        _client?.setProtocolV311();
        _client?.secure = true;
    
        final securityContext = SecurityContext.defaultContext;
        securityContext.setClientAuthorities('$_certPath/ios.p12', password: '');
        securityContext.useCertificateChain('$_certPath/ios.p12', password: '');
        securityContext.usePrivateKey('$_certPath/ios.p12', password: '');
        _client?.securityContext = securityContext;