Skip to content

Commit b5b0da7

Browse files
committed
gh-127740: For odd-length input to bytes.fromhex(...) change the error message to ValueError: fromhex() arg must be of even length
1 parent 2041a95 commit b5b0da7

File tree

2 files changed

+19
-1
lines changed

2 files changed

+19
-1
lines changed

Lib/test/test_bytes.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -459,6 +459,11 @@ def test_fromhex(self):
459459
self.assertRaises(ValueError, self.type2test.fromhex, '\x00')
460460
self.assertRaises(ValueError, self.type2test.fromhex, '12 \x00 34')
461461

462+
# For odd number of character(s)
463+
with self.assertRaises(ValueError) as cm:
464+
self.type2test.fromhex("a")
465+
self.assertIn("fromhex() arg must be of even length", str(cm.exception))
466+
462467
for data, pos in (
463468
# invalid first hexadecimal character
464469
('12 x4 56', 3),

Objects/bytesobject.c

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2490,7 +2490,7 @@ PyObject*
24902490
_PyBytes_FromHex(PyObject *string, int use_bytearray)
24912491
{
24922492
char *buf;
2493-
Py_ssize_t hexlen, invalid_char;
2493+
Py_ssize_t hexlen, invalid_char,real_len=0;
24942494
unsigned int top, bot;
24952495
const Py_UCS1 *str, *end;
24962496
_PyBytesWriter writer;
@@ -2516,6 +2516,19 @@ _PyBytes_FromHex(PyObject *string, int use_bytearray)
25162516
}
25172517

25182518
assert(PyUnicode_KIND(string) == PyUnicode_1BYTE_KIND);
2519+
2520+
const Py_UCS1 *s = PyUnicode_1BYTE_DATA(string);
2521+
for (Py_ssize_t i = 0; i < hexlen; i++) {
2522+
if (!Py_ISSPACE(s[i])) {
2523+
real_len++;
2524+
}
2525+
}
2526+
if (real_len % 2 != 0) {
2527+
PyErr_SetString(PyExc_ValueError,
2528+
"fromhex() arg must be of even length");
2529+
_PyBytesWriter_Dealloc(&writer);
2530+
return NULL;
2531+
}
25192532
str = PyUnicode_1BYTE_DATA(string);
25202533

25212534
/* This overestimates if there are spaces */

0 commit comments

Comments
 (0)