Skip to content

Commit 0bf3839

Browse files
piktomato42
authored andcommitted
python2.7 and python2.6 compatability for bit-wise randrange
1 parent 5a5ed01 commit 0bf3839

File tree

1 file changed

+14
-9
lines changed

1 file changed

+14
-9
lines changed

src/ecdsa/util.py

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import os
44
import math
55
import binascii
6+
import sys
67
from hashlib import sha256
78
from six import PY3, int2byte, b, next
89
from . import der
@@ -16,12 +17,16 @@
1617
oid_ecPublicKey = (1, 2, 840, 10045, 2, 1)
1718
encoded_oid_ecPublicKey = der.encode_oid(*oid_ecPublicKey)
1819

19-
20-
def bit_length(num):
21-
# http://docs.python.org/dev/library/stdtypes.html#int.bit_length
22-
s = bin(num) # binary representation: bin(-37) --> '-0b100101'
23-
s = s.lstrip('-0b') # remove leading zeros and minus sign
24-
return len(s) # len('100101') --> 6
20+
if sys.version > '3':
21+
entropy_to_bits = lambda ent_256: ''.join(bin(x)[2:].zfill(8) for x in ent_256)
22+
else:
23+
entropy_to_bits = lambda ent_256: ''.join(bin(ord(x))[2:].zfill(8) for x in ent_256)
24+
if sys.version < '2.7': #Can't add a method to a built-in type so we are stuck with this
25+
bit_length = lambda x: len(bin(x)) - 2
26+
else:
27+
bit_length = lambda x: x.bit_length() or 1
28+
29+
2530

2631

2732
def orderlen(order):
@@ -41,11 +46,11 @@ def randrange(order, entropy=None):
4146
assert order > 1
4247
if entropy is None:
4348
entropy = os.urandom
44-
upper_2 = (order-2).bit_length() or 1
49+
upper_2 = bit_length(order-2)
4550
upper_256 = int(upper_2/8 + 1);
46-
while True: #I don't think we need a counter with bit-wise randrange
51+
while True: #I don't think this needs a counter with bit-wise randrange
4752
ent_256 = entropy(upper_256)
48-
ent_2=''.join(bin(x)[2:].zfill(8) for x in ent_256)
53+
ent_2=entropy_to_bits(ent_256)
4954
rand_num = int(ent_2[:upper_2], base=2) +1
5055
if 0 < rand_num < order: return rand_num
5156
else:continue

0 commit comments

Comments
 (0)