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>
This commit is contained in:
@@ -11,9 +11,19 @@ namespace SVSim.BattleNode.Wire;
|
||||
public static class NodeCrypto
|
||||
{
|
||||
/// <summary>
|
||||
/// Generate a fresh 32-char key. 32 random hex digits, base64-encoded, truncated to 32 chars.
|
||||
/// Port of Cryptographer.generateKeyString.
|
||||
/// Generate a fresh 32-char key for server-initiated encryption.
|
||||
/// Calls <paramref name="randHexDigit"/> 32 times expecting a value in [0,15],
|
||||
/// formats each as a single hex char, then base64-encodes the resulting 32-char ASCII
|
||||
/// string and truncates to 32 chars.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Differs from the client's <c>Cryptographer.generateKeyString</c> in input shape:
|
||||
/// the client uses <c>Random.Next(0, 65535).ToString("x")</c> per iteration (1–4 hex
|
||||
/// chars each). The output distribution is therefore different, but both produce a
|
||||
/// valid 32-char UTF-8 AES-256 key — and the client never validates the server's key
|
||||
/// since the server is decrypt-only in practice. Server-initiated encryption (e.g.
|
||||
/// for <c>synchronize</c> pushes) uses this method.
|
||||
/// </remarks>
|
||||
public static string GenerateKey(Func<int> randHexDigit)
|
||||
{
|
||||
var sb = new StringBuilder(32);
|
||||
|
||||
@@ -41,4 +41,18 @@ public class NodeCryptoTests
|
||||
{
|
||||
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));
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user