ModernUO/Projects/UOContent.Tests/Tests/Accounting/Security/PasswordProtectionTest.cs
Kamron Batman 0ce2a62a76
fix: Use vectorized search for username-password validation. (#2152)
### Summary

Optimizes account validation:

```cs
| Method              | Mean       | Error     | StdDev    |
|-------------------- |-----------:|----------:|----------:|
| ForLoopUsernameSafe | 158.536 ns | 1.6247 ns | 1.5198 ns |
| SVUsernameSafe      |   2.859 ns | 0.0581 ns | 0.0796 ns |
```
2025-04-11 22:40:06 -07:00

77 lines
2.8 KiB
C#

using System;
using Server.Accounting;
using Server.Accounting.Security;
using Xunit;
namespace Server.Tests.Accounting.Security;
public class PasswordProtectionTest
{
private const string plainPassword = "hello-good-sir";
[Theory]
[InlineData(typeof(Argon2PasswordProtection), null)]
[InlineData(typeof(PBKDF2PasswordProtection), null)]
[InlineData(typeof(HashAlgorithmPasswordProtection), "MD5")]
[InlineData(typeof(HashAlgorithmPasswordProtection), "SHA1")]
[InlineData(typeof(HashAlgorithmPasswordProtection), "SHA2")]
public void TestValidates(Type protectionType, string algorithmType)
{
IPasswordProtection passwordProtection;
if (protectionType == typeof(HashAlgorithmPasswordProtection))
{
passwordProtection = algorithmType switch
{
"SHA1" => HashAlgorithmPasswordProtection.SHA1Instance,
"SHA2" => HashAlgorithmPasswordProtection.SHA2Instance,
_ => HashAlgorithmPasswordProtection.MD5Instance,
};
}
else
{
passwordProtection = Activator.CreateInstance(protectionType) as IPasswordProtection;
}
if (passwordProtection == null)
{
Assert.Fail($"{protectionType.Name} is not an IPasswordProtection.");
}
var encryptedPassword = passwordProtection.EncryptPassword(plainPassword);
Assert.True(passwordProtection.ValidatePassword(encryptedPassword, plainPassword));
}
[Theory]
[InlineData(typeof(Argon2PasswordProtection), null)]
[InlineData(typeof(PBKDF2PasswordProtection), null)]
[InlineData(typeof(HashAlgorithmPasswordProtection), "MD5")]
[InlineData(typeof(HashAlgorithmPasswordProtection), "SHA1")]
[InlineData(typeof(HashAlgorithmPasswordProtection), "SHA2")]
public void TestPasswordDoesNotValidate(Type protectionType, string algorithmType)
{
IPasswordProtection passwordProtection;
if (protectionType == typeof(HashAlgorithmPasswordProtection))
{
passwordProtection = algorithmType switch
{
"SHA1" => HashAlgorithmPasswordProtection.SHA1Instance,
"SHA2" => HashAlgorithmPasswordProtection.SHA2Instance,
_ => HashAlgorithmPasswordProtection.MD5Instance,
};
}
else
{
passwordProtection = Activator.CreateInstance(protectionType) as IPasswordProtection;
}
if (passwordProtection == null)
{
Assert.Fail($"{protectionType.Name} is not an IPasswordProtection.");
}
var encryptedPassword = passwordProtection.EncryptPassword(plainPassword);
Assert.False(passwordProtection.ValidatePassword(encryptedPassword, "Not the same password"));
}
}