.Net SqlConnection,服务器身份验证和证书固定

时间:2012-01-01 05:20:15

标签: c# sql-server ssl sqlconnection

使用s SqlConnection时如何固定证书?从SqlConnection Connection String Parameter Keywords & Values开始,我知道我可以将Encrypted设置为true以强制(鼓励?)使用SSL / TLS。

但是,为了固定证书,我认为我们需要使用ServerCertificateValidationCallback中的ServicePointManager(以下示例代码由ArneVajhøj提供,用于HTTP / HTTPS)。我不清楚如何将PinCertificate(从ServicePointManager)连接到SqlConnection

更新:在microsoft.public.dotnet.languages.csharp上与ArneVajhøj交谈,似乎无法对连接进行所需的控制。 Vajhøj提供了Encrypting Connections to SQL Server的链接。

public static void Main(string[] args)
{
  ServicePointManager.ServerCertificateValidationCallback = PinCertificate;
  WebRequest wr = WebRequest.Create("https://www.google.com/");

  wr.GetResponse();
}

public static bool PinCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
  byte[] chash = certificate.GetCertHash();

  StringBuilder sb = new StringBuilder(chash.Length * 2);
  foreach (byte b in chash)
    sb.AppendFormat("{0:X2}", b);

  // Verify against known SHA1 thumb print of the certificate
  String hash = sb.ToString();
  if (hash != "C1956DC8A7DFB2A5A56934DA09778E3A11023358")
    return false;

  return true;
}

1 个答案:

答案 0 :(得分:0)

如下:

System.Net.ServicePointManager.ServerCertificateValidationCallback = New RemoteCertificateValidationCallback(AddressOf ValidateCertificate)

Private Function ValidateCertificate(ByVal sender As Object, ByVal certificate As X509Certificate, ByVal chain As X509Chain, ByVal sslPolicyErrors As SslPolicyErrors) As Boolean
    'Return True to force the certificate to be accepted.
    Return True
End Function