sskaje / mqtt

MQTT Client class
https://sskaje.me/category/MQTT/
MIT License
86 stars 33 forks source link

Support TLS/SSL connections? #24

Open shenfeng07 opened 6 years ago

sskaje commented 6 years ago

https://github.com/sskaje/mqtt/blob/master/test/tls1.2/connect.php is this what you want?

shenfeng07 commented 6 years ago

yes。thank you。

shenfeng07 commented 6 years ago

请问ssl的证书要在哪里设置?看test上好像没有配置证书的路径。

sskaje commented 6 years ago

http://php.net/stream_context_create http://php.net/manual/en/context.ssl.php

btry commented 6 years ago

Hi

A small contribution to this issue.

Here is how I use TLS with this library, and it works. The code below is reactored to drop specificies of my project and make it more understandable.

   /**
    * Builds a MQTT
    * @param string $socketAddress
    * @param integer $port
    * @param boolean $isTls
    * @return sskaje\mqtt\MQTT an instance of a MQTT client
    */
   protected function buildMqtt($socketAddress, $port, $isTls) {
      $protocol = $isTls ? "ssl://" : "tcp://";
      $mqtt = new sskaje\mqtt\MQTT("$protocol$socketAddress:$port");
      if ($isTls) {
         $mqtt->setSocketContext(stream_context_create([
               'ssl' => [
                   'cafile'                => '/path/to/CACert-mqtt.crt',
                   'verify_peer'           => false,
                   'verify_peer_name'      => false,
                   'disable_compression'   => true,
                   'ciphers'               => 'ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:ECDHE-RSA-RC4-SHA:ECDHE-ECDSA-RC4-SHA:AES128:AES256:RC4-SHA:HIGH:!aNULL:!eNULL:!EXPORT:!DES:!3DES:!MD5:!PSK',
                   'crypto_method'         => STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT | STREAM_CRYPTO_METHOD_SSLv23_CLIENT,
                   'SNI_enabled'           => true,
                   'allow_self_signed'     => true
               ]
            ]
         ));
      }
      $mqtt->setKeepalive(50);

      return $mqtt;
   }