.NET-如何为套接字通信自签名SSL证书?

时间:2019-05-22 19:44:41

标签: c# .net sockets ssl ssl-certificate

我需要创建一个自签名SSL证书以用于C#中的套接字通信。理想情况下,代码将是纯.NET代码,而无需依赖任何外部库。

正在使用以下代码创建SSL证书:

public static X509Certificate2 Create(string host)
{
    // Generate an asymmetric key pair.
    var ecdsa = ECDsa.Create();

    // Request a certificate with the common name as the host using the key pair.
    // Common Name (AKA CN) represents the server name protected by the SSL certificate.
    var request = new CertificateRequest($"cn={host}", ecdsa, HashAlgorithmName.SHA512);

    var validFrom = DateTimeOffset.UtcNow;
    var validUntil = DateTimeOffset.UtcNow.AddYears(5);

    var certificate = request.CreateSelfSigned(validFrom, validUntil);
    var certificateBytes = certificate.Export(X509ContentType.Pfx);

    return new X509Certificate2(certificateBytes);
}

代码在这里被调用:

// host = "www.google.com"
var serverCertificate = SslCertificate.Create(host);

var clientSslStream = new SslStream(client.Stream, false);
await clientSslStream.AuthenticateAsServerAsync(serverCertificate, false, SslProtocols.Tls12, false);

AuthenticateAsServerAsync的调用引发了异常:

System.Security.Authentication.AuthenticationException
A call to SSPI failed, see inner exception.
System.ComponentModel.Win32Exception:
The client and server cannot communicate, because they do not possess a common algorithm

0 个答案:

没有答案