los*_*eep 3 c# ssl certificate x509certificate
当我在 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");
Run Code Online (Sandbox Code Playgroud)
如果我在 Internet Explorer 中手动导入我的证书文件,上面的代码工作正常。但是,如果我从 IE 中删除我的证书并改用以下代码,则会出现身份验证异常:
sslStream.AuthenticateAsClient("Test", GetX509CertificateCollection(), SslProtocols.Default, false);
Run Code Online (Sandbox Code Playgroud)
这是“GetX509CertificateCollection”方法:
public static X509CertificateCollection GetX509CertificateCollection()
{
X509Certificate2 certificate1 = new X509Certificate2("c:\\ssl.txt");
X509CertificateCollection collection1 = new X509CertificateCollection();
collection1.Add(certificate1);
return collection1;
}
Run Code Online (Sandbox Code Playgroud)
我应该怎么做才能动态加载我的证书?
为了建立在 owlstead 的回答基础上,以下是我在验证回调中使用单个 CA 证书和自定义链来避免 Microsoft 商店的方法。
我还没有弄清楚chain2
默认情况下如何使用这个链(下面),这样就不需要回调了。也就是说,将它安装在 ssl 套接字上,连接将“正常工作”。而且我还没有弄清楚如何安装它以使其传递到回调中。也就是说,我必须为每次调用回调构建链。我认为这些是 .Net 中的架构缺陷,但我可能会遗漏一些明显的东西。
函数的名称无关紧要。下面VerifyServerCertificate
是与RemoteCertificateValidationCallback
. 您也可以将它用于ServerCertificateValidationCallback
in ServicePointManager
。
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;
}
Run Code Online (Sandbox Code Playgroud)