{"id":4448,"date":"2024-12-25T14:00:40","date_gmt":"2024-12-25T06:00:40","guid":{"rendered":"https:\/\/learn-house.idv.tw\/?p=4448"},"modified":"2024-12-25T17:39:36","modified_gmt":"2024-12-25T09:39:36","slug":"androidmqtt%e5%a6%82%e4%bd%95%e8%a8%ad%e7%bd%ae%e9%9b%99%e5%90%91%e8%aa%8d%e8%ad%89%e8%88%87app%e5%af%a6%e4%bd%9c","status":"publish","type":"post","link":"https:\/\/learn-house.idv.tw\/?p=4448","title":{"rendered":"[Android]MQTT\u5982\u4f55\u8a2d\u7f6e\u96d9\u5411\u8a8d\u8b49\u8207APP\u5be6\u4f5c"},"content":{"rendered":"<p>MQTT\u7684\u5b89\u88dd\u548cPublisher\/Subscriber\u904b\u4f5c\u65b9\u5f0f\uff0c\u6211\u76f8\u4fe1\u5df2\u7d93\u6709\u96d9\u5411\u8a8d\u8b49\u9700\u6c42\u7684\u61c9\u8a72\u90fd\u5df2\u7d93\u5f88\u6e05\u695a\u4e86\u3002\u9019\u6211\u5c31\u4e0d\u591a\u505a\u8d05\u8ff0\uff0c\u53ea\u8b1b\u914d\u7f6e\u548cAndroid\u7a0b\u5f0f\u5be6\u4f5c\u7684\u90e8\u5206\u3002<\/p>\n<p>\u6240\u8b02\u7684\u96d9\u5411\u8a8d\u8b49\u5c31\u662fClinet\u7aef\u6703\u9700\u8981\u9a57\u8b49Server\u7684\u6191\u8b49\uff0c\u800cServer\u9700\u8981\u9a57\u8b49Client\u662f\u5426\u662f\u4f7f\u7528\u4ed6\u5141\u8a31\u7684\u6191\u8b49\u3002\u9019\u6642\u5c31\u9700\u8981\u5efa\u7acb\u4e09\u5f35\u6191\u8b49\u4f86\u9054\u5230\u9019\u500b\u6548\u679c\u3002CA\u6191\u8b49\uff0cServer\u7aef\u6191\u8b49\u548cClient\u6191\u8b49\u3002Mosquitto\u6703\u914d\u7f6eCA\u6191\u8b49\u548cServer\u7aef\u6191\u8b49\uff0c\u800cPublisher\/Subscriber\u6703\u914d\u7f6eClient\u6191\u8b49\uff0c\u5982\u4e0b\u5716\u3002<!--more--><\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone \" src=\"https:\/\/photos.learn-house.idv.tw\/api\/assets\/54b5b6be-4b68-4203-9ca7-ea1da44156ef\/thumbnail?size=preview&amp;key=glZv_mIC4SK8nkZdqKZVFGSymE_9iAjfa970y8GjG0vGel_imTydmVgN-XGLtIT9yy8&amp;c=jyoK8EM0zOlrcyURALM%2FhBlej6s%3D\" width=\"522\" height=\"286\" \/><\/p>\n<p>\u9996\u5148\u5c31\u662f\u5148\u7522\u751f\u4e0a\u8ff0\u6240\u8aaa\u7684\u6191\u8b49\uff0c\u4f7f\u7528openssl\u6307\u4ee4<\/p>\n<pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\n# \u751f\u6210CA\u79c1\u9470\u8207\u81ea\u7c3d\u540d\u8b49\u66f8\nopenssl genpkey -algorithm RSA -out ca.key -pkeyopt rsa_keygen_bits:2048\nopenssl req -new -x509 -key ca.key -out ca.crt -days 25550\n\n# \u751f\u6210\u4f3a\u670d\u5668\u7684\u79c1\u9470\u8207\u670d\u52d9\u5668\u8b49\u66f8\u7c3d\u540d\u8acb\u6c42\nopenssl genpkey -algorithm RSA -out server.key -pkeyopt rsa_keygen_bits:2048\nopenssl req -new -key server.key -out server.csr\n\n# \u751f\u6210\u5ba2\u6236\u7aef\u7684\u79c1\u9470\u8207\u5ba2\u6236\u7aef\u8b49\u66f8\u7c3d\u540d\u8acb\u6c42\nopenssl genpkey -algorithm RSA -out client.key -pkeyopt rsa_keygen_bits:2048\nopenssl req -new -key client.key -out client.csr\n\n# \u4f7f\u7528CA\u8b49\u66f8\u7c3d\u7f72\u4f3a\u670d\u5668\u8b49\u66f8\u548c\u5ba2\u6236\u7aef\u8b49\u66f8(-days\u53c3\u6578\u662f\u6191\u8b49\u6548\u671f\u5929\u6578\uff0c\u53ef\u81ea\u884c\u4fee\u6539)\nopenssl x509 -req -in server.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out server.crt -days 25550\nopenssl x509 -req -in client.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out client.crt -days 25550\n\n<\/pre>\n<p>\u4e0a\u8ff0\u904e\u7a0b\u6bd4\u8f03\u9700\u6ce8\u610f\u7684\u662f\u751f\u6210\u4f3a\u670d\u52d9\u5668\u8b49\u66f8\u7c3d\u540d\u8acb\u6c42server.csr\u6642\u6240\u9700\u8f38\u5165\u7684\u5167\u5bb9\uff0c\u5176\u4e2dCommon Name\u9700\u8981\u586b\u5165\u4f60\u4f3a\u670d\u5668\u7684\u5b8c\u6574\u5730domain name\uff0c\u81f3\u65bcCA.crt\u548cclient.csr\u5247\u96a8\u4fbf\u8f38\u5165\u6c92\u95dc\u4fc2\uff0c\u4f46\u4e09\u5f35\u4e0d\u80fd\u6709\u91cd\u8907\u7684FQDN\uff0c\u4ee5\u4e0b\u662f\u6211\u8f38\u5165\u5167\u5bb9\u4f9b\u53c3\u8003\uff1a<\/p>\n<pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\nYou are about to be asked to enter information that will be incorporated\ninto your certificate request.\nWhat you are about to enter is what is called a Distinguished Name or a DN.\nThere are quite a few fields but you can leave some blank\nFor some fields there will be a default value,\nIf you enter &#039;.&#039;, the field will be left blank.\n-----\nCountry Name (2 letter code) &#x5B;AU]:TW\nState or Province Name (full name) &#x5B;Some-State]:Taiwan\nLocality Name (eg, city) &#x5B;]:Hsinchu\nOrganization Name (eg, company) &#x5B;Internet Widgits Pty Ltd]:LearnHouse\nOrganizational Unit Name (eg, section) &#x5B;]:SW\nCommon Name (e.g. server FQDN or YOUR name) &#x5B;]:learn-house.idv.tw\nEmail Address &#x5B;]:mr.yuchin@gmail.com\n\nPlease enter the following &#039;extra&#039; attributes\nto be sent with your certificate request\nA challenge password &#x5B;]:\nAn optional company name &#x5B;]:\n\n<\/pre>\n<p>Broker Server\u7aef\u914d\u7f6e\/etc\/mosquitto\/mosquitto.conf<br \/>\n\u5c07\u4e0a\u8ff0\u7522\u751f\u7684\u91d1\u9470\u548c\u6191\u8b49\u653e\u5165\u76f8\u5c0d\u61c9\u7684\u4f4d\u7f6e<\/p>\n<pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\n# MQTT-over-SSL port 8883\nlistener 8883\n\n# Certificate\u914d\u7f6e\ncertfile \/etc\/mosquitto\/certs\/server.crt\nkeyfile \/etc\/mosquitto\/certs\/server.key\ncafile \/etc\/mosquitto\/ca_certificates\/ca.crt\n\n# \u958b\u555f\u96d9\u5411\u9a57\u8b49\nrequire_certificate true\nuse_identity_as_username true\n<\/pre>\n<p>Android APP\u7684\u5be6\u4f5c\u65b9\u9762\uff0c<br \/>\n\u9996\u5148\u5728app\u7684build.grade\u52a0\u5165bouncycastle<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\ndependencies {\n...\n    implementation &#039;org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.2.5&#039;\n    implementation &#039;org.eclipse.paho:org.eclipse.paho.android.service:1.1.1&#039;\n    implementation &#039;org.bouncycastle:bcprov-jdk15on:1.70&#039;\n    implementation &#039;org.bouncycastle:bcpkix-jdk15on:1.70&#039;\n}\n<\/pre>\n<p>\u5728\u539f\u59cb\u7684options\u52a0\u5165TLS\/SSL\u652f\u63f4<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\nMqttConnectOptions options = new MqttConnectOptions();\n...\nSSLSocketFactory socketFactory = getSSLSocketFactory(R.raw.ca, R.raw.client_crt, R.raw.client_key, &quot;&quot;);\noptions.setSocketFactory(socketFactory);\n<\/pre>\n<p>\u7531\u65bc\u57f7\u884c\u6642\u90fd\u6703\u51fa\u73fe\uff1a<br \/>\nMqttException (0) - javax.net.ssl.SSLHandshakeException: No subjectAltNames on the certificate match<br \/>\n\u6b63\u5e38\u4f86\u8aaa\uff0c\u51fa\u73fe\u9019\u6a23\u7684\u932f\u8aa4\u8a0a\u606f\u4e3b\u8981\u662f\u4f60\u9023\u63a5\u7684\u4e3b\u6a5f\u540d\u4e0d\u5339\u914d\uff0c\u4f46\u6211\u5f88\u78ba\u5b9a\u6211\u7684server\u90a3\u5f35\u6191\u8b49\u7684Common Name\u662flearn-house.idv.tw\u3002\u731c\u6e2c\u61c9\u8a72\u662f\u81ea\u7c3d\u6191\u8b49\u7684\u95dc\u4fc2\uff0c\u56e0\u6b64\u52a0\u5165<code class=\"bg-text-200\/5 border border-0.5 border-border-300 text-danger-000 whitespace-pre-wrap rounded-[0.3rem] px-1 py-px text-[0.9rem]\">CustomHostnameVerifier<\/code>\u4f86\u5ffd\u7565\u4e3b\u6a5f\u540d\u9a57\u8b49\u548c<code class=\"bg-text-200\/5 border border-0.5 border-border-300 text-danger-000 whitespace-pre-wrap rounded-[0.3rem] px-1 py-px text-[0.9rem]\">TrustManager<\/code>\u4f86\u63a5\u53d7\u6240\u6709\u670d\u52d9\u5668\u8b49\u66f8\u3002<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\n\/\/ \u81ea\u5b9a\u7fa9\u7684 HostnameVerifier\uff0c\u5ffd\u7565\u4e3b\u6a5f\u540d\u9a57\u8b49\nprivate class CustomHostnameVerifier implements HostnameVerifier {\n    @Override\n    public boolean verify(String hostname, SSLSession session) {\n        return true;\n    }\n}\n\n<\/pre>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\nprivate SSLSocketFactory getSSLSocketFactory(int caResId, int clientCertResId, int clientKeyResId, String clientKeyPassword) throws Exception {\n    \/\/ \u52a0\u8f09 CA \u8b49\u66f8\n    CertificateFactory cf = CertificateFactory.getInstance(&quot;X.509&quot;);\n    ByteArrayInputStream caInput = new ByteArrayInputStream(readFromResource(caResId));\n    Certificate ca = cf.generateCertificate(caInput);\n    caInput.close();\n\n    \/\/ \u5275\u5efa\u91d1\u9470\u5eab\u4e26\u5c0e\u5165 CA \u8b49\u66f8\n    KeyStore caKs = KeyStore.getInstance(KeyStore.getDefaultType());\n    caKs.load(null, null);\n    caKs.setCertificateEntry(&quot;ca-certificate&quot;, ca);\n\n    \/\/ \u5275\u5efa\u81ea\u5b9a\u7fa9\u7684 TrustManager\n    TrustManager&#x5B;] trustManagers = new TrustManager&#x5B;] {\n            new X509TrustManager() {\n                @Override\n                public void checkClientTrusted(X509Certificate&#x5B;] x509Certificates, String s) throws CertificateException {\n                    \/\/ \u4e0d\u505a\u4efb\u4f55\u6aa2\u67e5\uff0c\u610f\u5473\u8457\u4fe1\u4efb\u6240\u6709\u5ba2\u6236\u7aef\u8b49\u66f8\n                }\n\n                @Override\n                public X509Certificate&#x5B;] getAcceptedIssuers() {\n                    return null; \/\/ \u901a\u5e38\u8fd4\u56de null \u6216\u4e00\u500b\u7a7a\u9663\u5217\u8868\u793a\u4e0d\u4fe1\u4efb\u4efb\u4f55\u8b49\u66f8\u767c\u884c\u6a5f\u69cb\n                }\n\n                @Override\n                public void checkServerTrusted(X509Certificate&#x5B;] chain, String authType) throws CertificateException {\n                    \/\/ \u4e0d\u505a\u4efb\u4f55\u6aa2\u67e5\uff0c\u610f\u5473\u8457\u4fe1\u4efb\u6240\u6709\u4f3a\u670d\u5668\u8b49\u66f8\n                }\n            }\n    };\n\n    \/\/ \u52a0\u8f09\u5ba2\u6236\u7aef\u8b49\u66f8\u548c\u79c1\u9470\n    KeyStore clientKs = KeyStore.getInstance(KeyStore.getDefaultType());\n    clientKs.load(null, null);\n\n    \/\/ \u8b80\u53d6\u5ba2\u6236\u7aef\u8b49\u66f8\n    ByteArrayInputStream clientCertInput = new ByteArrayInputStream(readFromResource(clientCertResId));\n    Certificate clientCert = cf.generateCertificate(clientCertInput);\n    clientCertInput.close();\n\n    \/\/ \u8b80\u53d6\u4e26\u89e3\u6790\u79c1\u9470\n    byte&#x5B;] clientKeyBytes = readFromResource(clientKeyResId);\n    PrivateKey privateKey = getPrivateKey(clientKeyBytes, &quot;RSA&quot;);\n\n    \/\/ \u5c07\u5ba2\u6236\u7aef\u8b49\u66f8\u548c\u79c1\u9470\u5b58\u5165\u91d1\u9470\u5eab\n    clientKs.setCertificateEntry(&quot;client-cert&quot;, clientCert);\n    clientKs.setKeyEntry(&quot;client-key&quot;, privateKey, clientKeyPassword.toCharArray(), new Certificate&#x5B;]{clientCert});\n\n    \/\/ \u5275\u5efa KeyManager\n    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());\n    kmf.init(clientKs, clientKeyPassword.toCharArray());\n\n    \/\/ \u5275\u5efa SSLContext\n    SSLContext sslContext = SSLContext.getInstance(&quot;TLS&quot;);\n    sslContext.init(kmf.getKeyManagers(), trustManagers, null);\n\n    return sslContext.getSocketFactory();\n}\n<\/pre>\n<p>options\u4fee\u6539\u5982\u4e0b\uff1a<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\nMqttConnectOptions options = new MqttConnectOptions();\n...\nSSLSocketFactory socketFactory = getSSLSocketFactory(R.raw.ca, R.raw.client_crt, R.raw.client_key, &quot;&quot;);\noptions.setSocketFactory(socketFactory);\noptions.setSSLHostnameVerifier(new CustomHostnameVerifier());\n<\/pre>\n<p>\u9019\u6a23APP\u5c31\u53ef\u4ee5\u9023\u5230Broker Server\u4e26\u63a5\u6536subscribe\u7684topic\u4e86\u3002<\/p>\n","protected":false},"excerpt":{"rendered":"<p>MQTT\u7684\u5b89\u88dd\u548cPublisher\/Subscriber\u904b\u4f5c\u65b9\u5f0f\uff0c\u6211\u76f8\u4fe1\u5df2\u7d93\u6709\u96d9\u5411\u8a8d\u8b49\u9700\u6c42\u7684\u61c9\u8a72\u90fd\u5df2\u7d93\u5f88\u6e05\u695a\u4e86 [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[5],"tags":[],"class_list":["post-4448","post","type-post","status-publish","format-standard","hentry","category-5"],"_links":{"self":[{"href":"https:\/\/learn-house.idv.tw\/index.php?rest_route=\/wp\/v2\/posts\/4448"}],"collection":[{"href":"https:\/\/learn-house.idv.tw\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/learn-house.idv.tw\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/learn-house.idv.tw\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/learn-house.idv.tw\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=4448"}],"version-history":[{"count":21,"href":"https:\/\/learn-house.idv.tw\/index.php?rest_route=\/wp\/v2\/posts\/4448\/revisions"}],"predecessor-version":[{"id":4471,"href":"https:\/\/learn-house.idv.tw\/index.php?rest_route=\/wp\/v2\/posts\/4448\/revisions\/4471"}],"wp:attachment":[{"href":"https:\/\/learn-house.idv.tw\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=4448"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/learn-house.idv.tw\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=4448"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/learn-house.idv.tw\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=4448"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}