Last active
August 29, 2015 14:01
-
-
Save posita/8488da5bda5d75651e25 to your computer and use it in GitHub Desktop.
Alternate approach to <https://bitcoin.stackexchange.com/questions/13970/python-code-to-generate-private-ecdsa-key>.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
from random import SystemRandom | |
SYS_RAN = SystemRandom() | |
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | |
from binascii import hexlify | |
from struct import Struct | |
PACKER = Struct('>QQQQ') | |
MIN_VAL = 0x1L | |
MAX_VAL = 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140 | |
def mkprivkey(): | |
key = SYS_RAN.randint(MIN_VAL, MAX_VAL) | |
key0 = key >> 192 | |
key1 = (key >> 128) & 0xffffffffffffffff | |
key2 = (key >> 64) & 0xffffffffffffffff | |
key3 = key & 0xffffffffffffffff | |
return hexlify(PACKER.pack(key0, key1, key2, key3)) | |
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | |
HEX_CHARS = '0123456789abcdef' | |
MAX_HEX = 'fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140' | |
def create_private_key(): | |
ran_hex = '' | |
for i in range(64): # pylint: disable=unused-variable | |
ran_hex += HEX_CHARS[SYS_RAN.randint(0, 15)] | |
return ran_hex | |
# if int(ran_hex, 16) <= int(MAX_HEX, 16): | |
# return ran_hex | |
# else: | |
# return create_private_key() | |
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | |
from binascii import unhexlify | |
from time import time | |
def timefunc(a_func, a_repetitions): | |
total_s = 0 | |
for ignored in xrange(a_repetitions): # pylint: disable=unused-variable | |
s = time() | |
key = a_func() | |
e = time() | |
total_s += e - s | |
vals = PACKER.unpack(unhexlify(key)) | |
val = 0 | |
val += vals[0] << 192 | |
val += vals[1] << 128 | |
val += vals[2] << 64 | |
val += vals[3] | |
try: | |
assert val >= MIN_VAL | |
assert val <= MAX_VAL | |
except AssertionError: | |
print('assertion failed on: %s' % key) | |
return total_s | |
timefunc(mkprivkey, 1000) # warm up | |
times = 100000 | |
print('mkprivkey: %0.3f ms avg' % (timefunc(mkprivkey, times) * 1000 / times)) | |
timefunc(create_private_key, 1000) # warm up | |
times = 100000 | |
print('create_private_key: %0.3f ms avg' % (timefunc(create_private_key, times) * 1000 / times)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment