Powershell - 在 Windows 平台上使用“System.Net.Security.CipherSuitesPolicy”类型的对象

问题描述 投票:0回答:1

我正在使用此代码

Add-Type -AssemblyName System.Net.Http
$httpClient = New-Object System.Net.Http.HttpClient
try
{
    $task = $httpClient.GetAsync('http://www.example.com')
    $task.wait()
    $res = $task.Result
    if ($res.isFaulted)
    {
        write-host $('Error: Status {0}, reason {1}.' -f [int]$res.Status, $res.Exception.Message)
    }
    return $res.Content.ReadAsStringAsync().Result
}
catch [Exception]
{
    write-host ('Error: {0}' -f $_)
} finally {
    if($null -ne $res)
    {
        $res.Dispose()
    }
}

这个效果很好。我想做的是设置特定的密码套件。

据我所知,基于安全通道的客户端/服务器信息交换的默认客户端行为是在启动连接时提供可用的最佳密码(基于注册表中启用的密码)(TLS 握手的 ClientHello 部分),但是最终服务器决定要使用的密码。

据我研究,利用“System.Net.Http.HttpClient”实例来访问所需的Web资源,应该通过在相应的构造函数中提供“System.Net.Http.SocketsHttpHandler”实例来实例化该资源。这使您可以通过“SocketsHttpHandler”类的“SslOptions”属性定义密码套件,该类又包含具有“CipherSuitesPolicy”属性的“SslClientAuthenticationOptions”类的实例。

我发现它仅适用于 Linux / MacOS,因为您无法在 Windows 平台上实例化“System.Net.Security.CipherSuitesPolicy”类型的对象。

总结一下,在Windows平台上是不是不可能做到这一点?

谢谢,

powershell encryption tls1.2
1个回答
0
投票

要在 Windows 上的 PowerShell 中为

HttpClient
设置特定的密码套件,您是正确的,
System.Net.Security.CipherSuitesPolicy
类在 Linux 和 macOS 上可以直接使用,但不能在 Windows 上直接使用。此限制是由于 Windows 和基于 Unix 的系统处理 SSL/TLS 设置的方式不同造成的。

在 Windows 上,密码套件通常在操作系统级别而不是应用程序级别进行管理。这意味着对允许的密码套件的更改通常涉及修改系统设置而不是应用程序代码。

由于在 Windows 上无法使用

HttpClient
直接在
CipherSuitesPolicy
中设置密码套件,因此您可以创建一个脚本来修改 Windows 注册表以启用特定的密码套件。此后,您现有的
HttpClient
脚本将使用配置的密码套件,因为 Windows 在系统级别应用这些设置。

这是一个用于在 Windows 上启用特定密码套件的 PowerShell 脚本:

# Define the cipher suite you want to enable
$cipherSuite = "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"

# Registry path for SSL cipher suites
$registryPath = "HKLM:\SOFTWARE\Policies\Microsoft\Cryptography\Configuration\SSL\00010002"

# Check if the registry path exists and create if it doesn't
if (-not (Test-Path $registryPath)) {
    New-Item -Path $registryPath -Force
}

# Set the desired cipher suite in the registry
Set-ItemProperty -Path $registryPath -Name "Functions" -Value $cipherSuite

# Output for confirmation
Write-Host "Cipher suite set to $cipherSuite in the registry."

此脚本将指定的密码套件设置为 Windows 系统上 SSL/TLS 连接唯一启用的密码套件。将

"TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"
替换为您要使用的密码套件。

重要提示:

  • 此脚本修改系统级设置,这会影响系统上使用 SSL/TLS 的所有应用程序。
  • 请谨慎使用此脚本并了解安全隐患。
  • 运行此脚本后,您的
    HttpClient
    连接将使用指定的密码套件(前提是服务器支持)。

要恢复更改:

您需要将“功能”值设置回其原始状态,或者删除创建的注册表项(如果最初不存在)。郑重声明,在我的个人计算机中,在进行任何更改之前,此路径当前为空。

© www.soinside.com 2019 - 2024. All rights reserved.