确定协商的TLS版本
.NET Framework 4.7应用程序默认使用TLS 1.2。但是,确定安全通信期间协商的特定TLS版本至关重要。以下是实现此目的的方法:
方法一:使用反射
此技术涉及使用反射来访问GetRequestStream()
或GetResponseStream()
返回的流的内部TlsStream
属性。TlsStream
类公开SslState
属性,该属性提供对SslProtocol
属性的访问。
<code class="language-csharp">using System.IO.Compression; using System.Net; using System.Reflection; using System.Security.Authentication; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(decodedUri); using (Stream requestStream = request.GetRequestStream()) { SslProtocols sslProtocol = ExtractSslProtocol(requestStream); // 检查SSL版本,如有必要采取适当的措施 } private SslProtocols ExtractSslProtocol(Stream stream) { BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.NonPublic; Stream metaStream = stream; // 处理GZip或Deflate流 if (stream is GZipStream) metaStream = (stream as GZipStream).BaseStream; else if (stream is DeflateStream) metaStream = (stream as DeflateStream).BaseStream; var tlsStream = metaStream.GetType().GetProperty("Connection", bindingFlags).GetValue(metaStream); if (!(bool)tlsStream.GetType().GetProperty("UsingSecureStream", bindingFlags).GetValue(tlsStream)) return SslProtocols.None; var tlsState = tlsStream.GetType().GetField("m_Worker", bindingFlags).GetValue(tlsStream); return (SslProtocols)tlsState.GetType().GetProperty("SslProtocol", bindingFlags).GetValue(tlsState); }</code>
方法二:使用TcpClient
或者,您可以使用TcpClient
类建立TCP连接。TcpClient
还提供对SslStream
的访问,允许您检查协商的TLS版本。如果您需要在启动HTTP请求之前确定TLS版本,此方法很有用。
<code class="language-csharp">TlsInfo tlsInfo = null; IPHostEntry dnsHost = await Dns.GetHostEntryAsync(HostURI.Host); using (TcpClient client = new TcpClient(dnsHost.HostName, 443)) { using (SslStream sslStream = new SslStream(client.GetStream(), false, TlsValidationCallback, null)) { sslstream.AuthenticateAsClient(dnsHost.HostName, null, (SslProtocols)ServicePointManager.SecurityProtocol, false); tlsInfo = new TlsInfo(sslStream); } } public class TlsInfo { public TlsInfo(SslStream secStream) { this.ProtocolVersion = secStream.SslProtocol; } public SslProtocols ProtocolVersion { get; set; } }</code>
这两种方法都提供了一种在安全HTTP通信期间确定协商的TLS版本的方法,使您可以根据安全要求做出明智的决策。
以上是如何确定 .NET Framework 中协商的 TLS 版本?的详细内容。更多信息请关注PHP中文网其他相关文章!