gpt4 book ai didi

c# - 仅接受自签名 SSL 证书 C#

转载 作者:行者123 更新时间:2023-11-30 17:33:30 29 4
gpt4 key购买 nike

我有一个在带有自签名 SSL 证书的 Windows Server 2012 上运行的自编程 API。现在我想通过 HTTPS 与网络服务通信。

通信仅在本地网络上进行,但我仍然希望连接安全。

有没有办法只接受我的自签名证书?我找到了很多接受所有证书的解决方案,但我只希望我的被接受。

我已经考虑过将它添加到 Windows 接受的证书中,但是由于使用 Web 服务的程序是由不同 PC 上的几个用户使用的,我没有对所有这些用户的管理权限。

甚至可以按照我想要的方式建立安全连接吗?

最佳答案

是的,正如 Gusman 所建议的,您应该为 ServerCertificateValidationCallback 实现您自己的方法。您可以比较证书的指纹来验证它是否是您要信任的证书。这样的事情应该有效:

public static class CertificateValidator
{
public static string TrustedThumbprint { get; set; }

public static bool ValidateSslCertificate(
object sender,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors errors)
{
// Wrap certificate to access thumbprint.
var certificate2 = new X509Certificate2(certificate);

// Only accept certificate with trusted thumbprint.
if (certificate2.Thumbprint.Equals(
TrustedThumbprint, StringComparison.OrdinalIgnoreCase))
{
return true;
}

// In all other cases, don't trust the certificate.
return false;
}
}

在您的启动代码中,包括以下内容来连接它:

// Read your trusted thumbprint from some secure storage.
// Don't check it into source control! ;-)
CertificateValidator.TrustedThumbprint = SomeSecureConfig.Get["TrustedApiThumbprint"];

// Set the callback used to validate certificates.
ServicePointManager.ServerCertificateValidationCallback += CertificateValidator.ValidateSslCertificate;

关于c# - 仅接受自签名 SSL 证书 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43783595/

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