在 Azure IoT 中心设置 X.509 安全性Set up X.509 security in your Azure IoT hub

本教程介绍使用 X.509 证书身份验证保护 Azure IoT 中心所要执行的步骤。This tutorial shows the steps you need to secure your Azure IoT hub using the X.509 Certificate Authentication. 在演示过程中,我们将使用开源工具 OpenSSL 在 Windows 计算机本地创建证书。For the purpose of illustration, we use the open-source tool OpenSSL to create certificates locally on your Windows machine. 我们建议仅将本教程用于测试目的。We recommend that you use this tutorial for test purposes only. 对于生产环境,应该从根证书颁发机构 (CA) 购买证书。For production environment, you should purchase the certificates from a root certificate authority (CA).

先决条件Prerequisites

本教程要求准备好以下资源:This tutorial requires that you have the following resources ready:

获取 X.509 CA 证书Get X.509 CA certificates

IoT 中心基于 X.509 证书的安全性需从 X.509 证书链开始,其中包括根证书、任何中间证书,及至叶证书。The X.509 certificate-based security in the IoT Hub requires you to start with an X.509 certificate chain, which includes the root certificate as well as any intermediate certificates up until the leaf certificate.

可以选择以下任一方法获取证书:You may choose any of the following ways to get your certificates:

  • 根证书颁发机构 (CA) 购买 X.509 证书。Purchase X.509 certificates from a root certificate authority (CA). 建议在生产环境中使用此方法。This method is recommended for production environments.

  • 使用 OpenSSL 等第三方工具创建自己的 X.509 证书。Create your own X.509 certificates using a third-party tool such as OpenSSL. 此方法适用于测试和开发目的。This technique is fine for test and development purposes. 有关使用 PowerShell 或 Bash 生成测试 CA 证书的信息,请参阅管理示例和教程的测试 CA 证书See Managing test CA certificates for samples and tutorials for information about generating test CA certificates using PowerShell or Bash. 本教程的其余部分使用按照管理示例和教程的测试 CA 证书中的说明生成的测试 CA 证书。The rest of this tutorial uses test CA certificates generated by following the instructions in Managing test CA certificates for samples and tutorials.

  • 生成由某个现有根 CA 证书签名的 X.509 中间 CA 证书并将其上传到中心。Generate an X.509 intermediate CA certificate signed by an existing root CA certificate and upload it to the hub. 在上传并验证中间证书后,可以使用它来替代下面提到的根 CA 证书,如下所述。Once the intermediate certificate is uploaded and verified, as instructed below, it can be used in the place of a root CA certificate mentioned below. 可以使用诸如 OpenSSL(openssl reqopenssl ca)的工具来生成中间 CA 证书并对其进行签名。Tools like OpenSSL (openssl req and openssl ca) can be used to generate and sign an intermediate CA certificate.

备注

如果第三方根目录不是你独有的,请不要将其上传,因为这将使第三方的其他客户能够将其设备连接到你的 IoT 中心。Do not upload the 3rd party root if it is not unique to you because that would enable other customers of the 3rd party to connect their devices to your IoT Hub.

将 X.509 CA 证书注册到 IoT 中心Register X.509 CA certificates to your IoT hub

这些步骤说明如何通过门户将新的证书颁发机构添加到 IoT 中心。These steps show you how to add a new Certificate Authority to your IoT hub through the portal.

  1. 在 Azure 门户中,导航到你的 IoT 中心,并选择中心的“设置” > “证书”。 In the Azure portal, navigate to your IoT hub and select Settings > Certificates for the hub.

  2. 选择“添加”以添加新证书。Select Add to add a new certificate.

  3. 在“证书名称”中输入一个易记的显示名称,并从计算机中选择在上一部分创建的证书文件。In Certificate Name, enter a friendly display name, and select the certificate file you created in the previous section from your computer.

  4. 收到已成功上传证书的通知后,选择“保存”。Once you get a notification that your certificate is successfully uploaded, select Save.

    上传证书

    该证书将显示在证书列表中,其状态为“未验证”。Your certificate appears in the certificates list with status of Unverified.

  5. 选择刚刚添加的证书以显示“证书详细信息”,然后选择“生成验证码”。 Select the certificate that you just added to display Certificate Details, and then select Generate Verification Code.

    验证证书

  6. 将“验证码”复制到剪贴板。Copy the Verification Code to the clipboard. 稍后要使用它来验证证书所有权。You use it to validate the certificate ownership.

  7. 遵循管理用于示例和教程的测试 CA 证书中的“步骤 3”。Follow Step 3 in Managing test CA certificates for samples and tutorials. 此过程将使用与 X.509 CA 证书关联的、可生成签名的私钥来为验证码签名。This process signs your verification code with the private key associate with your X.509 CA certificate, which generates a signature. 有一些工具(例如 OpenSSL)可执行此签名过程。There are tools available to perform this signing process, for example, OpenSSL. 此过程称为所有权证明This process is known as the Proof of possession.

  8. 在“证书详细信息”中的“验证证书 .pem 或 .cer 文件”下,找到并打开签名文件。 In Certificate Details, under Verification Certificate .pem or .cer file, find and open the signature file. 然后选择“验证”。Then select Verify.

    证书状态将更改为“已验证”。The status of your certificate changes to Verified. 如果证书未自动更新,请选择“刷新”。Select Refresh if the certificate does not update automatically.

为 IoT 中心创建 X.509 设备Create an X.509 device for your IoT hub

  1. 在 Azure 门户中导航到你的 IoT 中心,然后选择“资源管理器” > “IoT 设备”。 In the Azure portal, navigate to your IoT hub, and then select Explorers > IoT devices.

  2. 选择“新建”以添加新设备。Select New to add a new device.

  3. 在“设备 ID”中,输入易记的显示名称。In Device ID, enter a friendly display name. 对于“身份验证类型”,请选择“已由 X.509 CA 签名”,然后选择“保存”。 For Authentication type, choose X.509 CA Signed, and then select Save.

    在门户中创建 X.509 设备

使用 X.509 证书对 X.509 设备进行身份验证Authenticate your X.509 device with the X.509 certificates

若要对 X.509 设备进行身份验证,首先需要使用 CA 证书为该设备签名。To authenticate your X.509 device, you need to first sign the device with the CA certificate. 叶设备的签名通常在已相应地启用了制造工具的制造车间完成。Signing of leaf devices is normally done at the manufacturing plant, where manufacturing tools have been enabled accordingly. 随着设备从一家制造商转移到另一家制造商,每家制造商的签名操作都捕获为链中的中间证书。As the device goes from one manufacturer to another, each manufacturer’s signing action is captured as an intermediate certificate within the chain. 结果是建立了从 CA 证书到设备叶证书的证书链。The result is a certificate chain from the CA certificate to the device’s leaf certificate. 管理示例和教程的测试 CA 证书中的步骤 4 会生成设备证书。Step 4 in Managing test CA certificates for samples and tutorials generates a device certificate.

接下来,我们演示如何创建一个 C# 应用程序来模拟针对 IoT 中心注册的 X.509 设备。Next, we will show you how to create a C# application to simulate the X.509 device registered for your IoT hub. 我们会将模拟设备提供的温度和湿度值发送到中心。We will send temperature and humidity values from the simulated device to your hub. 本教程只创建设备应用程序。In this tutorial, we will create only the device application. 至于如何创建 IoT 中心服务应用程序用于向此模拟设备发送的事件发送响应,是留给读者的练习。It is left as an exercise to the readers to create the IoT Hub service application that will send response to the events sent by this simulated device. C# 应用程序假定你已按照管理示例和教程的测试 CA 证书中的步骤进行操作。The C# application assumes that you have followed the steps in Managing test CA certificates for samples and tutorials.

  1. 打开 Visual Studio,选择“创建新项目”,然后选择“控制台应用(.NET Framework)”项目模板。 Open Visual Studio, select Create a new project, and then choose the Console App (.NET Framework) project template. 选择“下一步”。Select Next.

  2. 在“配置新项目”中,将项目命名为 SimulateX509Device,然后选择“创建”。 In Configure your new project, name the project SimulateX509Device, and then select Create.

    在 Visual Studio 中创建 X.509 设备项目

  3. 在解决方案资源管理器中,右键单击“SimulateX509Device”项目,然后选择“管理 NuGet 包”。 In Solution Explorer, right-click the SimulateX509Device project, and then select Manage NuGet Packages.

  4. 在“NuGet 包管理器”中,选择“浏览”,然后搜索并选择“Microsoft.Azure.Devices.Client”。 In the NuGet Package Manager, select Browse and search for and choose Microsoft.Azure.Devices.Client. 选择“安装”。Select Install.

    在 Visual Studio 中添加设备 SDK NuGet 包

    此步骤将下载、安装 Azure IoT 设备 SDK NuGet 包及其依赖项并添加对它的引用。This step downloads, installs, and adds a reference to the Azure IoT device SDK NuGet package and its dependencies.

  5. Program.cs 文件顶部添加以下 using 语句:Add the following using statements at the top of the Program.cs file:

        using Microsoft.Azure.Devices.Client;
        using Microsoft.Azure.Devices.Shared;
        using System.Security.Cryptography.X509Certificates;
    
  6. 将以下字段添加到 Program 类:Add the following fields to the Program class:

        private static int MESSAGE_COUNT = 5;
        private const int TEMPERATURE_THRESHOLD = 30;
        private static String deviceId = "<your-device-id>";
        private static float temperature;
        private static float humidity;
        private static Random rnd = new Random();
    

    请将 < your_device_id > 替换为在前一部分中所用的易记设备名称。Use the friendly device name you used in the preceding section in place of <your_device_id>.

  7. 添加以下函数,以创建温度和湿度的随机数并将这些值发送到中心:Add the following function to create random numbers for temperature and humidity and send these values to the hub:

    static async Task SendEvent(DeviceClient deviceClient)
    {
        string dataBuffer;
        Console.WriteLine("Device sending {0} messages to IoTHub...\n", MESSAGE_COUNT);
    
        for (int count = 0; count < MESSAGE_COUNT; count++)
        {
            temperature = rnd.Next(20, 35);
            humidity = rnd.Next(60, 80);
            dataBuffer = string.Format("{{\"deviceId\":\"{0}\",\"messageId\":{1},\"temperature\":{2},\"humidity\":{3}}}", deviceId, count, temperature, humidity);
            Message eventMessage = new Message(Encoding.UTF8.GetBytes(dataBuffer));
            eventMessage.Properties.Add("temperatureAlert", (temperature > TEMPERATURE_THRESHOLD) ? "true" : "false");
            Console.WriteLine("\t{0}> Sending message: {1}, Data: [{2}]", DateTime.Now.ToLocalTime(), count, dataBuffer);
    
            await deviceClient.SendEventAsync(eventMessage);
        }
    }
    
  8. 最后,将以下代码行添加到 Main 函数,并根据设置需要替换占位符 device-idyour-iot-hub-nameabsolute-path-to-your-device-pfx-fileFinally, add the following lines of code to the Main function, replacing the placeholders device-id, your-iot-hub-name and absolute-path-to-your-device-pfx-file as required by your setup.

    try
    {
        var cert = new X509Certificate2(@"<absolute-path-to-your-device-pfx-file>", "1234");
        var auth = new DeviceAuthenticationWithX509Certificate("<device-id>", cert);
        var deviceClient = DeviceClient.Create("<your-iot-hub-name>.azure-devices.cn", auth, TransportType.Amqp_Tcp_Only);
    
        if (deviceClient == null)
        {
            Console.WriteLine("Failed to create DeviceClient!");
        }
        else
        {
            Console.WriteLine("Successfully created DeviceClient!");
            SendEvent(deviceClient).Wait();
        }
    
        Console.WriteLine("Exiting...\n");
    }
    catch (Exception ex)
    {
        Console.WriteLine("Error in sample: {0}", ex.Message);
    }
    

    此代码通过创建 X.509 设备的连接字符串连接到 IoT 中心。This code connects to your IoT hub by creating the connection string for your X.509 device. 成功连接后,此代码将温度和湿度事件发送到中心,并等待其响应。Once successfully connected, it then sends temperature and humidity events to the hub, and waits for its response.

  9. 运行应用。Run the app. 由于此应用程序访问 .pfx 文件,因此你可能需要以管理员身份运行此应用。Because this application accesses a .pfx file, you may need to run this app as an administrator.

    1. 生成 Visual Studio 解决方案。Build the Visual Studio solution.

    2. 使用“以管理员身份运行”打开新的命令提示符窗口。Open a new Command Prompt window by using Run as administrator.

    3. 导航到包含你的解决方案的文件夹,然后导航到解决方案文件夹中的 bin/Debug 路径。Navigate to the folder that contains your solution, then navigate to the bin/Debug path within the solution folder.

    4. 在命令提示符下运行应用程序 SimulateX509Device.exeRun the application SimulateX509Device.exe from the command prompt.

    应会看到,设备已成功连接到中心并在发送事件。You should see your device successfully connecting to the hub and sending the events.

    运行设备应用

后续步骤Next steps

若要详细了解如何保护 IoT 解决方案,请参阅:To learn more about securing your IoT solution, see:

若要进一步探索 IoT 中心的功能,请参阅:To further explore the capabilities of IoT Hub, see: