.net 如何在MQTTnet中使用客户端证书和密钥?

0yycz8jy  于 2023-11-20  发布在  .NET
关注(0)|答案(1)|浏览(385)

我想用MQTTnet复制这个Python代码示例。

  1. client = mqtt.Client(str(uuid4()))
  2. current = dirname(__file__)
  3. cerfile = join(current, "rcm_certchain_pem.cer")
  4. keyfile = join(current, "rcm_pem_privkey.pkcs8")
  5. context = create_default_context(Purpose.CLIENT_AUTH)
  6. context.load_cert_chain(cerfile, keyfile)
  7. client.tls_set_context(context)
  8. client.tls_insecure_set(True)
  9. client.connect("192.168.1.X", 1234)

字符串
我在MQTTnet上试过了。

  1. var manager = new MqttFactory().CreateMqttClient();
  2. var options = new MqttClientOptionsBuilder()
  3. .WithCleanSession()
  4. .WithClientId(Guid.NewGuid().ToString())
  5. .WithTcpServer(address, port)
  6. .WithTls(new MqttClientOptionsBuilderTlsParameters()
  7. {
  8. AllowUntrustedCertificates = true,
  9. Certificates = new List<X509Certificate>
  10. {
  11. new X509Certificate2("Assets/rcm_certchain_pem.cer"),
  12. new X509Certificate2("Assets/rcm_pem_privkey.pkcs8")
  13. },
  14. UseTls = true,
  15. })
  16. .WithKeepAlivePeriod(TimeSpan.FromSeconds(60))
  17. .Build();
  18. await manager.ConnectAsync(options, CancellationToken.None);


我总是有这个加密相关的错误。

  1. <Internal.Cryptography.CryptoThrowHelper+WindowsCryptographicException: Cannot find the requested object.

w8f9ii69

w8f9ii691#

MQTTnet Wiki中记录的示例(这不是您想要的)假设您有一个PFX(PKCS12)文件.
我尝试以编程方式创建PFX,将其添加到X509Certificate2的列表中,然后将THAT分配给MqttClientOptionsBuilderTlsParameters.Certificates.Clunky,但它可以工作。代码示例:

  1. var mqttClientOptions = new MqttClientOptionsBuilder().
  2. WithTcpServer(mybrokerhostname.com, 8883).
  3. WithClientId(goofy-client-id)
  4. );
  5. MqttClientOptionsBuilderTlsParameters tlsParams = new MqttClientOptionsBuilderTlsParameters();
  6. if (connectionData.VerifyCertificateChain)
  7. {
  8. byte[]? caCertFile = null;
  9. X509Certificate2? caCert = null;
  10. caCertFile = File.ReadAllBytes(connectionData.CaCertFilePath);
  11. caCert = new X509Certificate2(caCertFile);
  12. //Validate the server certificate using the user supplied CA certificate file.
  13. tlsParams.UseTls = true;
  14. tlsParams.CertificateValidationHandler = (certContext) =>
  15. {
  16. X509Chain chain = new X509Chain();
  17. chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
  18. chain.ChainPolicy.RevocationFlag = X509RevocationFlag.ExcludeRoot;
  19. chain.ChainPolicy.VerificationFlags = X509VerificationFlags.NoFlag;
  20. chain.ChainPolicy.VerificationTime = DateTime.Now;
  21. chain.ChainPolicy.UrlRetrievalTimeout = new TimeSpan(0, 0, 0);
  22. chain.ChainPolicy.CustomTrustStore.Add(caCert);
  23. chain.ChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust;
  24. // convert provided X509Certificate to X509Certificate2
  25. var x5092 = new X509Certificate2(certContext.Certificate);
  26. return chain.Build(x5092);
  27. };
  28. }
  29. else
  30. {
  31. //Don't bother verifying whether the server certificate is valid.
  32. tlsParams.UseTls = true;
  33. tlsParams.CertificateValidationHandler = _ => true;
  34. }
  35. List<X509Certificate2> clientCerts = new List<X509Certificate2>();
  36. X509Certificate2? clientCert = null;
  37. clientCert = X509Certificate2.CreateFromEncryptedPemFile(connectionData.ClientCertFilePath, connectionData.ClientKeyPassword, connectionData.ClientKeyFilePath);
  38. var clientCertPFX = new X509Certificate2(clientCert.Export(X509ContentType.Pkcs12));
  39. clientCerts.Add(clientCertPFX);
  40. tlsParams.Certificates = clientCerts;
  41. mqttClientOptions.WithTls(tlsParams);

字符串

展开查看全部

相关问题