Skip to content

Commit 5c536bf

Browse files
committed
use built-in int.from_bytes on python3 for bytes→int conversion
1 parent 693bc32 commit 5c536bf

File tree

2 files changed

+14
-12
lines changed

2 files changed

+14
-12
lines changed

tlslite/utils/compat.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,8 @@ def remove_whitespace(text):
8080
"""Removes all whitespace from passed in string"""
8181
return re.sub(r"\s+", "", text, flags=re.UNICODE)
8282

83+
bytes_to_int = int.from_bytes
84+
8385
else:
8486
# Python 2.6 requires strings instead of bytearrays in a couple places,
8587
# so we define this function so it does the conversion if needed.
@@ -147,6 +149,16 @@ def time_stamp():
147149
"""Returns system time as a float"""
148150
return time.clock()
149151

152+
def bytes_to_int(val, byteorder):
153+
"""Convert bytes to an int."""
154+
if not val:
155+
return 0
156+
if byteorder == "big":
157+
return int(b2a_hex(val), 16)
158+
if byteorder == "little":
159+
return int(b2a_hex(val[::-1]), 16)
160+
raise ValueError("Only 'big' and 'little' endian supported")
161+
150162
try:
151163
# Fedora and Red Hat Enterprise Linux versions have small curves removed
152164
getattr(ecdsa, 'NIST192p')

tlslite/utils/cryptomath.py

Lines changed: 2 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
import binascii
1616
import sys
1717

18-
from .compat import compat26Str, compatHMAC, compatLong, b2a_hex
18+
from .compat import compat26Str, compatHMAC, compatLong, bytes_to_int
1919
from .codec import Writer
2020

2121
from . import tlshashlib as hashlib
@@ -204,18 +204,8 @@ def bytesToNumber(b, endian="big"):
204204
205205
By default assumes big-endian encoding of the number.
206206
"""
207-
# if string is empty, consider it to be representation of zero
208-
# while it may be a bit unorthodox, it is the inverse of numberToByteArray
209-
# with default parameters
210-
if not b:
211-
return 0
207+
return bytes_to_int(b, endian)
212208

213-
if endian == "big":
214-
return int(b2a_hex(b), 16)
215-
elif endian == "little":
216-
return int(b2a_hex(b[::-1]), 16)
217-
else:
218-
raise ValueError("Only 'big' and 'little' endian supported")
219209

220210
def numberToByteArray(n, howManyBytes=None, endian="big"):
221211
"""

0 commit comments

Comments
 (0)