Generating X.509 Certificates with Private and Public Keys for IoT Device Security

Introduction

In this article, we will explore the process of generating an X.509 certificate with both a private and public key using PowerShell. This certificate plays a crucial role in authentication for various scenarios, including IoT devices and other types of client-to-server or server-to-client authentication.

In the previous articles, we learned about the basics of the IoT (Internet of Things) and Azure IoT platforms, and the focus of this article is on the authentication scenario involving an IoT device with an X.509 certificate. If you want to read my previous articles, then please use the following links.

What is the X.509 certificate?

The X.509 certificate is a standard format for public key certificates, as specified by the International Telecommunication Union (ITU) in the X.509 specification. It is widely used in various security protocols and applications, including TLS/SSL, for securing web communications, digital signatures, email encryption, and authentication in network communication.

An X.509 certificate contains information about the entity it identifies, such as a person, device, or organization, and it associates a public key with that entity. The certificate includes details such as the subject's name, the public key, the issuer (who issued the certificate), the expiration date, and other relevant metadata. X.509 certificates form the basis of the Public Key Infrastructure (PKI), providing a framework for secure communication by verifying the authenticity and integrity of digital entities in a networked environment.

What is the purpose of the X.509 certificate for the IoT device?

An X.509 certificate for an IoT device is like its digital identification card. This certificate contains essential information about the device, such as its name and a pair of keys, one public and one private. The public key is shared openly, allowing others to verify the device's identity, while the private key is kept securely on the device.

Think of it as a passport for your IoT device. When the device communicates with a central hub or server, it presents this digital passport (X.509 certificate) to prove it's genuine. This ensures a secure connection and helps prevent unauthorized access or tampering. In simpler terms, an X.509 certificate is the digital credential that allows an IoT device to securely participate in the digital conversations happening in the Internet of Things world.

Now, let's learn how to generate the X509 certificate step by step, which can be used during the development phase since it is difficult to purchase the X509 certificate during the development phase since it increases the cost.

Step 1. Copy the PowerShell script

Copy the provided PowerShell script and save it on your PC storage with a chosen name, ensuring the file is saved with the '.ps1' extension. An example could be 'GenerateTestCertificate.ps1' or any other name of your preference.

Note. This script is provided by Microsoft, and you can obtain it from the Microsoft Azure IoT GitHub project.

# 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

The preceding PowerShell script is a powerful tool for automating the creation of X.509 certificates, particularly useful in the context of Internet of Things (IoT) deployments, such as those involving Microsoft Azure IoT Hub. Let's dissect the key components of the script.

  • The script begins by accepting parameters such as $deviceName and $certificateValidityInYears, allowing users to customize the certificate for a specific IoT device. The default values are set to "iothubx509device1" and a certificate validity period of 1 year.
  • The heart of the script lies in the New-SelfSignedCertificate cmdlet, which generates a self-signed X.509 certificate. Noteworthy parameters include -Subject, defining the certificate's subject with details like Common Name (CN) and Organisation (O), and -TextExtension, incorporating specific extensions for IoT client authentication.
  • Once the certificate is generated, the script prompts the user for a password to secure the exported PFX file. The Export-PfxCertificate cmdlet then exports the certificate in PFX format, ensuring the protection of sensitive information.
  • Additionally, the script creates a CER file containing the Base64-encoded representation of the certificate using Set-Content. This step facilitates compatibility with various systems and services.

In essence, this script streamlines the creation and export of self-signed X.509 certificates, providing a seamless way to enhance security in IoT environments. The generated certificates can be easily integrated into IoT solutions, ensuring secure communication channels between devices and services. This automated approach significantly simplifies the otherwise intricate process of certificate generation, catering to the demands of scalable and secure IoT deployments.

Now save the above file on your machine based on your suitable location. I have saved the file on my E drive in the Cert folder, which looks like this.

File

Step 2. Launch the PowerShell Integrated Scripting Environment (ISE)

Proceed by opening the PowerShell ISE command prompt in administrative mode to ensure elevated privileges for seamless execution.

Windows PowerShell ISE

Step 3. Navigate to the Directory

Update your current directory to the location where your generated test certificate PowerShell file resides. In this guide, the file is situated within the Cert folder on the E Drive. Adjust the directory path accordingly to match your specific file location.

Administrator

In the preceding image, the CD command is used to set the path to the Cert folder, where our PowerShell script file is housed. This ensures that subsequent commands and operations are executed within the designated directory.

Step 4. Import the GenerateTestCertificate.ps1 File

As illustrated in the following image, execute the command to load the GenerateTestCertificate.ps1 file, ensuring that you provide the required parameter, which serves as the CA (common name of the certificate). Internally, this parameter can be utilized as the DeviceId for the IoT device. Adhere to the precise command syntax displayed in the image for accurate execution.

First Device

Once you have entered all the details as displayed in the image, press the Enter key on your keyboard. This action will prompt the following screen. Input the password for the PFX certificate, ensuring to remember this password, as it will be necessary during the provisioning of the device on the IoT Hub.

File image

Upon entering the designated password, proceed by clicking either the enter key or the OK button, as illustrated in the preceding image. Once the certificate generation process is successfully completed, pertinent details will be displayed on the PowerShell command prompt for your reference.

Command Prompt

Two certificates have been generated through the aforementioned process, resulting in a password-protected PKCS12-formatted file named certificate.pfx and a public key certificate file named certificate.cer, both of these certificate files are conveniently stored in the same location as your GenerateTestCertificate.ps1 file. To locate these files, navigate to the "cert" folder on your E drive, where you will find the aforementioned certificates.

Certificate

As you see in the preceding image, the X.509 self-signed certificates have been successfully generated. These certificates serve distinct yet crucial roles: the password-protected PKCS12 formatted file named "certificate.pfx" and the public key certificate file named "certificate.cer."

Both certificates play integral roles in authenticating a singular device. The public key certificate is employed for enrolling the device on the Azure Device Provisioning Service, while the password is protected.Pfx file (certificate.pfx) is responsible for device identification and provisioning on the IoT Hub. Together, they form a robust authentication mechanism to ensure the secure and seamless integration of the device within the designated ecosystem.

Notes

  • The certificates created using this process are designated for testing purposes only.
  • Strictly avoid deploying these certificates in a production environment.
  • For production requirements, it is highly recommended to purchase certificates from the respective device certificate authority.

Summary

I hope that from the preceding explanation, you have learned how to create the X.509 test certificate. In my next article, we will explore the process of enrolling an X.509 device on the Azure Device Provisioning Service and provisioning the device on the Azure IoT Hub. If you encounter any challenges or have questions during the certificate generation process, feel free to use the comment box to seek assistance. I look forward to addressing your queries and guiding you through the upcoming article on device enrollment and provisioning in the Azure ecosystem.

Related Articles