Skip to content

Commit 689a10d

Browse files
committed
Bytes2int transformation more efficient using binascii.hexlify
1 parent 1058ccf commit 689a10d

1 file changed

Lines changed: 7 additions & 17 deletions

File tree

rsa/transform.py

Lines changed: 7 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -4,33 +4,23 @@
44
'''
55

66
import types
7+
import binascii
78

89
from rsa import common
910

1011
def bytes2int(bytes):
11-
"""Converts a list of bytes or an 8-bit string to an integer.
12+
r"""Converts a list of bytes or an 8-bit string to an integer.
1213
1314
When using unicode strings, encode it to some encoding like UTF8 first.
1415
1516
>>> (((128 * 256) + 64) * 256) + 15
1617
8405007
17-
>>> l = [128, 64, 15]
18-
>>> bytes2int(l) #same as bytes2int('\x80@\x0f')
19-
8405007
18+
>>> bytes2int('\x80@\x0f')
19+
8405007L
2020
2121
"""
2222

23-
if not (type(bytes) is types.ListType or type(bytes) is types.StringType):
24-
raise TypeError("You must pass a string or a list")
25-
26-
# Convert byte stream to integer
27-
integer = 0
28-
for byte in bytes:
29-
integer *= 256
30-
if type(byte) is types.StringType: byte = ord(byte)
31-
integer += byte
32-
33-
return integer
23+
return long(binascii.hexlify(bytes), 16)
3424

3525
def int2bytes(number, block_size=None):
3626
r'''Converts a number to a string of bytes.
@@ -47,12 +37,12 @@ def int2bytes(number, block_size=None):
4737
>>> int2bytes(123456789)
4838
'\x07[\xcd\x15'
4939
>>> bytes2int(int2bytes(123456789))
50-
123456789
40+
123456789L
5141
5242
>>> int2bytes(123456789, 6)
5343
'\x00\x00\x07[\xcd\x15'
5444
>>> bytes2int(int2bytes(123456789, 128))
55-
123456789
45+
123456789L
5646
5747
>>> int2bytes(123456789, 3)
5848
Traceback (most recent call last):

0 commit comments

Comments
 (0)