Last active
January 9, 2024 13:59
-
-
Save esersahin/b0d80d996655fc7428df012764dd772c to your computer and use it in GitHub Desktop.
Password Manager and Tests
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.Security.Cryptography; | |
using System.Text; | |
public class PasswordManager | |
{ | |
public string HashPassword(string password) | |
{ | |
using (SHA256 sha256 = SHA256.Create()) | |
{ | |
byte[] hashedBytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(password)); | |
return BitConverter.ToString(hashedBytes).Replace("-", "").ToLower(); | |
} | |
} | |
public bool VerifyPassword(string password, string hashedPassword) | |
{ | |
string hashedInput = HashPassword(password); | |
return hashedInput.Equals(hashedPassword); | |
} | |
} | |
// Password Manager Tests | |
using Xunit; | |
using NSubstitute; | |
public class PasswordManagerTests | |
{ | |
[Fact] | |
public void HashPassword_VerifyPassword_Correct() | |
{ | |
// Arrange | |
var passwordManager = new PasswordManager(); | |
var password = "MySecretPassword"; | |
// Act | |
var hashedPassword = passwordManager.HashPassword(password); | |
var result = passwordManager.VerifyPassword(password, hashedPassword); | |
// Assert | |
Assert.True(result); | |
} | |
[Fact] | |
public void VerifyPassword_IncorrectPassword_ReturnsFalse() | |
{ | |
// Arrange | |
var passwordManager = new PasswordManager(); | |
var password = "MySecretPassword"; | |
var incorrectPassword = "IncorrectPassword"; | |
// Act | |
var hashedPassword = passwordManager.HashPassword(password); | |
var result = passwordManager.VerifyPassword(incorrectPassword, hashedPassword); | |
// Assert | |
Assert.False(result); | |
} | |
[Fact] | |
public void VerifyPassword_UsingNSubstitute_Correct() | |
{ | |
// Arrange | |
var passwordManagerMock = Substitute.For<PasswordManager>(); | |
var password = "MySecretPassword"; | |
var hashedPassword = passwordManagerMock.HashPassword(password); | |
// Act | |
passwordManagerMock.VerifyPassword(password, hashedPassword).Returns(true); | |
var result = passwordManagerMock.VerifyPassword(password, hashedPassword); | |
// Assert | |
Assert.True(result); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment