我无法与配置为仅接受有效 SSL 证书的 PostgreSQL 数据库建立连接。我可以使用带有适当证书和密钥的 pgAdmin III 进行连接,但我无法让它与 Npgsql 一起使用。当我尝试打开与数据库的连接时,我得到System.IO.IOException: The authentication or decryption has failed
. 这是我的代码:
NpgsqlConnectionStringBuilder csb = new NpgsqlConnectionStringBuilder();
csb.Database = "database";
csb.Host = "psql-server";
csb.UserName = "dreamlax"; // must match Common Name of client certificate
csb.SSL = true;
csb.SslMode = SslMode.Require;
NpgsqlConnection conn = new NpgsqlConnection(csb.ConnectionString);
conn.ProvideClientCertificatesCallback += new ProvideClientCertificatesCallback(Database_ProvideClientCertificatesCallback);
conn.CertificateSelectionCallback += new CertificateSelectionCallback(Database_CertificateSelectionCallback);
conn.CertificateValidationCallback += new CertificateValidationCallback(Database_CertificateValidationCallback);
conn.PrivateKeySelectionCallback += new PrivateKeySelectionCallback(Database_PrivateKeySelectionCallback);
conn.Open(); //System.IO.IOException: The authentication or decryption has failed
回调定义如下:
static void Database_ProvideClientCertificates(X509CertificateCollection clienteCertis)
{
X509Certificate2 cert = new X509Certificate2("mycert.pfx", "passphrase");
clienteCertis.Add(cert);
}
static X509Certificate Database_CertificateSelectionCallback(X509CertificateCollection clientCerts, X509Certificate serverCert, string host, X509CertificateCollection serverRequestedCerts)
{
return clienteCertis[0];
}
static AsymmetricAlgorithm Database_PrivateKeySelectionCallback(X509Certificate cert, string host)
{
X509Cerficate2 thisCert = cert as X509Certificate2;
if (cert != null)
return cert.PrivateKey;
else
return null;
}
static bool MyCertificateValidationCallback(X509Certificate certificate, int[] certificateErrors)
{
// forego server validation for now
return true;
}
我设置了断点,确认每个回调都返回了有效的东西,但仍然抛出了 IOException。