Files
SVSimServer/SVSim.UnitTests/BattleNode/Wire/NodeCryptoTests.cs
gamer147 a786599416 fix(battle-node): clarify NodeCrypto.GenerateKey contract + add fixed-vector regression test
Replace inaccurate GenerateKey docstring (it claimed to port Cryptographer.generateKeyString
directly but the input shape differs: server uses one hex digit per call, client uses
Random.Next(0,65535) per call). New doc is honest about the difference and explains why
it's safe. Add EncryptForNode_FixedVector_ProducesStableOutput: a pinned AES-CBC vector
that catches encoding/IV/padding regressions that would slip past the roundtrip test.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-31 21:31:22 -04:00

59 lines
2.0 KiB
C#

using NUnit.Framework;
using SVSim.BattleNode.Wire;
namespace SVSim.UnitTests.BattleNode.Wire;
[TestFixture]
public class NodeCryptoTests
{
[Test]
public void EncryptThenDecrypt_RoundTripsArbitraryString()
{
const string plaintext = "{\"uri\":\"InitNetwork\",\"viewerId\":906243102,\"try\":0,\"cat\":99}";
const string key = "Y2FmZWJhYmU3ZmY3ZmY3ZmY3ZmY3ZmY3"; // 32 chars
var encrypted = NodeCrypto.EncryptForNode(plaintext, key);
var decrypted = NodeCrypto.DecryptForNode(encrypted);
Assert.That(decrypted, Is.EqualTo(plaintext));
}
[Test]
public void GenerateKey_WithDeterministicSource_ProducesStable32CharOutput()
{
var seq = 0;
string key = NodeCrypto.GenerateKey(() => seq++ % 16);
Assert.That(key.Length, Is.EqualTo(32));
// Two calls with the same source produce the same output.
seq = 0;
Assert.That(NodeCrypto.GenerateKey(() => seq++ % 16), Is.EqualTo(key));
}
[Test]
public void EncryptForNode_NonStandardKeyLength_Throws()
{
Assert.Throws<ArgumentException>(() => NodeCrypto.EncryptForNode("x", "tooshort"));
}
[Test]
public void DecryptForNode_TooShortInput_Throws()
{
Assert.Throws<ArgumentException>(() => NodeCrypto.DecryptForNode("tooshort"));
}
[Test]
public void EncryptForNode_FixedVector_ProducesStableOutput()
{
// Pinned wire-format regression: any change to encoding/padding/IV derivation
// that drifts in both directions would still pass the roundtrip test but break
// this hardcoded vector — and break interop with the real client.
const string plaintext = "hello, node!";
const string key = "01234567890123456789012345678901";
const string expected = "012345678901234567890123456789015mEezM5MgR7UUEkmx5OzPQ==";
Assert.That(NodeCrypto.EncryptForNode(plaintext, key), Is.EqualTo(expected));
Assert.That(NodeCrypto.DecryptForNode(expected), Is.EqualTo(plaintext));
}
}