forked from Azure/azure-iot-sdk-csharp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProgram.cs
136 lines (117 loc) · 5.6 KB
/
Program.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.Azure.Devices.Client;
using Microsoft.Azure.Devices.Provisioning.Client;
using Microsoft.Azure.Devices.Provisioning.Client.Transport;
using Microsoft.Azure.Devices.Shared;
using System;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
namespace ProvisioningDeviceClientX509
{
class Program
{
// In your Device Provisioning Service please go to "Manage enrollments" and select "Individual Enrollments".
// Select "Add" then fill in the following:
// Mechanism: X.509
// Certificate:
// You can generate a self-signed certificate by running the GenerateTestCertificate.ps1 powershell script.
// Select the public key 'certificate.cer' file. ('certificate.pfx' contains the private key and is password protected.)
// For production code, it is advised that you install the certificate in the CurrentUser (My) store.
// DeviceID: iothubx509device1
private const string GlobalDeviceEndpoint = "global.azure-devices-provisioning.net";
private static string s_idScope;
private static string s_certificateFileName = "certificate.pfx";
public static async Task RunSample(X509Certificate2 certificate)
{
using (var security = new SecurityProviderX509Certificate(certificate))
// using (var transport = new ProvisioningTransportHandlerHttp())
using (var transport = new ProvisioningTransportHandlerAmqp(TransportFallbackType.TcpOnly))
// using (var transport = new ProvisioningTransportHandlerMqtt(TransportFallbackType.TcpOnly))
{
ProvisioningDeviceClient provClient =
ProvisioningDeviceClient.Create(GlobalDeviceEndpoint, s_idScope, security, transport);
Console.WriteLine($"RegistrationID = {security.GetRegistrationID()}");
Console.Write("ProvisioningClient RegisterAsync . . . ");
DeviceRegistrationResult result = await provClient.RegisterAsync();
Console.WriteLine($"{result.Status}");
Console.WriteLine($"ProvisioningClient AssignedHub: {result.AssignedHub}; DeviceID: {result.DeviceId}");
if (result.Status != ProvisioningRegistrationStatusType.Assigned) return;
IAuthenticationMethod auth = new DeviceAuthenticationWithX509Certificate(result.DeviceId, certificate);
using (DeviceClient iotClient = DeviceClient.Create(result.AssignedHub, auth))
{
Console.WriteLine("DeviceClient OpenAsync.");
await iotClient.OpenAsync();
Console.WriteLine("DeviceClient SendEventAsync.");
await iotClient.SendEventAsync(new Message(Encoding.UTF8.GetBytes("TestMessage")));
Console.WriteLine("DeviceClient CloseAsync.");
await iotClient.CloseAsync();
}
}
}
public static void Main(string[] args)
{
if (string.IsNullOrWhiteSpace(s_idScope) && (args.Length < 1))
{
Console.WriteLine("ProvisioningDeviceClientX509 sample requires your Azure Device Provisioning Service <IDScope>");
return;
}
s_idScope = args[0];
string certificatePassword = ReadCertificatePassword();
var certificateCollection = new X509Certificate2Collection();
certificateCollection.Import(s_certificateFileName, certificatePassword, X509KeyStorageFlags.UserKeySet);
X509Certificate2 certificate = null;
foreach (X509Certificate2 element in certificateCollection)
{
Console.WriteLine($"Found certificate: {element?.Thumbprint} {element?.Subject}; PrivateKey: {element?.HasPrivateKey}");
if (certificate == null && element.HasPrivateKey)
{
certificate = element;
}
else
{
element.Dispose();
}
}
if (certificate == null)
{
Console.WriteLine($"ERROR: {s_certificateFileName} did not contain any certificate with a private key.");
return;
}
else
{
Console.WriteLine($"Using certificate {certificate.Thumbprint} {certificate.Subject}");
}
RunSample(certificate).GetAwaiter().GetResult();
}
private static string ReadCertificatePassword()
{
var password = new StringBuilder();
Console.WriteLine($"Enter the PFX password for {s_certificateFileName}:");
while(true)
{
ConsoleKeyInfo key = Console.ReadKey(true);
if (key.Key == ConsoleKey.Backspace)
{
if (password.Length > 0)
{
password.Remove(password.Length - 1, 1);
Console.Write("\b \b");
}
}
else if (key.Key == ConsoleKey.Enter)
{
Console.WriteLine();
break;
}
else
{
Console.Write('*');
password.Append(key.KeyChar);
}
}
return password.ToString();
}
}
}