仅接受自签名SSL证书C#
我有一个在Windows Server 2012上运行的自编程API,带有自签名SSL证书。现在我想通过HTTPS与webservice通信 通信仅在本地网络上进行,但我仍然希望连接安全 有没有办法只接受我的自签名证书?我找到了很多解决方案来接受所有证书,但我只希望我的证书被接受 我已经考虑过将其添加到windows接受的证书中,但由于使用Web服务的程序是不同PC上的多个用户的程序,因此我没有对所有这些程序的管理权限仅接受自签名SSL证书C#,c#,https,ssl-certificate,self-signed,C#,Https,Ssl Certificate,Self Signed,我有一个在Windows Server 2012上运行的自编程API,带有自签名SSL证书。现在我想通过HTTPS与webservice通信 通信仅在本地网络上进行,但我仍然希望连接安全 有没有办法只接受我的自签名证书?我找到了很多解决方案来接受所有证书,但我只希望我的证书被接受 我已经考虑过将其添加到windows接受的证书中,但由于使用Web服务的程序是不同PC上的多个用户的程序,因此我没有对所有这些程序的管理权限 甚至可以按我希望的方式建立安全连接吗?是的,正如Gusman所建议的,您应该
甚至可以按我希望的方式建立安全连接吗?是的,正如Gusman所建议的,您应该为
服务器CertificateValidationCallback实现自己的方法。您可以比较证书的指纹以验证它是否是您想要信任的证书。像这样的方法应该会奏效:
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;
是的,这是可能的,并且您已经看到了,使用与接受任何证书相同的解决方案,但在ServerCertificateValidationCallback
事件中自己验证它。好的,我认为这似乎是合乎逻辑的。我是否要检查证书的哈希和,或者检查证书的内容和方式?这可能会帮助您:为什么不将证书添加到您的证书存储中?