Reject signed and non-ASCII hexadecimal byte chunks

This commit is contained in:
Taksh 2026-09-12 12:21:04 +05:30
parent 53fdacca83
commit 3754d416d2
2 changed files with 9 additions and 1 deletions

View File

@ -27,7 +27,8 @@ fun String.dataFromHexString(): ByteArray? {
if (hex.isEmpty()) {
return ByteArray(0)
}
if (hex.length % 2 != 0) {
// Radix parsing accepts signs and Unicode digits; encoded bytes require ASCII hex.
if (hex.length % 2 != 0 || hex.any { it !in '0'..'9' && it !in 'a'..'f' && it !in 'A'..'F' }) {
return null
}

View File

@ -48,6 +48,13 @@ class HexStringTest {
assertNull("0xgg".dataFromHexString())
}
@Test
fun `rejects signed byte chunks and non-ascii digits`() {
for (invalid in listOf("0x-1", "0x+1", "-1", "+1", "00-1", "0X+100", "01")) {
assertNull(invalid.dataFromHexString())
}
}
@Test
fun `round-trips with hexEncodedString`() {
val original = byteArrayOf(0x00, 0x7f, 0xff.toByte())