4

我使用 SslStream 构建 Web 服务器。但是,下面的代码在 AuthenticateAsServer 时抛出异常。

static X509Certificate cert;
protected virtual Stream GetStream(TcpClient client)
{
        var ss = new SslStream(client.GetStream(), false);
        if (cert == null)
        {
            cert = X509Certificate2.CreateFromCertFile("test.cer");
        }
        ss.AuthenticateAsServer(cert, false, System.Security.Authentication.SslProtocols.Tls, true);
        return ss;
}

我已经使用 X509Certificate2 加载证书文件,为什么它仍然抛出异常(服务器模式 SSL 必须使用带有关联私钥的证书)?

证书文件是使用以下命令创建的:

makecert    
    -pe                                     Exportable private key
    -n "CN=localhost"                       Subject name
    -ss my                                  Certificate store name
    -sr LocalMachine                        Certificate store location
    -a sha1                                 Signature algorithm
    -sky signature                          Subject key type is for signature purposes
    -r                                      Make a self-signed cert
    "test.cer"                            Output filename
4

1 回答 1

6
makecert.exe -r -pe -n "CN=localhost" -sky exchange -sv server.pvk server.cer
pvk2pfx -pvk server.pvk -spc server.cer -pfx server.pfx -pi <password>

var certificate = new X509Certificate("path\server.pfx", "password");
于 2015-07-25T08:57:14.127 回答