Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions btcpy/structs/crypto.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
# propagated, or distributed except according to the terms contained in the
# LICENSE.md file.

import secrets
from binascii import unhexlify
from ..lib.base58 import b58decode_check, b58encode_check
from hashlib import sha256
Expand Down Expand Up @@ -61,6 +62,13 @@ def from_wif(wif, strict=None):
def unhexlify(hexa):
return PrivateKey(bytearray(unhexlify(hexa)))

@staticmethod
def generate():
"""
Generate a random text string, in hexadecimal with 32 random bytes.
"""
return PrivateKey(bytearray(secrets.token_hex(nbytes=32), encoding='ascii'))

def __init__(self, priv, public_compressed=True):
self.key = priv
self.public_compressed = public_compressed
Expand Down
6 changes: 6 additions & 0 deletions tests/unit.py
Original file line number Diff line number Diff line change
Expand Up @@ -418,6 +418,12 @@ def test_to_wif(self):
priv.public_compressed = False
self.assertEqual(priv.to_wif(w['mainnet']), w['wif'])

def test_private_key_generation(self):
with patch('secrets.token_hex', return_value='1697da9ed39e670abb6981dcfe9ea96db2f06e7d6d18db2474ffb2ffadd1e3bb'):
priv = PrivateKey.generate()
self.assertEqual(len(priv.key), 64)
self.assertEqual(priv.key, bytearray(b'1697da9ed39e670abb6981dcfe9ea96db2f06e7d6d18db2474ffb2ffadd1e3bb'))


class TestPubkey(unittest.TestCase):

Expand Down