繁体   English   中英

为什么我无法通过 MQTT 连接到 Google Cloud IOT Core 中的设备?

[英]Why can't I connect to device in Google Cloud IOT Core through MQTT?

我想将 Spring 启动时的后端连接到 Google Cloud Iot-Core 硬件设置中的其中一台设备。 我基本上复制了这个 github 存储库并调整了身份验证和连接选项。 当我运行我的程序时,它抛出这个异常:

Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.eclipse.paho.client.mqttv3.MqttClient]: 工厂方法 'connectToMqttClient' 抛出异常; 嵌套异常是不正确的用户名或密码 (4)

要创建密码,我使用这种方法

private static String createJwtRsa(String projectId, String privateKeyFile)
        throws NoSuchAlgorithmException, IOException, InvalidKeySpecException {
    DateTime now = new DateTime();

    JwtBuilder jwtBuilder =
            Jwts.builder()
                    .setIssuedAt(now.toDate())
                    .setExpiration(now.plusMinutes(20).toDate())
                    .setAudience(projectId);

    byte[] keyBytes = Files.readAllBytes(Paths.get(privateKeyFile));
    PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
    KeyFactory kf = KeyFactory.getInstance("RSA");

    return jwtBuilder.signWith(SignatureAlgorithm.RS256, kf.generatePrivate(spec)).compact();
}

我遇到了 privateKeyFile 格式的问题。 在 Iot-core 上,设备具有 RS256_X509 的公钥

在此处输入图像描述

但是 Spring Boot 只允许 RS256_PKCS8 密钥格式,所以我不得不这样做:

  1. 我生成了格式为 X509 openssl req -x509 -nodes -newkey rsa:2048 -keyout rsa_private.pem -out rsa_cert.pem -subj "/CN=unused"的密钥,它还生成了证书 rsa_cer.pem
  2. 我将密钥转换为 PKCS8 格式openssl pkcs8 -topk8 -inform PEM -outform DER -in rsa_private.pem -out private_key.der -nocrypt
  3. 我在 createJwtRsa 方法中使用的 Iot-core 和 rsa_private.der 中作为公钥添加的证书

从那时起我得到了例外:不正确的用户名和密码。 我能做些什么来修复它?

编辑:

我还尝试生成普通的 RSA256 密钥并将其转换为 PKCS8 格式,我得到了同样的异常。 与ES256密钥相同

我设法解决了这个问题! clientId 不正确

final String mqttClientId = String.format("projects/%s/locations/%s/registries/%s/devices/%s",
options.projectId, options.cloudRegion, options.registryId, options.gatewayId);

我的 gatewayId 是一个空字符串,因为我们没有在 Iot Core 上创建网关,我们直接连接到设备。 所以今天我将gatewayId设置为deviceId并且后端成功连接到设备。 所以现在这条线看起来像这样

final String mqttClientId = String.format("projects/%s/locations/%s/registries/%s/devices/%s",options.projectId, 
 options.cloudRegion, options.registryId, options.deviceId);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM