无法使用paho mqtt java客户端代码连接到aws iot

无法使用paho mqtt java客户端代码连接到aws iot,mqtt,publish-subscribe,tls1.2,paho,aws-iot,Mqtt,Publish Subscribe,Tls1.2,Paho,Aws Iot,我在AWS内核上创建了这个东西。然后下载证书、私钥和rootCa证书。我的主要目标是发布和订阅AWS shadow,这样我就可以自动化我的家庭照明系统。 我尝试使用paho mqtt java客户端代码连接到aws iot,使用以下代码 package test.pub; import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.FileReader;

我在AWS内核上创建了这个东西。然后下载证书、私钥和rootCa证书。我的主要目标是发布和订阅AWS shadow,这样我就可以自动化我的家庭照明系统。 我尝试使用paho mqtt java客户端代码连接到aws iot,使用以下代码

    package test.pub;

    import java.io.BufferedInputStream;
    import java.io.FileInputStream;
    import java.io.FileReader;
    import java.security.KeyPair;
    import java.security.KeyStore;
    import java.security.Security;
    import java.security.cert.CertificateFactory;
    import java.security.cert.X509Certificate;

    import javax.net.ssl.KeyManagerFactory;
    import javax.net.ssl.SSLContext;
    import javax.net.ssl.SSLSocketFactory;
    import javax.net.ssl.TrustManagerFactory;

    import org.bouncycastle.jce.provider.BouncyCastleProvider;
    import org.bouncycastle.openssl.PEMDecryptorProvider;
    import org.bouncycastle.openssl.PEMEncryptedKeyPair;
    import org.bouncycastle.openssl.PEMKeyPair;
    import org.bouncycastle.openssl.PEMParser;
    import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
    import org.bouncycastle.openssl.jcajce.JcePEMDecryptorProviderBuilder;
    import org.eclipse.paho.client.mqttv3.MqttClient;
    import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
    import org.eclipse.paho.client.mqttv3.MqttException;

    public class App {

        public static void main(String[] args) {

            String serverUrl = "ssl://xxxxxxxx.iot.us-east- 
       1.amazonaws.com:8883";
            String caFilePath = "ca1.pem";
            String clientCrtFilePath = "thing.cert.pem";
            String clientKeyFilePath = "thing.private.key";

        MqttClient client;
        try {
            client = new MqttClient(serverUrl, MqttClient.generateClientId());
            MqttConnectOptions options = new MqttConnectOptions();

            options.setConnectionTimeout(60);
            options.setKeepAliveInterval(60);
            options.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1);


            SSLSocketFactory socketFactory = getSocketFactory(caFilePath,
                    clientCrtFilePath, clientKeyFilePath, "");
            options.setSocketFactory(socketFactory);

            System.out.println("starting connect the server...");
            client.connect(options);
            System.out.println("connected!");
            Thread.sleep(1000);

            client.subscribe(
                    "test",
                    0);
            client.disconnect();
            System.out.println("disconnected!");


        } catch (MqttException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private static SSLSocketFactory getSocketFactory(final String caCrtFile,
            final String crtFile, final String keyFile, final String password)
            throws Exception {
        Security.addProvider(new BouncyCastleProvider());

        // load CA certificate
        X509Certificate caCert = null;

        FileInputStream fis = new FileInputStream(caCrtFile);
        BufferedInputStream bis = new BufferedInputStream(fis);
        CertificateFactory cf = CertificateFactory.getInstance("X.509");

        while (bis.available() > 0) {
            caCert = (X509Certificate) cf.generateCertificate(bis);
            // System.out.println(caCert.toString());
        }

        // load client certificate
        bis = new BufferedInputStream(new FileInputStream(crtFile));
        X509Certificate cert = null;
        while (bis.available() > 0) {
            cert = (X509Certificate) cf.generateCertificate(bis);
            // System.out.println(caCert.toString());
        }

        // load client private key
        PEMParser pemParser = new PEMParser(new FileReader(keyFile));
        Object object = pemParser.readObject();
        PEMDecryptorProvider decProv = new JcePEMDecryptorProviderBuilder()
                .build(password.toCharArray());
        JcaPEMKeyConverter converter = new JcaPEMKeyConverter()
                .setProvider("BC");
        KeyPair key;
        if (object instanceof PEMEncryptedKeyPair) {
            System.out.println("Encrypted key - we will use provided password");
            key = converter.getKeyPair(((PEMEncryptedKeyPair) object)
                    .decryptKeyPair(decProv));
        } else {
            System.out.println("Unencrypted key - no password needed");
            key = converter.getKeyPair((PEMKeyPair) object);
        }
        pemParser.close();

        // CA certificate is used to authenticate server
        KeyStore caKs = KeyStore.getInstance(KeyStore.getDefaultType());
        caKs.load(null, null);
        caKs.setCertificateEntry("ca-certificate", caCert);
        TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
        tmf.init(caKs);

        // client key and certificates are sent to server so it can authenticate
        // us
        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ks.load(null, null);
        ks.setCertificateEntry("certificate", cert);
        ks.setKeyEntry("private-key", key.getPrivate(), password.toCharArray(),
                new java.security.cert.Certificate[] { cert });
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory
                .getDefaultAlgorithm());
        kmf.init(ks, password.toCharArray());

        // finally, create SSL socket factory
        SSLContext context = SSLContext.getInstance("TLSv1.2");
        context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

        return context.getSocketFactory();
    }

}
我得到以下控制台日志和错误

Unencrypted key - no password needed
starting connect the server...
Unable to connect to server (32103) - java.net.ConnectException: Connection timed out: connect
    at org.eclipse.paho.client.mqttv3.internal.TCPNetworkModule.start(TCPNetworkModule.java:79)
    at org.eclipse.paho.client.mqttv3.internal.SSLNetworkModule.start(SSLNetworkModule.java:82)
    at org.eclipse.paho.client.mqttv3.internal.ClientComms$ConnectBG.run(ClientComms.java:590)
    at java.lang.Thread.run(Unknown Source)
Caused by: java.net.ConnectException: Connection timed out: connect
    at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method)
    at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
    at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
    at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
    at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
    at java.net.PlainSocketImpl.connect(Unknown Source)
    at java.net.SocksSocketImpl.connect(Unknown Source)
    at java.net.Socket.connect(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.connect(Unknown Source)
    at org.eclipse.paho.client.mqttv3.internal.TCPNetworkModule.start(TCPNetworkModule.java:70)
    ... 3 more

请帮助我连接到aws IOT,以便我可以将shadow或至少pub/sub更新到主题。

请仔细检查您是否拥有您尝试连接到的代理的正确主机名。超时错误意味着在你认为的地方没有任何东西在听。某个地方的防火墙正在丢弃数据包。@hardillb我正在使用aws端点:-xxxxxxxx.iot.us-east-1.amazonaws.com连接到aws iot东西。这里xxxxxxxx是前缀。是的,我知道您已将其更改为此处发布,但请检查实际值。@hardillb我检查了所有详细信息,但没有成功。如果主机正确,则您很可能在客户端和代理之间有防火墙阻止访问。