GsDChat/tests/GsDChat.Tests/CryptoTests.cs

167 lines
6.4 KiB
C#

using GsDChat.Core.Security;
using Xunit;
namespace GsDChat.Tests;
public class CryptoTests
{
[Fact]
public void HashPassword_ShouldReturnValidHashAndSalt()
{
var password = "SuperSecretPassword123!";
var (hash, salt) = PasswordHasher.HashPassword(password);
Assert.False(string.IsNullOrWhiteSpace(hash));
Assert.False(string.IsNullOrWhiteSpace(salt));
Assert.Equal(128, hash.Length); // 64 bytes hex
Assert.Equal(64, salt.Length); // 32 bytes hex
}
[Fact]
public void VerifyPassword_ShouldSucceedForCorrectPassword()
{
var password = "MyP@ssw0rd!#2026";
var (hash, salt) = PasswordHasher.HashPassword(password);
bool isValid = PasswordHasher.VerifyPassword(password, hash, salt);
Assert.True(isValid);
}
[Fact]
public void VerifyPassword_ShouldFailForIncorrectPassword()
{
var password = "CorrectPassword";
var (hash, salt) = PasswordHasher.HashPassword(password);
bool isValid = PasswordHasher.VerifyPassword("WrongPassword", hash, salt);
Assert.False(isValid);
}
[Fact]
public void HashPassword_SamePassword_ShouldGenerateDifferentSaltsAndHashes()
{
var password = "IdenticalPassword";
var (hash1, salt1) = PasswordHasher.HashPassword(password);
var (hash2, salt2) = PasswordHasher.HashPassword(password);
Assert.NotEqual(salt1, salt2);
Assert.NotEqual(hash1, hash2);
}
[Fact]
public void GenerateSecureToken_ShouldGenerateUniqueHexStrings()
{
var token1 = TokenGenerator.GenerateSecureToken(32);
var token2 = TokenGenerator.GenerateSecureToken(32);
Assert.Equal(64, token1.Length);
Assert.Equal(64, token2.Length);
Assert.NotEqual(token1, token2);
}
[Fact]
public void E2eeCrypto_KeyPairGeneration_And_SharedSecretAgreement_ShouldMatch()
{
var (pubAlice, privAlice) = E2eeCrypto.GenerateKeyPair();
var (pubBob, privBob) = E2eeCrypto.GenerateKeyPair();
byte[] sharedAlice = E2eeCrypto.DeriveSharedAesKey(privAlice, pubBob);
byte[] sharedBob = E2eeCrypto.DeriveSharedAesKey(privBob, pubAlice);
Assert.Equal(32, sharedAlice.Length);
Assert.Equal(sharedAlice, sharedBob);
}
[Fact]
public void E2eeCrypto_EncryptAndDecryptMessage_ShouldRoundTrip_AndHidePlaintext()
{
var (pubAlice, privAlice) = E2eeCrypto.GenerateKeyPair();
var (pubBob, privBob) = E2eeCrypto.GenerateKeyPair();
var (_, privMallory) = E2eeCrypto.GenerateKeyPair();
string secretText = "Confidential E2EE Direct Message between Alice and Bob!";
string encrypted = E2eeCrypto.EncryptMessage(secretText, privAlice, pubBob);
Assert.True(E2eeCrypto.IsEncryptedPayload(encrypted));
Assert.DoesNotContain("Confidential", encrypted);
// Bob can decrypt using his private key and Alice's public key
string decryptedByBob = E2eeCrypto.DecryptMessage(encrypted, privBob, pubAlice);
Assert.Equal(secretText, decryptedByBob);
// Alice can also decrypt her own sent message from history using her private key and Bob's public key
string decryptedByAlice = E2eeCrypto.DecryptMessage(encrypted, privAlice, pubBob);
Assert.Equal(secretText, decryptedByAlice);
// Mallory cannot decrypt
string decryptedByMallory = E2eeCrypto.DecryptMessage(encrypted, privMallory, pubAlice);
Assert.NotEqual(secretText, decryptedByMallory);
}
[Fact]
public void E2eeCrypto_WrapAndUnwrapPrivateKey_ShouldRestoreExactPrivateKey()
{
var (_, privKey) = E2eeCrypto.GenerateKeyPair();
string wrapped = E2eeCrypto.WrapPrivateKey(privKey, "AlicePassword123!", "Alice");
Assert.StartsWith("WRAP:v1:", wrapped);
Assert.DoesNotContain(privKey, wrapped);
string? unwrapped = E2eeCrypto.UnwrapPrivateKey(wrapped, "AlicePassword123!", "alice");
Assert.Equal(privKey, unwrapped);
string? wrongPassword = E2eeCrypto.UnwrapPrivateKey(wrapped, "WrongPassword", "Alice");
Assert.Null(wrongPassword);
}
[Fact]
public void WebPushCrypto_GenerateVapidKeys_And_SignVerifyJwt_ShouldSucceed()
{
var (publicKey, privateKey) = WebPushCrypto.GenerateVapidKeys();
Assert.False(string.IsNullOrWhiteSpace(publicKey));
Assert.False(string.IsNullOrWhiteSpace(privateKey));
var pubBytes = WebPushCrypto.Base64UrlDecode(publicKey);
var privBytes = WebPushCrypto.Base64UrlDecode(privateKey);
Assert.Equal(65, pubBytes.Length);
Assert.Equal(0x04, pubBytes[0]);
Assert.Equal(32, privBytes.Length);
string authHeader = WebPushCrypto.CreateVapidAuthorizationHeader(
"https://fcm.googleapis.com/fcm/send/example123",
"mailto:admin@gsdchat.local",
publicKey,
privateKey);
Assert.StartsWith("vapid t=", authHeader);
Assert.Contains($", k={publicKey}", authHeader);
// Extract JWT token and verify ES256 signature
int tStart = authHeader.IndexOf("t=", StringComparison.Ordinal) + 2;
int tEnd = authHeader.IndexOf(", k=", StringComparison.Ordinal);
string jwt = authHeader.Substring(tStart, tEnd - tStart);
Assert.True(WebPushCrypto.VerifyVapidJwt(jwt, publicKey));
}
[Fact]
public void WebPushCrypto_Rfc8291Aes128GcmPayloadEncryption_ShouldRoundTrip()
{
// Generate simulated browser push subscription keypair (p256dh) and 16-byte auth secret
var (subPub, subPriv) = WebPushCrypto.GenerateVapidKeys();
byte[] authSecretBytes = new byte[16];
System.Security.Cryptography.RandomNumberGenerator.Fill(authSecretBytes);
string authSecret = WebPushCrypto.Base64UrlEncode(authSecretBytes);
string jsonPayload = "{\"title\":\"GsDChat (@Alice)\",\"body\":\"Hey @Bob check #announcements!\",\"channelId\":\"ch_1\"}";
byte[] encryptedBody = WebPushCrypto.EncryptPayload(System.Text.Encoding.UTF8.GetBytes(jsonPayload), subPub, authSecret);
Assert.NotNull(encryptedBody);
// Header is 86 bytes (16 salt + 4 rs + 1 idlen + 65 pubkey) + ciphertext + 16 tag
Assert.True(encryptedBody.Length > 86 + 16);
byte[] decryptedBytes = WebPushCrypto.DecryptPayload(encryptedBody, subPub, subPriv, authSecret);
string decrypted = System.Text.Encoding.UTF8.GetString(decryptedBytes);
Assert.Equal(jsonPayload, decrypted);
}
}