Skip to content

Commit 24dd115

Browse files
committed
Validate curve key during DecodePubCurveKey and add test to reject non-curve keys.
1 parent 13c0c38 commit 24dd115

2 files changed

Lines changed: 16 additions & 8 deletions

File tree

NATS.NKeys.Tests/NKeysTest.cs

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -307,16 +307,10 @@ public void DecodePubCurveKey_does_not_include_crc_bytes()
307307
var raw = new byte[rawLen];
308308
Base32.FromBase32(publicKey.ToCharArray(), raw);
309309

310-
// CRC is the last 2 bytes (indices 33 and 34)
311-
var crcByte1 = raw[33];
312-
var crcByte2 = raw[34];
313-
310+
// Decoded key should be exactly raw[1..33) — the 32-byte key without prefix or CRC
314311
var decoded = KeyPair.DecodePubCurveKey(publicKey);
315-
316-
// The decoded key must not contain CRC bytes
317-
// If it were 33 bytes, the last byte would be crcByte1
318312
Assert.Equal(32, decoded.Length);
319-
Assert.NotEqual(crcByte1, decoded[31]); // would match if off-by-one bug existed
313+
Assert.Equal(raw.AsSpan().Slice(1, 32).ToArray(), decoded);
320314
}
321315

322316
[Fact]
@@ -331,6 +325,15 @@ public void DecodePubCurveKey_round_trips_with_seal_open()
331325
Assert.Equal(message, opened);
332326
}
333327

328+
[Fact]
329+
public void DecodePubCurveKey_rejects_non_curve_key()
330+
{
331+
// A valid User public key has the same decoded length but wrong prefix
332+
var kp = KeyPair.CreatePair(PrefixByte.User);
333+
var ex = Assert.Throws<NKeysException>(() => KeyPair.DecodePubCurveKey(kp.GetPublicKey()));
334+
Assert.Equal("Not a valid curve key", ex.Message);
335+
}
336+
334337
[Fact]
335338
public void DecodePubCurveKey_rejects_too_short()
336339
{

NATS.NKeys/KeyPair.cs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -320,6 +320,11 @@ internal static void DecodePubCurveKey(string key, Span<byte> pub)
320320

321321
Base32.FromBase32(keySpan, buf);
322322

323+
if (buf[0] != (byte)PrefixByte.Curve)
324+
{
325+
throw new NKeysException("Not a valid curve key");
326+
}
327+
323328
var crc = (ushort)(buf[CurveDecodeLen - 2] | buf[CurveDecodeLen - 1] << 8);
324329
if (crc != Crc16.Checksum(buf.Slice(0, CurveDecodeLen - 2)))
325330
{

0 commit comments

Comments
 (0)