我想在资源文件(Resources.resx)中包含CA证书,并且一旦读取为字节流,就会提供给X509Certificate构造函数类。 CA证书采用.der格式。我已将 .der 文件添加到项目的"资源"文件夹中。如何在另一个类中访问它并将其传递给 X509Certificate 构造函数?
我遵循了此链接底部给出的 c# 代码 [http://www.embedded101.com/Blogs/PaoloPatierno/entryid/366/mqtt-over-ssl-tls-with-the-m2mqtt-library-and-the-mosquitto-broker]
更新:这是我在客户端的做法。
client = new MqttClient(ddlServerIP.Text, MqttSettings.MQTT_BROKER_DEFAULT_SSL_PORT, true, new X509Certificate(Properties.Resources.ca)
, new X509Certificate(Properties.Resources.client2), MqttSslProtocols.TLSv1_2);
String clientId= Guid.NewGuid().ToString();
byte code = client.Connect(clientId);
然而,在服务器端,我收到一个错误:
OpenSSL 错误:错误:140890C7:SSL 例程:SSL3_GET_CLIENT_CERTIFICATE:对等未返回证书
如果将证书嵌入到程序集本身中(通过右键单击该文件并在其"属性"下选择"生成操作"="嵌入的资源",确保该文件是"嵌入资源"),则可以执行以下操作:
using (Stream cs = Assembly.GetExecutingAssembly().GetManifestResourceStream("MyProj.MyCert.cer"))
{
Byte[] raw = new Byte[cs.Length];
for (Int32 i = 0; i < cs.Length; ++i)
raw[i] = (Byte)cs.ReadByte();
X509Certificate2 cert = new X509Certificate2();
cert.Import(raw);
// Do whatever you need...
}
不使用资源"嵌入"证书的另一种方法是将其添加到.fsproj
/.csproj
<ItemGroup>
<Content Include="mycert.pem">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
<CopyToPublishDirectory>Always</CopyToPublishDirectory>
</Content>
</ItemGroup>
然后:
let certPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "mycert.pem")
let clientCert = new X509Certificate2(certPath)
(F# 中的示例,但由于它是 dotnet,因此几乎没有区别)