Generating X.509 IoT Device Certificate Using PowerShell

The X.509 certificate helps to identify the device on IoT Hub using public and private keys stored within the certificate.

The developer test many scenarios during the development, so every time buying the new certificate and device for development is not possible, so we required something virtual but gives a real-life experience, so by considering time and cost, we will create the test certificates locally and test the Azure IoT experience. Microsoft has provided the sample PowerShell script on GitHub to generate the X.509 certificates.

Step 1: Copy the PowerShell Script

Copy the following PowerShell script and save it on your PC storage location as GenerateTestCertificate.ps1 or whatever name you wish, just make sure you have saved the file having an extension .ps1.

# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE file in the project root for full license information.

Param(
    $deviceName = "iothubx509device1",
    $certificateValidityInYears = 1
)

$cert = New-SelfSignedCertificate `
    -Type Custom `
    -Subject "CN=$deviceName, O=TEST, C=US" `
    -KeySpec Signature `
    -KeyExportPolicy Exportable `
    -HashAlgorithm sha256 `
    -KeyLength 2048 `
    -TextExtension @("2.5.29.37={text}1.3.6.1.5.5.7.3.2") `
    -CertStoreLocation "Cert:\CurrentUser\My" `
    -NotAfter (Get-Date).AddYears($certificateValidityInYears)

Write-Host "Generated the certificate:"
Write-Host $cert

Write-Host "Enter the PFX password:"
$password = Read-Host -AsSecureString

$cert | Export-PfxCertificate -FilePath certificate.pfx -Password $password
Set-Content -Path certificate.cer -Value ([Convert]::ToBase64String($cert.RawData)) -Encoding Ascii

I have saved the file on my E drive in the Cert folder which looks like as follows.


Step 2: Open the PowerShell ISE

Now open the PowerShell ISE command prompt in administrative mode as follows.


Make sure it's PowerShell ISE, not just PowerShell command prompt.

Step 3: Change The Directory

Change the directory location where your generate test certificate PowerShell file is located. In this article, the file is located under the E Drive Cert folder.


In the preceding image, the path is set to the Cert folder using the CD command in which our PowerShell Script file is located.

Step 4: Load GenerateTestCertificate.ps1 File

As shown in the following image, load the GenerateTestCertificate.ps1 file and  provide the parameter which is a CA (common name of the certificate) which internally can be become as a DeviceId of the IoT device. Make sure you are following the command syntax exactly as shown in the below image.


Once all details are given as shown in the image, then press the enter key on your keyboard, it will prompt the following screen. Provide the password for the pfx certificate and remember the password which is required during the provisioning the device on IoT Hub.


Once you enter the password press the enter or OK button as shown in the preceding image. Once the certificates are successfully generated, the following details are shown on the PowerShell command prompt.



There are two certificates created with the preceding procedure that are password-protected PKCS12 formatted file (certificate.pfx) and public key certificate file (certificate.cer).

The created certificates files are stored in the same location as your GenerateTestCertificate.ps1 file. Now navigate to the my E drive cert folder where you will see the created file.


As you see in the preceding image, the X.509 self signed certificates are created that are password-protected PKCS12 formatted file certificate.pfx and public key certificate file certificate.cer.

Both the certificates are required to authenticate the single device that is a public key certificate used to enroll the device on Azure device provisioning service and password protected .Pfx required to identify the device identity and provision the device on IoT Hub.

Note

  • These certificates are only for testing purposes, don’t use for the production. 
  • Please buy the certificates from the respective device certificate authority for production requirement.

Summary

I hope from the preceding explanation you have learned how to create the X.509 test certificate using the PowerShell. If you are facing any issue during generating the certificates, then you can use the comment box to ask your queries.

Related articles

How To Create X.509 Device Certificate

During the IoT application development we need the X.509 certificates for those devices which are depends on the X.509 based authentication. The developer test many scenarios during the development, so every time buying the new certificate and device for development is not possible, so we required something virtual but gives a real-life experience, so by considering time and cost, we will create the test certificates locally and test the Azure IoT experience. Microsoft has provided the sample PowerShell script on GitHub to generate the X.509 certificates.

What is use of X.509 Certificate?

The X.509 certificate helps to identify the device on IoT Hub using public and private keys stored within the certificate.

Step 1: Copy the PowerShell Script

Copy the following PowerShell script and save it on your PC storage location as GenerateTestCertificate.ps1 or whatever name you wish, just make sure you have saved the file having an extension .ps1.

# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE file in the project root for full license information.

Param(
    $deviceName = "iothubx509device1",
    $certificateValidityInYears = 1
)

$cert = New-SelfSignedCertificate `
    -Type Custom `
    -Subject "CN=$deviceName, O=TEST, C=US" `
    -KeySpec Signature `
    -KeyExportPolicy Exportable `
    -HashAlgorithm sha256 `
    -KeyLength 2048 `
    -TextExtension @("2.5.29.37={text}1.3.6.1.5.5.7.3.2") `
    -CertStoreLocation "Cert:\CurrentUser\My" `
    -NotAfter (Get-Date).AddYears($certificateValidityInYears)

Write-Host "Generated the certificate:"
Write-Host $cert

Write-Host "Enter the PFX password:"
$password = Read-Host -AsSecureString

$cert | Export-PfxCertificate -FilePath certificate.pfx -Password $password
Set-Content -Path certificate.cer -Value ([Convert]::ToBase64String($cert.RawData)) -Encoding Ascii

I have saved the file on my E drive in the Cert folder which looks like as follows.


Step 2: Open the PowerShell ISE

Now open the PowerShell ISE command prompt in administrative mode as follows.


Make sure it's PowerShell ISE, not just PowerShell command prompt.

Step 3: Change The Directory

Change the directory location where your generate test certificate PowerShell file is located. In this article, the file is located under the E Drive Cert folder.


In the preceding image, the path is set to the Cert folder using the CD command in which our PowerShell Script file is located.

Step 4: Load GenerateTestCertificate.ps1 File

As shown in the following image, load the GenerateTestCertificate.ps1 file and  provide the parameter which is a CA (common name of the certificate) which internally can be become as a DeviceId of the IoT device. Make sure you are following the command syntax exactly as shown in the below image.


Once all details are given as shown in the image, then press the enter key on your keyboard, it will prompt the following screen. Provide the password for the pfx certificate and remember the password which is required during the provisioning the device on IoT Hub.


Once you enter the password press the enter or OK button as shown in the preceding image. Once the certificates are successfully generated, the following details are shown on the PowerShell command prompt.



There are two certificates created with the preceding procedure that are password-protected PKCS12 formatted file (certificate.pfx) and public key certificate file (certificate.cer).

The created certificates files are stored in the same location as your GenerateTestCertificate.ps1 file. Now navigate to the my E drive cert folder where you will see the created file.


As you see in the preceding image, the X.509 self signed certificates are created that are password-protected PKCS12 formatted file certificate.pfx and public key certificate file certificate.cer.

Both the certificates are required to authenticate the single device that is a public key certificate used to enroll the device on Azure device provisioning service and password protected .Pfx required to identify the device identity and provision the device on IoT Hub.

Note

  • These certificates are only for testing purposes, don’t use for the production. 
  • Please buy the certificates from the respective device certificate authority for production requirement.

Summary

I hope from the preceding explanation you have learned how to create the X.509 test certificate. In my next article, we will learn how to enroll X.509 device on Azure Device provisioning service and provision the device on Azure IoT Hub. If you are facing any issue during generating the certificates then you can use the comment box to ask your queries.

If you are new to the IoT, then you can read my previous articles using the following given links to learn more about the IoT.

Related article

Creating X.509 Certificate for Azure IoT Hub Device Provisioning Service

In this article, we will learn how to create the self-signed X.509 device test certificate for Azure IoT Hub Device Provisioning Service and Azure IoT Hub which can be helpful during the development instead of relaying on the real certificate. If you are new to the IoT, then you can read my previous articles using the following given links to learn more about the IoT.

What is use of X.509 Certificate?

The X.509 certificate helps to identify the device on IoT Hub using public and private keys stored within the certificate.

How To Create X.509 Test Certificates locally?

During the IoT application development we need the X.509 certificates for those devices which are depends on the X.509 based authentication. The developer test many scenarios during the development, so every time buying the new certificate and device for development is not possible, so we required something virtual but gives a real-life experience, so by considering time and cost, we will create the test certificates locally and test the Azure IoT experience. Microsoft has provided the sample PowerShell script on GitHub to generate the X.509 certificates.

Step 1: Copy the PowerShell Script

Copy the following PowerShell script and save it on your PC storage location as GenerateTestCertificate.ps1 or whatever name you wish, just make sure you have saved the file having an extension .ps1.

# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE file in the project root for full license information.

Param(
    $deviceName = "iothubx509device1",
    $certificateValidityInYears = 1
)

$cert = New-SelfSignedCertificate `
    -Type Custom `
    -Subject "CN=$deviceName, O=TEST, C=US" `
    -KeySpec Signature `
    -KeyExportPolicy Exportable `
    -HashAlgorithm sha256 `
    -KeyLength 2048 `
    -TextExtension @("2.5.29.37={text}1.3.6.1.5.5.7.3.2") `
    -CertStoreLocation "Cert:\CurrentUser\My" `
    -NotAfter (Get-Date).AddYears($certificateValidityInYears)

Write-Host "Generated the certificate:"
Write-Host $cert

Write-Host "Enter the PFX password:"
$password = Read-Host -AsSecureString

$cert | Export-PfxCertificate -FilePath certificate.pfx -Password $password
Set-Content -Path certificate.cer -Value ([Convert]::ToBase64String($cert.RawData)) -Encoding Ascii

I have saved the file on my E drive in the Cert folder which looks like as follows.


Step 2: Open the PowerShell ISE

Now open the PowerShell ISE command prompt in administrative mode as follows.


Make sure it's PowerShell ISE, not just PowerShell command prompt.

Step 3: Change The Directory

Change the directory location where your generate test certificate PowerShell file is located. In this article, the file is located under the E Drive Cert folder.


In the preceding image, the path is set to the Cert folder using the CD command in which our PowerShell Script file is located.

Step 4: Load GenerateTestCertificate.ps1 File

As shown in the following image, load the GenerateTestCertificate.ps1 file and  provide the parameter which is a CA (common name of the certificate) which internally can be become as a DeviceId of the IoT device. Make sure you are following the command syntax exactly as shown in the below image.


Once all details are given as shown in the image, then press the enter key on your keyboard, it will prompt the following screen. Provide the password for the pfx certificate and remember the password which is required during the provisioning the device on IoT Hub.


Once you enter the password press the enter or OK button as shown in the preceding image. Once the certificates are successfully generated, the following details are shown on the PowerShell command prompt.



There are two certificates created with the preceding procedure that are password-protected PKCS12 formatted file (certificate.pfx) and public key certificate file (certificate.cer).

The created certificates files are stored in the same location as your GenerateTestCertificate.ps1 file. Now navigate to the my E drive cert folder where you will see the created file.


As you see in the preceding image, the X.509 self signed certificates are created that are password-protected PKCS12 formatted file certificate.pfx and public key certificate file certificate.cer.

Both the certificates are required to authenticate the single device that is a public key certificate used to enroll the device on Azure device provisioning service and password protected .Pfx required to identify the device identity and provision the device on IoT Hub.

Summary

I hope from the preceding explanation you have learned how to create the X.509 test certificate. In my next article, we will learn how to enroll X.509 device on Azure Device provisioning service and provision the device on Azure IoT Hub. If you are facing any issue during generating the certificates then you can use the comment box to ask your queries.

Related article

How To Enroll IoT Device on Azure Device Provisioning Service Using X.509 Certificate

This article explains how to enroll an IoT device on Azure device provisioning service using X.509 certificate. In my previous articles on the Azure IoT series, we have learned about the Azure IoT Hub and Device Provisioning Service (DPS). If you have not read my previous articles about Azure device provisioning service yet, then please read them using the following link.As explained in the previous articles, IoT devices on the IoT hub can be connected in two ways that are
  • Using Device Provisioning Service then Azure IoT Hub
  • Directly to the Azure IoT hub
So let's learn how to enroll the IoT devices with Device Provisioning Service (DPS).

What is Device Enrollment?

Device enrollment is the process of adding the pre-configured IoT devices details on Azure device provisioning service and connect to the IoT hub on-demand or based on the requirement without any human intervention.

Now let's learn step by step how to enroll the IoT devices

Step 1: Login To Azure Portal

After login into the azure portal, find the device provisioning service which we have created in the How To Create Azure Device Provisioning Service article or if you haven't created it, then please follow the steps shown in the article and create it. I hope you have DPS services on the portal. Now find the option to manage enrollments as shown in the following image.


 Device Provisioning Service (DPS) provide the  following two concepts,
  • Individual Enrollment
  • Group Enrollment
In this article we will learn about the individual device enrollment

What is Individual Enrollment?

This allows enrolling one device at a time that allows unique configuration per device. 

Step 2:  Navigate To Azure Device Provisioning Service Instance

To create the individual enrollment, select manage enrollment, then click on the Add individual enrollment as shown in the following image.


After clicking on the Add individual enrollment button, the following screen will get appeared as shown in the step 3.

Step 3: Provide Enrollment Details and X.509 Certificate

Provide the required details including the X.509 security certificate


As shown in the preceding image, we need some details to create the enrollment entry,
  • Attestation Mechanism
  • Primary Certificate
  • Secondary certificate
  • IoT Hub Device Id
  • IoT Edge Device
  • Device Allocation Policy
  • Choose IoT Hub
  • Device Re-Provisioning
  • Device Twin State
  • Enable Entry
These details differ based on the chosen attestation mechanism type as shown in the following image

What is Attestation Mechanism?

The attestation Mechanism is the process of cross verifying the enrolled device identity during the device registration on IoT Hub, Device Provisioning Service supports the following attestation mechanism

  • X.509
  • TPM
  • SymetricKey
Now let's learn how to enroll devices using the above attestation mechanisms

Device Enrollment Using X.509

The X.509 is the security certificate which includes the authentication details about the device. These certificates can be provided by a device manufacturer which they can buy from the authorized certificate provider such as CA. For development and testing purposes we can create the X.509 certificate by using the tools like PowerShell or OpenSSl etc. I will show in a separate article how to generate the X.509 certificates.

I have X.509 certificates on my pc which I have generated using PowerShell. If you want to know how to create the X.509 test certificate, then you can learn by using the following link.


Now choose X.509 attestation mechanism from the dropdown list and choose the device.cer certificate as shown in the following image.


After uploading the certificate provide the following optional details

IoT Hub Device Id

Provide the Device Id name which is unique per X.509 certificate. This is optional, if you do not provide the device Id, then the registration id becomes the deviceId on the Azure IoT hub.

IoT Edge Device


Choose between true or false, which indicates if it's true, then it's an edge device, else it's an IoT device.

Device Allocation Policy

This chosen policy decides how IoT devices allocate to the IoT Hub, you can read my previous article to understand the details about the device allocation policies.

Choose IoT Hub

Device provisioning service can be linked with multiple IoT Hubs, you can choose on which IoT hub, device should register or you can let it decide by device allocation policy.

Device Re-Provisioning Policy

There may be a requirement to re-provision the device, so during this process, it allows whether to keep the previous data or not.

Initial Device Twin State

The initial device twin allows storing the custom properties about the device or whatever you want. Mostly, the device twin is used to keep the device-related information such as the path of the device upgrade package file or client details etc.

Example,


{  
  "tags": {},  
  "properties": {  
    "desired": {  
      "devicetype": "waterflow",  
      "client": "www.compilemode.com"  
    }  
  }  
}  

Enable Entry

This option allows enabling to disable the enrollment entry.

Now providing all the above details, click on the save. After successfully creating the enrollment entry, the following notification will be shown.


Now go to our created device provisioning service (DPS) instance and see the created enrollment entry as follows.



In the preceding image, you see the registration id as my device which comes from the certificate common name (CN).

Device Enrollment Using Symmetric Key

Now choose the symmetric key attestation mechanism from the dropdown list and check on auto-generated keys as shown in the following image.



Provide the required details as we did in the X.509 enrollment, in the symmetric key attestation mechanism we need to provide the registration id but in X.509 enrollment the registration id taken from the certificate common name (CN).

Now providing all the above details, click on the save, now go to our created device provisioning service (DPS) instance and see the created enrollment entry as follows.


As shown in the preceding image, we see the registration id reg100 is added, follow the same steps for other types of attestation mechanism, and enroll the device.

Summary

I hope this article is useful to understand how to enroll the device using azure device provisioning service with X.509 certificate.

Introduction To Azure IoT Hub

In my last article, we learned about the Azure device provisioning service, which allows us to manage IoT devices. If you have not read my previous article about Azure device provisioning service yet, then please read it using the following link
Now we have a platform to manage the IoT devices, but what about connecting the devices to some platform and getting the data from those connected devices? We must connect the device to some gateway platform to establish a secure connection between the cloud and the device to exchange the data. So, in this article we will learn about the Azure IoT hub and the role of IoT Hub in managing the IoT devices communication and telemetry data.

What is Azure IoT?

Azure IoT is the IoT gateway for IoT devices which allows bi-directional communication between IoT devices to cloud and cloud to IoT devices. Azure IoT can process the millions of IoT devices and route the messages to specific data storage platforms.

Key Advantages of Azure IoT

  • Built-in UI to manage and monitor the IoT devices
  • Allows us to capture entire device lifecycle events using the device life cycle change event feature
  • Allows us to upgrade the firmware of single or bulk of devices using the automatic device management feature
  • Allows the bi-directional communication between IoT devices to cloud and cloud to IoT devices
  • IoT hub allows us to connect the edge devices and IoT devices its means IoT hub capable to connect low powered and high processing devices
  • IoT devices can send telemetry data as well as can connect devices over a network using AMQP, MQTT, and HTTPS protocol to the Azure IoT hub
  • Azure IoT hub supports the wide range of IoT device authentication mechanisms such as X509, TPM, and Symmetric Key
  • Azure IoT hub allows routing the messages to the specific data store and data process platform using the message routing feature
  • Azure IoT hub allows uploading the file for a specific device which can be used for device upgradation for storing device process-related information
  • Azure IoT hub IoT Hub allows us to send commands to the device which can help to change the behavior of the device using the Cloud to Device message feature
  • Provides the device twin feature to store the metadata or any specific information about the IoT devices
  • Azure IoT hub is supposed to be a secure platform for communication and authentication for the devices with the help of communication protocol AMQP, MQTT and HTTPS and authentication mechanisms such as X509, TPM, and symmetric key
  • Provides the wide range of SDK which help to connect to the IoT hub and devices programmatically C#, java, python, C, Node.js, android SDK also IoT hub supports api
  • Provides the feature to enable or disable the connected IoT devices

Creating An Azure IoT Hub Using Azure Portal

Azure IoT Hub can be created using:
  • Azure CLI
  • SDK
  • API
  • ARM
  • Azure portal 
In this article, we will be creating an IoT hub using the portal so we can avoid confusion for beginners. Now let’s start creating the azure IoT hub step-by-step via the Azure portal.

Prerequisites
 
To create any Azure service, we need an active Azure subscription, whether it’s a paid or trial subscription. I am assuming you have an active Azure subscription

Step 1: Go to the Azure Portal

Navigate to the portal.azure.com using your browser and login into the portal with valid credentials, as shown in the following image:


After a successful login, the page will be redirected to the Azure portal, by default, the dashboard page is set as:


Step 2: Create Azure IoT

Find the create resource option which can be found on the left top side of the portal as shown in the following image or follow any other option which you may know to create the resource (service) in the Azure portal:



Click on the left side option to create a resource & type IoT hub into the populated search box, it will pop up the following screen as:



As shown in the preceding image click on the create button, it will show the following screen:



Provide required details as shown in the preceding image:
  • Subscription: Choose the available azure subscription which you want to use for creating service from drop-down list
  • Resource Group: Choose an existing resource group or create a new resource group that you may want to use.
  • Region: Choose the deployment location for IoT hub device provisioning from the given list. However, the device provisioning service is global and associated with any specific location, but you must specify a location for the resource group where the metadata associated with the service profile will reside.
  • IoT Hub Name: Name of the IoT hub service which must contain only alphanumeric characters or a hyphen.
After providing all the basic required details, click to review and create the IoT hub, which skips the remaining steps, or click to choose the next step, networking. It shows the following screen to configure networking:



In the above image, we choose the connectivity method for the IoT hub which decides which network the devices can connect to the IoT hub, there are three methods:
  • Public Endpoint all Network
  • Public Endpoint selected IP addresses
  • Private Endpoint 

Public EndPoint all Network

This option allows us to connect devices to the IoT hub on all public networks for whoever has access to public URI and the required credentials.

Public Endpoint selected IP addresses

Even you have a public endpoint (URI) but want to restrict devices, you should connect from a specific IP address. Then you can define the range of IP addresses. The IoT hub allows you to connect only to devices that fall within the defined IP address range. This option gives the useful feature to allow only known networks to connect to the devices

Private EndPoint 

This is the URI or endpoint which allows us to connect devices over the private network, which gives the robust security between devices and IoT hub communication
Once you choose your intended connectivity method, click on the next step which shows the step to configure the scalability of the IoT hub as:


The preceding management step allows us to define the scalability and security of the IoT hub with the help of the following options:
  • Pricing and Scale Tier
  • IoT Hub Units
  • Defender
Pricing and Scale Tier
 
There are different types of pricing and scale tiers that decide how many messages the device sends to the IoT hub per day and what feature does it supports. The features and message frequency of IoT hub can differ based on the pricing and scale tier. The pricing tiers are categorized as:

Free Tier
 
The F1 is the free tier by using you can use the free tier of IoT hub for your learning and check how IoT hub works. it allows 8000 messages per day with limited feature

Basic Tier

The basic tier is sub-categorized into the three types as
  • B1
  • B2
  • B3
Basic tiers are suitable for development activities but you can not get all the features in this pricing and scale tier.

Standard Tier

The standard pricing and scale tier provides the most advanced features and scales for the incoming IoT messages, The standard tier subcategorized into the three types as:
  • S1
  • S2
  • S3 
These tiers are most suitable for a production environment where hyper scalability and advanced security are required. Once you choose the configuration for the IoT hub, click on the next step tags, which shows the following screen:



The tagging helps to identify or categorize the services across the line of applications, after providing tags details, click on the next step review and create, it will show the following screen to review the details before creating the service:


After reviewing details, click on the create button, it will take some time to create the service. Once the service is created, the status can be notified on the notification icon as shown in the following image: 


Now click on the Go to resource button, you will be redirected to the newly created IoT hub service as shown in the following image:


Let’s learn about the preceding Azure IoT hub key sections in brief, listed below:
  • Overview
  • Certificates
  • Built-in Endpoints
  • Query Explorer
  • IoT Devices
  • Automatic Device Management
  • Messaging
  • Security
  • Monitoring
Overview
 
The overview section of the IoT hub is like a dashboard where you can see an overview of the service details, including the charts for incoming messages, status, etc.

Certificates
 
This section allows to add and save the device certificates which can be assigned to the devices during creating or adding the devices to the IoT hub.

Built-in Endpoints
 
This section contains the details which allow us to use the IoT hub as an event hub. The event hub compatible connectionString gives almost the same functionality as an event hub without creating any instance of the event hub.

Query Explorer
 
This section allows us to query devices that reside in the IoT hub. This feature is useful to query any device from the millions of devices from the IoT hub.

IoT Devices
 
This section lets you add the different types of IoT devices and related configuration.

Automatic Device Management
 
This section allows us to upgrade the firmware of individual or bulk of IoT devices based on the properties of the device such as tags or deviceId.

Messaging
 
This feature allows to capture the IoT device messages and their related events also you can route the messages to any other service such as data store etc.

Security
 
This section allows to secure the IoT devices using the IoT defender feature and create the security-related alerts

Monitoring

This section allows to monitor the logs related to the IoT hub, you can set any filter or rule for monitoring and create the alerts

Summary

I hope this article was useful for understanding the basics of the Azure IoT hub service.

Next Suggested Article
Articles you may interested 

ARM Template To Create Azure IoT Hub with File Upload Support

In this article we will learn how to create azure IoT hub with file upload support. The azure IoT hub supports the file upload feature to maintain the files related to the IoT devices which can be used to store the package files to upgrade the device or any files which are required for certain requirement related to the IoT devices.

Template.json

{
  "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "keyVaultUri": {
      "type": "string"
    },
    "appInsightsKey": {
      "type": "string"
    },
    "serviceName": {
      "type": "string",
      "defaultValue": "SmartDevicesIoTHub"
    },
    "region": {
      "type": "string",
      "defaultValue": "West Europe"
    },
    "location": {
      "type": "string",
      "defaultValue": "eastus"
    },
    "containerName": {
      "type": "string",
      "defaultValue": "AzureblobStorageContainerName"
    },
    "iotHubAccessPolicies": {
      "type": "object"
    }
  },
    "resourceGroup": "[('YourAzureResourceGroupName')]",
    "AzureStorageAccountName": "[concat('YourStorageAccountName',toLower(parameters('location')))]",
    "storageAccountApiVersion": "2018-07-01",
    "iotHubName": "[(parameters('serviceName'))]",
    "iothubApiVersion": "2018-04-01",
    "eventHubDefaultRetentionInDays": 7
  },
  "resources": [
    {
      "type": "Microsoft.Storage/storageAccounts",
      "name": "[variables('AzureStorageAccountName')]",
      "location": "[parameters('region')]",
      "apiVersion": "[variables('storageAccountApiVersion')]",
      "sku": {
        "name": "Standard_LRS",
        "tier": "Standard"
      },
      "kind": "StorageV2",
      "properties": {
        "accessTier": "Hot"

      },
      "resources": [
        {
          "name": "[concat('default/', parameters('containerName'))]",
          "type": "blobServices/containers",
          "apiVersion": "2018-07-01",
          "dependsOn": [
            "[variables('AzureStorageAccountName')]"
          ]
        }
      ]
    },
    {
      "name": "[variables('iotHubName')]",
      "type": "Microsoft.Devices/IotHubs",
      "apiVersion": "[variables('iothubApiVersion')]",
      "location": "[parameters('region')]",
      "tags": "[variables('tags')]",
      "sku": {
        "name": "S1",
        "tier": "Standard",
        "capacity": 1
      },
      "dependsOn": [
        "[variables('AzureStorageAccountName')]"
      ],
      "properties": {
        "enableFileUploadNotifications": true,
        "authorizationPolicies": [
          {
            "keyName": "[parameters('iotHubAccessPolicies').iotHubOwner.name]",
            "rights": "[parameters('iotHubAccessPolicies').iotHubOwner.rights]",
            "primaryKey": "[parameters('iotHubAccessPolicies').iotHubOwner.primaryKey]",
            "secondaryKey": "[parameters('iotHubAccessPolicies').iotHubOwner.secondaryKey]"
          }
        ],
        "eventHubEndpoints": {
          "events": {
            "retentionTimeInDays": "[variables('eventHubDefaultRetentionInDays')]",
            "partitionCount": 4,
            "path": "[variables('iotHubName')]"
          },
          "operationsMonitoringEvents": {
            "retentionTimeInDays": "[variables('eventHubDefaultRetentionInDays')]",
            "partitionCount": 4
          }
        },
        "storageEndpoints": {
          "$default": {
            "containerName": "[parameters('containerName')]",
            "connectionString": "[Concat('DefaultEndpointsProtocol=https;AccountName=',variables('AzureStorageAccountName'),';AccountKey=',listKeys(resourceId('Microsoft.Storage/storageAccounts', variables('AzureStorageAccountName')), providers('Microsoft.Storage', 'storageAccounts').apiVersions[0]).keys[0].value)]",
            "sasTtlAsIso8601": "PT1H"
          }
        },
        "messagingEndpoints": {
          "fileNotifications": {
            "lockDurationAsIso8601": "PT1M",
            "ttlAsIso8601": "P1D",
            "maxDeliveryCount": 10
          }
        }
      }
    }
  ]
}

Note

The preceding is the just template and you need to replace and modify the template as per your environment details. The following things need to be replaced
  • Resource group Name
  • Azure IoT Hub Name
  • Azure Storage Container Name 
  • Azure Storage Account Name
You can run the preceding template with the help of PowerShell.

Summary

I hope from the preceding article you have learned how to create the IoT hub with file upload support using ARM template.

Related Articles

Individual Device Enrollment Using Azure Device Provisioning Service with X.509 Certificate

In my previous articles on the azure IoT series, we have learned about the Azure IoT Hub and Device Provisioning Service (DPS). If you have not read my previous articles about Azure device provisioning service yet, then please read them using the following link

As explained in the previous articles IoT devices to the IoT hub can be connected in two ways that are either using Device Provisioning Service (DPS) or directly to the IoT hub, So let's learn how to enroll the IoT devices with Device Provisioning Service (DPS).

What is Device Enrollment?

Device enrollment is the process of adding the pre-configured IoT devices details on Azure device provisioning service and connect to the IoT hub on-demand or based on the requirement without any human intervention.

Now let's learn step by step how to enroll the IoT devices

Login To Azure Portal

After login into the azure portal Find the device provisioning service which we have created in the How To Create Azure Device Provisioning Service or if you haven't created then please follow the steps shown in the article and create it. Hope you have DPS services on the portal, Now find the option manage enrollments as shown in the following image


 Device Provisioning Service (DPS) provide the  following two concepts,
  • Individual Enrollment
  • Group Enrollment
In this article we will learn about the individual device enrollment

What is Individual Enrollment?

This allows enrolling one device at a time that allows unique configuration per device. To create the individual enrollment select manage enrollment then click on Add individual enrollment as shown in the following image


After clicking on Add individual enrollment button the following screen will get appears


As shown in the preceding image, we need some details to create the enrollment entry,
  • Attestation Mechanism
  • Primary Certificate
  • Secondary certificate
  • IoT Hub Device Id
  • IoT Edge Device
  • Device Allocation Policy
  • Choose IoT Hub
  • Device Re-Provisioning
  • Device Twin State
  • Enable Entry
These details differ based on the chosen attestation mechanism type as shown in the following image

What is Attestation Mechanism?

The attestation Mechanism is the process of cross verifying the enrolled device identity during the device registration on IoT Hub, Device Provisioning Service supports the following attestation mechanism

  • X.509
  • TPM
  • SymetricKey
Now let's learn how to enroll devices using the above attestation mechanisms

Device Enrollment Using X.509

X.509 certificate is the security certificate which includes the authentication details about the device, these certificates can be provided by a device manufacturer which they can buy from the authorized certificate provider such as CA. For development and testing purposes we can create the x.509 certificate by using the tools like PowerShell or Openssl etc. I will show in the separate article how to generate an x.509 certificates.

I have X.509 certificates on my pc which I have generated using the PowerShell


Now choose X.509 attestation mechanism from the dropdown list and choose device.cer certificate as shown in the following image


After uploading the certificate provide the following optional details

IoT Hub Device Id

Provide the Device Id name which is the unique per x.509 certificate, This is optional, if you do not provide the device Id then registration id becomes the deviceid on Azure IoT hub

IoT Edge Device


Choose between true or false which indicates if its true then its as edge device else its an IoT device

Device Allocation Policy

This chosen policy decides how IoT device allocate to the IoT Hub, you can read my previous article on same to understand the details about the device allocation policies

Choose IoT Hub


DPS linked with multiple IoT Hubs, you can choose on which IoT hub device should register or you can let it decide by device allocation policy

Device Re-Provisioning Policy

There may be a requirement to re-provision the device, so during this process, it allows whether to keep the previous data or not.

Initial Device Twin State


The initial device twin allows storing the custom properties about the device or whatever you want. mostly device twin used to keep the device-related information such as the path of device upgrade package file or client details etc.

Example,

{  
  "tags": {},  
  "properties": {  
    "desired": {  
      "devicetype": "waterflow",  
      "client": "www.compilemode.com"  
    }  
  }  
}  

Enable Entry

This option allows enabling to disable the enrollment entry

Now providing the all above details click on save, after successfully creating the enrollment entry the following notification will be shown


Now go to our created device provisioning service (DPS) instance and see the created enrollment entry as follows



In the preceding image, you see the registration id as my device which is come from the certificate common name (CN).

Device Enrollment Using Symmetric Key

Now choose the symmetric key attestation mechanism from the dropdown list and check on auto-generated keys as shown in the following image


Provide the required details as we did in the x.509 enrollment, in the symmetric key attestation mechanism we need to provide the registration id but in x.509 enrollment the registration id taken from the certificate common name (CN).

Now providing the all above details click on save, now go to our created device provisioning service (DPS) instance and see the created enrollment entry as follows


As shown in the preceding image we see the registration id reg100 is go added, follow the same steps for other types of attestation mechanism, and enroll the device

Summary

I hope this article is useful to understand how to enroll the device using azure device provisioning service with X.509 certificate. In this series of Azure IoT, next, we will learn about the enrollment group of devices.

www.CodeNirvana.in

Protected by Copyscape
Copyright © Compilemode