Files
RobotApp/RobotApp/Services/MQTTClientCertificatesProvider.cs
Đăng Nguyễn b006c5b197 update console
2025-12-22 19:43:04 +07:00

38 lines
1.6 KiB
C#

using MQTTnet;
using MQTTnet.Certificates;
using System.Security.Cryptography.X509Certificates;
namespace RobotApp.Services;
public class MQTTClientCertificatesProvider(string? CerFile, string? KeyFile) : IMqttClientCertificatesProvider
{
private readonly string certificatesPath = "MqttCertificates";
private readonly string cerFilePath = "cer";
private readonly string keyFilePath = "key";
public X509CertificateCollection? GetCertificates()
{
if (!string.IsNullOrEmpty(CerFile) && !string.IsNullOrEmpty(KeyFile))
{
if (Directory.Exists(certificatesPath))
{
var certFolder = Path.Combine(certificatesPath, cerFilePath);
var keyFolder = Path.Combine(certificatesPath, keyFilePath);
if (Directory.Exists(certFolder) && Directory.Exists(keyFolder))
{
var certLocal = Path.Combine(certFolder, CerFile);
var keyLocal = Path.Combine(keyFolder, KeyFile);
if (File.Exists(certLocal) && File.Exists(keyLocal))
{
var cert = X509Certificate2.CreateFromPem(File.ReadAllText(certLocal), File.ReadAllText(keyLocal));
var pfxBytes = cert.Export(X509ContentType.Pfx);
var pfxCert = X509CertificateLoader.LoadPkcs12(pfxBytes, "", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);
return [pfxCert];
}
}
}
}
return null;
}
}