# c# 使用SSL记录

使用openssl生成 pfx 密钥文件

C#
//1、生成.key文件,要求输入一个自定义的密码
openssl genrsa -des3 -out server.key 2048

//2、生成.crt文件,要求输入server.key的密码,和一些其他内容,-days为过期时间,可以搞长一点
openssl req -new -x509 -key server.key -out server.crt -days 365000

//3、生成pfx
openssl pkcs12 -export -out server.pfx -inkey server.key -in server.crt

//4、在目录中得到 server.key,server.crt,server.pfx

服务端使用

C#
//path,你的pfx路径,password,生成pfx时填的密码
var serverCertificate = new X509Certificate(path, password);

//假设已经从socket监听接收到一个链接
SslStream sslStream = new SslStream(new NetworkStream(socket), true);
await sslStream.AuthenticateAsServerAsync(serverCertificate, false, SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12 | SslProtocols.Tls13, false);

//接下来使用 sslStream 去接收和发送数据就可以了

客户端使用

C#
//假设,已经使用socket,链接到服务器
SslStream sslStream = new SslStream(new NetworkStream(socket), true, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
await sslStream.AuthenticateAsClientAsync(new SslClientAuthenticationOptions { EnabledSslProtocols = SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12 | SslProtocols.Tls13 });

//接下来使用 sslStream 去接收和发送数据就可以了

//这里我们不验证证书,直接信任
private bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
    return true;
}