gpt4 book ai didi

c# - 如何在 SslStream.AuthenticateAsClient 方法中使用证书回调?

转载 作者:行者123 更新时间:2023-11-30 13:48:23 24 4
gpt4 key购买 nike

当我在 IE 中手动导入证书(工具/Internet 选项/内容/证书)时,我的 C#.NET SSL 连接工作正常,但是如何通过代码加载证书?这是我的代码:

TcpClient client = new TcpClient(ConfigManager.SSLSwitchIP, Convert.ToInt32(ConfigManager.SSLSwitchPort));

SslStream sslStream = new SslStream(
client.GetStream(),
false,
new RemoteCertificateValidationCallback(ValidateServerCertificate),
null
);
sslStream.AuthenticateAsClient("Test");

如果我在 Internet Explorer 中手动导入我的证书文件,上面的代码工作正常。但是,如果我从 IE 中删除我的证书并改为使用以下代码,我会收到身份验证异常:

sslStream.AuthenticateAsClient("Test", GetX509CertificateCollection(), SslProtocols.Default, false);

这是“GetX509CertificateCollection”方法:

public static X509CertificateCollection GetX509CertificateCollection()
{
X509Certificate2 certificate1 = new X509Certificate2("c:\\ssl.txt");
X509CertificateCollection collection1 = new X509CertificateCollection();
collection1.Add(certificate1);
return collection1;
}

我应该怎么做才能动态加载我的证书?

最佳答案

以 owlstead 的回答为基础,以下是我在验证回调中使用单个 CA 证书和自定义链以避免 Microsoft 商店的方法。

没有想出如何默认使用这个链(下面的chain2),这样就不需要回调了。也就是说,将它安装在 ssl 套接字上,连接就会“正常工作”。而且我没有弄清楚如何安装它以便将其传递到回调中。也就是说,我必须为回调的每次调用构建链。我认为这些是 .Net 中的架构缺陷,但我可能遗漏了一些明显的东西。

函数的名称无关紧要。下面,VerifyServerCertificateRemoteCertificateValidationCallback 是相同的回调。您还可以将它用于 ServicePointManager 中的 ServerCertificateValidationCallback

static bool VerifyServerCertificate(object sender, X509Certificate certificate,
X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
try
{
String CA_FILE = "ca-cert.der";
X509Certificate2 ca = new X509Certificate2(CA_FILE);

X509Chain chain2 = new X509Chain();
chain2.ChainPolicy.ExtraStore.Add(ca);

// Check all properties
chain2.ChainPolicy.VerificationFlags = X509VerificationFlags.NoFlag;

// This setup does not have revocation information
chain2.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;

// Build the chain
chain2.Build(new X509Certificate2(certificate));

// Are there any failures from building the chain?
if (chain2.ChainStatus.Length == 0)
return true;

// If there is a status, verify the status is NoError
bool result = chain2.ChainStatus[0].Status == X509ChainStatusFlags.NoError;
Debug.Assert(result == true);

return result;
}
catch (Exception ex)
{
Console.WriteLine(ex);
}

return false;
}

关于c# - 如何在 SslStream.AuthenticateAsClient 方法中使用证书回调?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12653911/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com