我需要创建一个自签名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