Skip to content

Commit

Permalink
Merge pull request #527 from tlsfuzzer/correct-int-to-bytes
Browse files Browse the repository at this point in the history
make int_to_bytes and numberToByteArray encode 0 as b'\x00'
  • Loading branch information
tomato42 authored Aug 29, 2024
2 parents 04c1e80 + d586c42 commit 77ef321
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 3 deletions.
5 changes: 4 additions & 1 deletion tlslite/messages.py
Original file line number Diff line number Diff line change
Expand Up @@ -1738,7 +1738,10 @@ def parse(self, parser):
else:
raise AssertionError()
elif self.cipherSuite in CipherSuite.dhAllSuites:
self.dh_Yc = bytesToNumber(parser.getVarBytes(2))
val = parser.getVarBytes(2)
if len(val) < 1:
raise DecodeError("DH key share too short")
self.dh_Yc = bytesToNumber(val)
elif self.cipherSuite in CipherSuite.ecdhAllSuites:
self.ecdh_Yc = parser.getVarBytes(1)
else:
Expand Down
10 changes: 8 additions & 2 deletions tlslite/utils/compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,10 @@ def bit_length(val):
def int_to_bytes(val, length=None, byteorder="big"):
"""Return number converted to bytes"""
if length is None:
length = byte_length(val)
if val:
length = byte_length(val)
else:
length = 1
# for gmpy we need to convert back to native int
if type(val) != int:
val = int(val)
Expand Down Expand Up @@ -206,7 +209,10 @@ def bytes_to_int(val, byteorder):
def int_to_bytes(val, length=None, byteorder="big"):
"""Return number converted to bytes"""
if length is None:
length = byte_length(val)
if val:
length = byte_length(val)
else:
length = 1
if byteorder == "big":
return bytearray((val >> i) & 0xff
for i in reversed(range(0, length*8, 8)))
Expand Down
6 changes: 6 additions & 0 deletions unit_tests/test_tlslite_utils_cryptomath.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,12 @@ def test_numberToByteArray(self):
self.assertEqual(numberToByteArray(0x00000000000001),
bytearray(b'\x01'))

def test_numberToByteArray_zero_bigendian(self):
self.assertEqual(numberToByteArray(0, endian="big"), bytearray(b'\x00'))

def test_numberToByteArray_zero_littleendian(self):
self.assertEqual(numberToByteArray(0, endian="little"), bytearray(b'\x00'))

def test_numberToByteArray_with_MSB_number(self):
self.assertEqual(numberToByteArray(0xff),
bytearray(b'\xff'))
Expand Down

0 comments on commit 77ef321

Please sign in to comment.