教程:使用适用于 IoT 中心设备预配服务的 Java 设备和服务 SDK 与组登记来创建和预配模拟的 X.509 设备Tutorial: Create and provision a simulated X.509 device using Java device and service SDK and group enrollments for IoT Hub Device Provisioning Service

以下步骤说明如何在运行 Windows OS 的开发计算机上模拟 X.509 设备,以及如何使用代码示例通过登记组将模拟设备连接到设备预配服务和 IoT 中心。These steps show how to simulate an X.509 device on your development machine running Windows OS, and use a code sample to connect this simulated device with the Device Provisioning Service and your IoT hub using enrollment groups.

在继续操作之前,请确保完成通过 Azure 门户设置 IoT 中心设备预配服务中的步骤。Make sure to complete the steps in the Setup IoT Hub Device Provisioning Service with the Azure portal before you proceed.

先决条件Prerequisites

  1. 确保已在计算机上安装 Java SE 开发工具包 8Make sure you have Java SE Development Kit 8 installed on your machine.

  2. 下载并安装 MavenDownload and install Maven.

  3. 确保在计算机上安装 git 并将其添加到可供命令窗口访问的环境变量。Make sure git is installed on your machine and is added to the environment variables accessible to the command window. 请参阅软件自由保护组织提供的 Git 客户端工具,了解要安装的最新版 git 工具,其中包括 Git Bash,这是一个命令行应用,可以用来与本地 Git 存储库交互。See Software Freedom Conservancy's Git client tools for the latest version of git tools to install, which includes the Git Bash , the command-line app that you can use to interact with your local Git repository.

  4. 使用以下证书概述创建测试证书。Use the following Certificate Overview to create your test certificates.

    备注

    此步骤需要 OpenSSL,可以通过源代码生成并安装此工具,也可以通过第三方(例如此处)下载并安装此工具。This step requires OpenSSL, which can either be built and installed from source or downloaded and installed from a 3rd-party such as this. 如果已创建根证书、中间证书和设备证书,则可以跳过此步骤。 If you have already created your root , intermediate and device certificates you may skip this step.

    1. 运行头两个步骤即可创建根证书和中间证书。 Run through the first two steps to create your root and intermediate certificates.

    2. 登录到 Azure 门户,单击左侧菜单上的“所有资源”按钮,打开预配服务 。Sign in to the Azure portal, click on the All resources button on the left-hand menu and open your provisioning service.

      1. 在设备预配服务摘要边栏选项卡上选择“证书”,然后单击顶部的“添加”按钮。 On the Device Provisioning Service summary blade, select Certificates and click the Add button at the top.

      2. 在“添加证书”下 输入以下信息:Under the Add Certificate , enter the following information:

        • 输入唯一的证书名称。Enter a unique certificate name.
        • 选择创建的 RootCA.pem 文件。Select the RootCA.pem file you created.
        • 完成后,单击“保存”按钮 。Once complete, click the Save button.

        添加证书

      3. 选择新建的证书:Select the newly created certificate:

        • 单击“生成验证码”。 Click Generate Verification Code . 复制生成的代码。Copy the code generated.

        • 运行验证步骤。Run the verification step. 输入验证码,或者在运行的 PowerShell 窗口中右键单击进行粘贴。 Enter the verification code or right-click to paste in your running PowerShell window. EnterPress Enter .

        • 在 Azure 门户中选择新建的 verifyCert4.pem 文件。Select the newly created verifyCert4.pem file in the Azure portal. 单击“验证”。 Click Verify .

          验证证书

    3. 最后,请运行创建设备证书并清理资源的步骤。Finish by running the steps to create your device certificates and clean-up resources.

      备注

      创建设备证书时,请确保只在设备名称中使用小写字母数字和连字符。When creating device certificates be sure to use only lower-case alphanumerics and hyphens in your device name.

创建设备注册项Create a device enrollment entry

  1. 打开命令提示符。Open a command prompt. 克隆 Java SDK 代码示例的 GitHub 存储库:Clone the GitHub repo for Java SDK code samples:

    git clone https://github.com/Azure/azure-iot-sdk-java.git --recursive
    
  2. 在下载的源代码中,导航到示例文件夹 azure-iot-sdk-java/provisioning/provisioning-samples/service-enrollment-group-sampleIn the downloaded source code, navigate to the sample folder azure-iot-sdk-java/provisioning/provisioning-samples/service-enrollment-group-sample . 在所选编辑器中打开文件 /src/main/java/samples/com/microsoft/azure/sdk/iot/ServiceEnrollmentGroupSample.java ,添加以下详细信息:Open the file /src/main/java/samples/com/microsoft/azure/sdk/iot/ServiceEnrollmentGroupSample.java in an editor of your choice, and add the following details:

    1. 在门户中为预配服务添加 [Provisioning Connection String],如下所示:Add the [Provisioning Connection String] for your provisioning service, from the portal as following:

      1. Azure 门户中导航到预配服务。Navigate to your provisioning service in the Azure portal.

      2. 打开“共享访问策略”,选择具有 EnrollmentWrite 权限的策略。 Open the Shared access policies , and select a policy that has the EnrollmentWrite permission.

      3. 复制“主密钥连接字符串” 。Copy the Primary key connection string .

        从门户获取预配连接字符串

      4. 在示例代码文件 ServiceEnrollmentGroupSample.java 中,将 [Provisioning Connection String] 替换为“主密钥连接字符串”。 In the sample code file ServiceEnrollmentGroupSample.java , replace the [Provisioning Connection String] with the Primary key connection string .

        private static final String PROVISIONING_CONNECTION_STRING = "[Provisioning Connection String]";
        
    2. 在文本编辑器中打开中间签名证书文件。Open your intermediate signing certificate file in a text editor. 使用中间签名证书的值更新 PUBLIC_KEY_CERTIFICATE_STRING 值。Update the PUBLIC_KEY_CERTIFICATE_STRING value with the value of your intermediate signing certificate.

      如果是使用 Bash shell 生成的设备证书,则 ./certs/azure-iot-test-only.intermediate.cert.pem 包含中间证书密钥。If you generated your device certificates with Bash shell, ./certs/azure-iot-test-only.intermediate.cert.pem contains the intermediate certificate key. 如果是使用 PowerShell 生成的证书,则 ./Intermediate1.pem 会是中间证书文件。If your certs were generated with PowerShell, ./Intermediate1.pem will be your intermediate certificate file.

      private static final String PUBLIC_KEY_CERTIFICATE_STRING =
              "-----BEGIN CERTIFICATE-----\n" +
              "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" +
              "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" +
              "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" +
              "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" +
              "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" +
              "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" +
              "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" +
              "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" +
              "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" +
              "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" +
              "-----END CERTIFICATE-----\n";
      
    3. Azure 门户中导航到已链接到预配服务的 IoT 中心。Navigate to the IoT hub linked to your provisioning service in the Azure portal. 打开中心的“概览”选项卡,复制“主机名”。 Open the Overview tab for the hub, and copy the Hostname . 将该“主机名” 指定给 IOTHUB_HOST_NAME 参数。Assign this Hostname to the IOTHUB_HOST_NAME parameter.

      private static final String IOTHUB_HOST_NAME = "[Host name].azure-devices.cn";
      
    4. 研究示例代码。Study the sample code. 此代码用于创建、更新、查询和删除 X.509 设备的组注册。It creates, updates, queries, and deletes a group enrollment for X.509 devices. 若要验证是否已在门户中成功注册,请暂时性地注释掉 ServiceEnrollmentGroupSample.java 文件末尾的以下代码行:To verify successful enrollment in portal, temporarily comment out the following lines of code at the end of the ServiceEnrollmentGroupSample.java file:

      // ************************************** Delete info of enrollmentGroup ***************************************
      System.out.println("\nDelete the enrollmentGroup...");
      provisioningServiceClient.deleteEnrollmentGroup(enrollmentGroupId);
      
    5. 保存 ServiceEnrollmentGroupSample.java 文件。Save the file ServiceEnrollmentGroupSample.java .

  3. 打开命令窗口,导航到文件夹 azure-iot-sdk-java/provisioning/provisioning-samples/service-enrollment-group-sampleOpen a command window, and navigate to the folder azure-iot-sdk-java/provisioning/provisioning-samples/service-enrollment-group-sample .

  4. 使用以下命令生成示例代码:Build the sample code by using this command:

    mvn install -DskipTests
    
  5. 运行示例,方法是在命令窗口使用以下命令:Run the sample by using these commands at the command window:

    cd target
    java -jar ./service-enrollment-group-sample-{version}-with-deps.jar
    
  6. 在成功注册后观察输出窗口。Observe the output window for successful enrollment.

    成功登记

  7. 在 Azure 门户中导航到预配服务。Navigate to your provisioning service in the Azure portal. 单击“管理注册”。 Click Manage enrollments . 请注意,X.509 设备组显示在“注册组”选项卡下,带有自动生成的“组名称”。 Notice that your group of X.509 devices appears under the Enrollment Groups tab, with an auto-generated GROUP NAME .

模拟设备Simulate the device

  1. 在设备预配服务摘要边栏选项卡上选择“概览”,记下“ID 范围”和“预配服务全局终结点”。 On the Device Provisioning Service summary blade, select Overview and note your ID Scope and Provisioning Service Global Endpoint .

    服务信息

  2. 打开命令提示符。Open a command prompt. 导航到示例项目文件夹。Navigate to the sample project folder.

    cd azure-iot-sdk-java/provisioning/provisioning-samples/provisioning-X509-sample
    
  3. 编辑 /src/main/java/samples/com/microsoft/azure/sdk/iot/ProvisioningX509Sample.java,使之包括前面记下的“ID 范围”和“预配服务全局终结点”。 Edit /src/main/java/samples/com/microsoft/azure/sdk/iot/ProvisioningX509Sample.java to include your ID Scope and Provisioning Service Global Endpoint that you noted previously.

    private static final String idScope = "[Your ID scope here]";
    private static final String globalEndpoint = "[Your Provisioning Service Global Endpoint here]";
    private static final ProvisioningDeviceClientTransportProtocol PROVISIONING_DEVICE_CLIENT_TRANSPORT_PROTOCOL = ProvisioningDeviceClientTransportProtocol.HTTPS;
    private static final int MAX_TIME_TO_WAIT_FOR_REGISTRATION = 10000; // in milli seconds
    private static final String leafPublicPem = "<Your Public PEM Certificate here>";
    private static final String leafPrivateKey = "<Your Private PEM Key here>";
    
  4. 使用公共和专用设备证书更新 leafPublicPemleafPrivateKey 变量。Update the leafPublicPem and leafPrivateKey variables with your public and private device certificates.

    如果是使用 PowerShell 生成的设备证书,则文件 mydevice* 包含设备的公钥、私钥和 PFX。If you generated your device certificates with PowerShell, the files mydevice* contain the public key, private key, and PFX for the device.

    如果是使用 Bash shell 生成的设备证书,则 ./certs/new-device.cert.pem 包含公钥。If you generated your device certificates with Bash shell, ./certs/new-device.cert.pem contains the public key. 设备的私钥位于 ./private/new-device.key.pem 文件中。The device's private key will be in the ./private/new-device.key.pem file.

    打开公钥文件并使用该值更新 leafPublicPem 变量。Open your public key file and update the leafPublicPem variable with that value. 复制从 -----BEGIN PRIVATE KEY----- 到 -----END PRIVATE KEY----- 的文本。Copy the text from -----BEGIN PRIVATE KEY----- to -----END PRIVATE KEY----- .

    private static final String leafPublicPem = "-----BEGIN CERTIFICATE-----\n" +
        "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" +
        "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" +
        "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" +
        "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" +
        "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" +
        "-----END CERTIFICATE-----\n";
    

    打开私钥文件并使用该值更新 leafPrivatePem 变量。Open your private key file and update the leafPrivatePem variable with that value. 复制从 -----BEGIN RSA PRIVATE KEY----- 到 -----END RSA PRIVATE KEY----- 的文本。Copy the text from -----BEGIN RSA PRIVATE KEY----- to -----END RSA PRIVATE KEY----- .

    private static final String leafPrivateKey = "-----BEGIN RSA PRIVATE KEY-----\n" +
        "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" +
        "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" +
        "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" +
        "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" +
        "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" +
        "-----END RSA PRIVATE KEY-----\n";
    
  5. 就在 leafPrivateKey 下方为中间证书添加新变量。Add a new variable just below leafPrivateKey for your intermediate certificate. 将此新变量命名为 intermediateKeyName this new variable intermediateKey. 向它提供中间签名证书的值。Give it the value of your intermediate signing certificate.

    如果是使用 Bash shell 生成的设备证书,则 ./certs/azure-iot-test-only.intermediate.cert.pem 包含中间证书密钥。If you generated your device certificates with Bash shell, ./certs/azure-iot-test-only.intermediate.cert.pem contains the intermediate certificate key. 如果是使用 PowerShell 生成的证书,则 ./Intermediate1.pem 会是中间证书文件。If your certs were generated with PowerShell, ./Intermediate1.pem will be your intermediate certificate file.

    private static final String intermediateKey = "-----BEGIN CERTIFICATE-----\n" +
        "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" +
        "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" +
        "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" +
        "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" +
        "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" +
        "-----END CERTIFICATE-----\n";
    
  6. main 函数中,在 securityProviderX509 的初始化之前将 intermediateKey 添加到 signerCertificates 集合。In the main function, add the intermediateKey to the signerCertificates collection before the initialization of securityProviderX509.

    public static void main(String[] args) throws Exception
    {
        ...
    
        try
        {
            ProvisioningStatus provisioningStatus = new ProvisioningStatus();
    
            // Add intermediate certificate as part of the certificate key chain.
            signerCertificates.add(intermediateKey);
    
            SecurityProvider securityProviderX509 = new SecurityProviderX509Cert(leafPublicPem, leafPrivateKey, signerCertificates);
    
  7. 保存更改,然后生成示例。Save your changes and build the sample. 导航到目标文件夹,然后执行创建的 jar 文件。Navigate to the target folder and execute the created jar file.

    mvn clean install
    cd target
    java -jar ./provisioning-x509-sample-{version}-with-deps.jar
    

    注册成功

  8. 在门户中导航到已链接到预配服务的 IoT 中心,然后打开“Device Explorer”边栏选项卡。 In the portal, navigate to the IoT hub linked to your provisioning service and open the Device Explorer blade. 将模拟的 X.509 设备成功预配到中心以后,设备 ID 会显示在“Device Explorer”边栏选项卡上,“状态”为“已启用”。 On successful provisioning of the simulated X.509 device to the hub, its device ID appears on the Device Explorer blade, with STATUS as enabled . 请注意,如果在运行示例设备应用程序之前已打开边栏选项卡,则可能需要单击顶部的“刷新”按钮。 Note that you might need to click the Refresh button at the top if you already opened the blade prior to running the sample device application.

    设备注册到 IoT 中心

清理资源Clean up resources

如果打算继续使用和探索设备客户端示例,请勿清理在本快速入门中创建的资源。If you plan to continue working on and exploring the device client sample, do not clean up the resources created in this Quickstart. 如果不打算继续学习,请通过以下步骤删除通过本快速入门创建的所有资源。If you do not plan to continue, use the following steps to delete all resources created by this Quickstart.

  1. 关闭计算机上的设备客户端示例输出窗口。Close the device client sample output window on your machine.
  2. 在 Azure 门户的左侧菜单中单击“所有资源”,然后选择设备预配服务 。From the left-hand menu in the Azure portal, click All resources and then select your Device Provisioning service. 打开服务的“管理注册”边栏选项卡,然后单击“单个注册”选项卡。 选择在本快速入门中注册的设备的“注册 ID”,然后单击顶部的“删除”按钮。 Open the Manage Enrollments blade for your service, and then click the Individual Enrollments tab. Select the REGISTRATION ID of the device you enrolled in this Quickstart, and click the Delete button at the top.
  3. 在 Azure 门户的左侧菜单中单击“所有资源”,然后选择 IoT 中心 。From the left-hand menu in the Azure portal, click All resources and then select your IoT hub. 打开中心的“IoT 设备”边栏选项卡,选择在本快速入门中注册的设备的“设备 ID”,然后单击顶部的“删除”按钮。 Open the IoT Devices blade for your hub, select the DEVICE ID of the device you registered in this Quickstart, and then click Delete button at the top.

后续步骤Next steps

本教程介绍了如何在 Windows 计算机上创建模拟 X.509 设备,以及如何使用 Azure IoT 中心设备预配服务和登记组将其预配到 IoT 中心。In this tutorial, you’ve created a simulated X.509 device on your Windows machine and provisioned it to your IoT hub using the Azure IoT Hub Device Provisioning Service and enrollment groups. 若要了解有关 X.509 设备的详细信息,请继续阅读设备概念。To learn more about your X.509 device, continue to device concepts.