Created
October 5, 2021 09:23
-
-
Save craigmccauley/c55bdfdb33365f19421ce2b4620cc922 to your computer and use it in GitHub Desktop.
C# HaveIBeenPwned
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Linq; | |
using System.Net.Http; | |
using System.Security.Cryptography; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace McCauley.Util.Services | |
{ | |
public interface IPasswordPwnedService | |
{ | |
Task<bool> IsPasswordPwned(string password); | |
} | |
public class PasswordPwnedService : IPasswordPwnedService | |
{ | |
private readonly HttpClient httpClient; | |
public PasswordPwnedService(HttpClient httpClient) | |
{ | |
this.httpClient = httpClient; | |
} | |
public async Task<bool> IsPasswordPwned(string password) | |
{ | |
var isPwned = false; | |
var hash = new SHA1Managed().ComputeHash(Encoding.UTF8.GetBytes(password)); | |
var hashString = string.Concat(hash.Select(b => b.ToString("X2"))); | |
var firstPart = hashString.Substring(0, 5); | |
var secondPart = hashString.Substring(5); | |
var response = await httpClient.GetAsync($"https://api.pwnedpasswords.com/range/{firstPart}"); | |
if (response.IsSuccessStatusCode) | |
{ | |
var responseBody = await response.Content.ReadAsStringAsync(); | |
isPwned = responseBody.Split(Environment.NewLine).Any(row => row.StartsWith(secondPart)); | |
} | |
return isPwned; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment