Python ECDSA SECP256k1签名异常求助(基于warner/python-ecdsa库)
Hey Alexander, let's walk through fixing your signing problem with the python-ecdsa library. I've run into similar issues before, so here are the key fixes and checks to get your signature working properly:
1. Correctly Import Your Hex Private Key
Your private key is a hex string, but the library needs a SigningKey object initialized from raw bytes. You can't pass the hex string directly—here's how to convert it properly:
import ecdsa import hashlib # Your hex private key priv_hex = 'ffbd2d76fde8d62642379e507f4ab69883e094708410392d8470246146195e56' # Convert hex string to bytes priv_bytes = bytes.fromhex(priv_hex) # Initialize the SigningKey (assuming SECP256k1 curve—adjust if you used a different one) private_key = ecdsa.SigningKey.from_string(priv_bytes, curve=ecdsa.SECP256k1)
2. Encode Your Message to Bytes
The sign() method requires the message to be in bytes, not a plain string. Your 'aaa' message needs to be encoded first:
message = 'aaa'.encode('utf-8') # Convert string to UTF-8 bytes
3. Replace Deprecated encode("hex") with .hex()
In Python 3, the encode("hex") method is no longer supported. Use the .hex() method to get the hex string representation of your signature:
# Generate the signature signature = private_key.sign(message, hashfunc=hashlib.sha256) # Convert signature bytes to hex string signHex = signature.hex()
4. Verify the Signature to Confirm It Works
To make sure everything is working, let's verify the signature with your public key. First, parse the public key correctly (note we skip the 04 prefix for uncompressed keys):
# Your full hex public key (including 04 prefix) pub_hex = '04615a523e41d5984d5afc18e5adddddfa0ab8ac63b49933ff1b07fae90604fa6cdd6572996117b3ffce6e1258668c88fc2aad3c45eab31ef8a57b5176c91b272a' pub_bytes = bytes.fromhex(pub_hex) # Initialize VerifyingKey—skip the first byte (04) which marks uncompressed format public_key = ecdsa.VerifyingKey.from_string(pub_bytes[1:], curve=ecdsa.SECP256k1) # Check if the signature is valid try: public_key.verify(signature, message, hashfunc=hashlib.sha256) print("✅ Signature is valid!") except ecdsa.BadSignatureError: print("❌ Invalid signature—double-check your keys or curve!")
Quick Troubleshooting Checks
- Curve Mismatch: If you get a key length error, ensure you're using the same curve for both key generation and signing/verification (SECP256k1 is common, but NIST256p is another default).
- Key Truncation: Double-check that your private key is exactly 64 hex characters (32 bytes) and public key is 130 hex characters (65 bytes including the 04 prefix)—truncated keys will break signing.
内容的提问来源于stack exchange,提问作者Alexander

