| title | How to connect a device to IoT Hub using a certificate (Java) |
|---|---|
| titleSuffix | Azure IoT Hub |
| description | Learn how to connect a device to IoT Hub using a certificate and the Azure IoT Hub SDK for Java. |
| author | SoniaLopezBravo |
| ms.author | sonialopez |
| ms.service | iot-hub |
| ms.devlang | java |
| ms.topic | include |
| ms.manager | lizross |
| ms.date | 12/12/2024 |
To connect a device to IoT Hub using an X.509 certificate:
- Build the SSLContext object using buildSSLContext.
- Add the
SSLContextinformation to a ClientOptions object. - Call DeviceClient using the
ClientOptionsinformation to create the device-to-IoT Hub connection.
This example shows certificate input parameter values as local variables for clarity. In a production system, store sensitive input parameters in environment variables or another more secure storage location. For example, use Environment.GetEnvironmentVariable("PUBLICKEY") to read a public key certificate string environment variable.
private static final String publicKeyCertificateString =
"-----BEGIN CERTIFICATE-----\n" +
"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" +
"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" +
"-----END CERTIFICATE-----\n";
//PEM encoded representation of the private key
private static final String privateKeyString =
"-----BEGIN EC PRIVATE KEY-----\n" +
"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" +
"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" +
"-----END EC PRIVATE KEY-----\n";
SSLContext sslContext = SSLContextBuilder.buildSSLContext(publicKeyCertificateString, privateKeyString);
ClientOptions clientOptions = ClientOptions.builder().sslContext(sslContext).build();
DeviceClient client = new DeviceClient(connString, protocol, clientOptions);For more information about certificate authentication, see:
- Authenticate identities with X.509 certificates
- Tutorial: Create and upload certificates for testing
For working samples of device X.509 certificate authentication, see: