fix(battle-node): NodeCrypto.GenerateKey masks rand source with & 0xF

This commit is contained in:
gamer147
2026-06-01 11:35:53 -04:00
parent e4fbb155e4
commit 34c4ca0237
2 changed files with 20 additions and 4 deletions

View File

@@ -42,6 +42,21 @@ public class NodeCryptoTests
Assert.Throws<ArgumentException>(() => NodeCrypto.DecryptForNode("tooshort"));
}
[Test]
public void GenerateKey_RandSourceReturnsOutOfRange_MasksToLowFourBits()
{
// Defensive: misbehaving caller returns 31 (binary 11111). Internal contract is
// "each call produces one hex digit"; without masking, 31 widens to "1f" (two
// chars) which throws off the base64 length math. After masking with & 0xF,
// 31 becomes 15 — one hex digit "f". This pair distinguishes because
// base64-of-repeated-"1f" and base64-of-repeated-"f" differ at every position.
var keyFromThirtyOne = NodeCrypto.GenerateKey(() => 31);
var keyFromFifteen = NodeCrypto.GenerateKey(() => 15);
Assert.That(keyFromThirtyOne, Is.EqualTo(keyFromFifteen),
"31 & 0xF == 15 — GenerateKey must mask out-of-range bits, not let them widen the hex digit.");
}
[Test]
public void EncryptForNode_FixedVector_ProducesStableOutput()
{