2017-08-11 7 views
2

Troy Hunt's have i been pwned serviceで提供されているPwned Passwordsのリストを使用したいと考えています。このサービスについては、ブログのIntroducing 306 Million Freely Downloadable Pwned Passwordsに掲載されています。 APIは、HTTP Not Found 404のステータスコードを使用して、リストにパスワードが見つからない場合はそれを示し、妥協リストに見つかったことを示す場合は200を示します。これにより、Invoke-WebRequest PowerShell Cmdletを介して消費するのが難しくなり、404のWebExceptionがスローされます。パスワードをPowerShellのパスワードで確認する方法

私はこの質問に答えます。

+0

グレート質問と回答を以下のようにあなたは、この目的球をテストすることができますが、なぜ特にあなただけの例外をキャッチしないようにしたいのですか? –

+0

.NET APIについての好奇心は本当にありますが、2つの結果をテストするときにも、そのうちの1つは「例外的」であると感じられません。@MarkWragg –

答えて

4

新しいバージョンHttpClientでは、下のレベルでHttp要求を行い、404の例外を処理せずにHttpStatusCodeをチェックすることができます。

function Test-CompromisedPassword { 
    param([Parameter(Mandatory=$True)][string]$password) 

    # Force assembly to be loaded 
    Add-Type -AssemblyName 'System.Net.Http'  
    # By default PowerShell would use TLS 1.0 which is not supported by the API 
    [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 

    $baseUrl = "https://haveibeenpwned.com/api/v2/pwnedpassword/{0}?originalPasswordIsAHash={1}" 
    $url = $baseUrl -f $password,'false' 

    $httpClient = New-Object System.Net.Http.HttpClient 
    # User-Agent header must be set to call the API 
    $httpClient.DefaultRequestHeaders.Add("User-Agent", "PowerShell script $($MyInvocation.MyCommand.Name)") 

    # HttpClient is only Async so use .Result to force the synchronous call 
    $response = $httpClient.GetAsync($url).Result 

    Write-Verbose "$password $([int]$response.StatusCode) $($response.StatusCode)" 

    switch ([int]$response.StatusCode) { 
     200 { $passwordFound = $true; break; } 
     404 { $passwordFound = $false; break; } 
     429 { throw "Rate limit exceeded" } 
     default { throw "Not expected" + $response.StatusCode } 
    } 

    if ($response) { $response.Dispose() } 
    if ($httpClient) { $httpClient.Dispose() } 

    return $passwordFound 
} 

Test-CompromisedPassword 'password' # Returns true to indicate password found 
Start-Sleep -Milliseconds 1500 # Wait for the Rate limit time to expire 
Test-CompromisedPassword ([Guid]::NewGuid()) # Returns false to indicate password not found 
関連する問題