From 6f84ad7323a7761bd91fc2f6742a9f4427757015 Mon Sep 17 00:00:00 2001 From: The MMGen Project Date: Thu, 4 Jun 2026 10:41:42 +0000 Subject: [PATCH] WifKey, PrivKey: add key length checks --- mmgen/key.py | 5 ++++- mmgen/proto/btc/params.py | 1 - 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/mmgen/key.py b/mmgen/key.py index 1bae1e76..c9da63b2 100755 --- a/mmgen/key.py +++ b/mmgen/key.py @@ -35,7 +35,8 @@ class WifKey(HiliteStr, InitErrors): return wif try: assert wif.isascii() and wif.isalnum(), 'not an ASCII alphanumeric string' - proto.decode_wif(wif) # raises exception on error + k = proto.decode_wif(wif) # raises exception on error + assert len(k.sec) == proto.privkey_len, f'incorrect private key length for proto {proto.name}! ({len(k.sec)} != {proto.privkey_len})' return str.__new__(cls, wif) except Exception as e: return cls.init_fail(e, wif) @@ -77,6 +78,7 @@ class PrivKey(bytes, InitErrors, MMGenObject): assert s is None, "'wif' and key hex args are mutually exclusive" assert wif.isascii() and wif.isalnum(), 'not an ASCII alphanumeric string' k = proto.decode_wif(wif) # raises exception on error + assert len(k.sec) == proto.privkey_len, f'incorrect private key length for proto {proto.name}! ({len(k.sec)} != {proto.privkey_len})' me = bytes.__new__(cls, k.sec) me.compressed = k.compressed me.pubkey_type = k.pubkey_type @@ -105,6 +107,7 @@ class PrivKey(bytes, InitErrors, MMGenObject): me = bytes.__new__(cls, proto.preprocess_key(s, pubkey_type)) me.wif = WifKey(proto, proto.encode_wif(me, pubkey_type, compressed=compressed)) me.compressed = compressed + assert len(me) == proto.privkey_len, f'incorrect private key length for proto {proto.name}! ({len(me)} != {proto.privkey_len})' me.pubkey_type = pubkey_type me.orig_bytes = s # save the non-preprocessed key me.proto = proto diff --git a/mmgen/proto/btc/params.py b/mmgen/proto/btc/params.py index 8168a653..3c3388e1 100755 --- a/mmgen/proto/btc/params.py +++ b/mmgen/proto/btc/params.py @@ -68,7 +68,6 @@ class mainnet(CoinProtocol.Secp256k1): # chainparams.cpp ) def encode_wif(self, privbytes, pubkey_type, *, compressed): # input is preprocessed - assert len(privbytes) == self.privkey_len, f'{len(privbytes)} bytes: incorrect private key length!' assert pubkey_type in self.wif_ver_bytes, f'{pubkey_type!r}: invalid pubkey_type' return b58chk_encode( self.wif_ver_bytes[pubkey_type]