Make str2int/int2str work with bytes.
This commit is contained in:
+5
-4
@@ -180,9 +180,10 @@ def str2int(s):
|
|||||||
@param s: byte string representing a positive integer to convert
|
@param s: byte string representing a positive integer to convert
|
||||||
@return: converted integer
|
@return: converted integer
|
||||||
"""
|
"""
|
||||||
|
s = bytearray(s)
|
||||||
r = 0
|
r = 0
|
||||||
for c in s:
|
for c in s:
|
||||||
r = (r << 8) | ord(c)
|
r = (r << 8) | c
|
||||||
return r
|
return r
|
||||||
|
|
||||||
|
|
||||||
@@ -195,15 +196,15 @@ def int2str(n, length=-1):
|
|||||||
specified
|
specified
|
||||||
"""
|
"""
|
||||||
assert n >= 0
|
assert n >= 0
|
||||||
r = []
|
r = bytearray()
|
||||||
while length < 0 or len(r) < length:
|
while length < 0 or len(r) < length:
|
||||||
r.append(chr(n & 0xff))
|
r.append(n & 0xff)
|
||||||
n >>= 8
|
n >>= 8
|
||||||
if length < 0 and n == 0:
|
if length < 0 and n == 0:
|
||||||
break
|
break
|
||||||
r.reverse()
|
r.reverse()
|
||||||
assert length < 0 or len(r) == length
|
assert length < 0 or len(r) == length
|
||||||
return ''.join(r)
|
return r
|
||||||
|
|
||||||
|
|
||||||
def perform_rsa(message, exponent, modulus, mlen):
|
def perform_rsa(message, exponent, modulus, mlen):
|
||||||
|
|||||||
@@ -55,13 +55,13 @@ TEST_KEY_PRIVATE_EXPONENT = int(
|
|||||||
class TestStrIntConversion(unittest.TestCase):
|
class TestStrIntConversion(unittest.TestCase):
|
||||||
|
|
||||||
def test_str2int(self):
|
def test_str2int(self):
|
||||||
self.assertEquals(1234, str2int('\x04\xd2'))
|
self.assertEquals(1234, str2int(b'\x04\xd2'))
|
||||||
|
|
||||||
def test_int2str(self):
|
def test_int2str(self):
|
||||||
self.assertEquals('\x04\xd2', int2str(1234))
|
self.assertEquals(b'\x04\xd2', int2str(1234))
|
||||||
|
|
||||||
def test_int2str_with_length(self):
|
def test_int2str_with_length(self):
|
||||||
self.assertEquals('\x00\x00\x04\xd2', int2str(1234, 4))
|
self.assertEquals(b'\x00\x00\x04\xd2', int2str(1234, 4))
|
||||||
|
|
||||||
def test_int2str_fails_on_negative(self):
|
def test_int2str_fails_on_negative(self):
|
||||||
self.assertRaises(AssertionError, int2str, -1)
|
self.assertRaises(AssertionError, int2str, -1)
|
||||||
|
|||||||
Reference in New Issue
Block a user