18
18
19
19
From bytes to a number, number to bytes, etc.
20
20
"""
21
+
22
+ # from __future__ import absolute_import
23
+
21
24
from struct import pack
22
- from adafruit_binascii import hexlify
25
+ import adafruit_binascii as binascii
23
26
24
27
from adafruit_rsa ._compat import byte , is_integer
25
28
from adafruit_rsa import common , machine_size
@@ -37,7 +40,7 @@ def bytes2int(raw_bytes):
37
40
38
41
"""
39
42
40
- return int (hexlify (raw_bytes ), 16 )
43
+ return int (binascii . hexlify (raw_bytes ), 16 )
41
44
42
45
43
46
def _int2bytes (number , block_size = None ):
@@ -133,14 +136,11 @@ def bytes_leading(raw_bytes, needle=b'\x00'):
133
136
def int2bytes (number , fill_size = None , chunk_size = None , overflow = False ):
134
137
"""
135
138
Convert an unsigned integer to bytes (base-256 representation)::
136
-
137
139
Does not preserve leading zeros if you don't specify a chunk size or
138
140
fill size.
139
-
140
141
.. NOTE:
141
142
You must not specify both fill_size and chunk_size. Only one
142
143
of them is allowed.
143
-
144
144
:param number:
145
145
Integer value
146
146
:param fill_size:
@@ -172,7 +172,7 @@ def int2bytes(number, fill_size=None, chunk_size=None, overflow=False):
172
172
raise ValueError ("You can either fill or pad chunks, but not both" )
173
173
174
174
# Ensure these are integers.
175
- is_integer ( number )
175
+ assert number & 1 == 0 , "Number must be an unsigned integer, not a float."
176
176
177
177
raw_bytes = b''
178
178
@@ -197,9 +197,10 @@ def int2bytes(number, fill_size=None, chunk_size=None, overflow=False):
197
197
"Need %d bytes for number, but fill size is %d" %
198
198
(length , fill_size )
199
199
)
200
- raw_bytes = b' \x00 ' + raw_bytes
200
+ raw_bytes = "% {}s" . format ( fill_size ). encode () % raw_bytes
201
201
elif chunk_size and chunk_size > 0 :
202
202
remainder = length % chunk_size
203
203
if remainder :
204
- raw_bytes = b'\x00 ' + raw_bytes
204
+ padding_size = chunk_size - remainder
205
+ raw_bytes = "% {}s" .format (length + padding_size ).encode () % raw_bytes
205
206
return raw_bytes
0 commit comments