Digital Signature Implementation in Python
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn your Security question into a ready to paste AI prompt, free →
Key Takeaways
- ✓Digital Signature runs in O(n) time and O(1) space, in Python as in every other language.
- ✓The standard library stops at symmetric integrity: hmac (with hmac.compare_digest) and hashlib.
- ✓Reviewers want the key object loaded once at module scope or in a cache, never load_pem_private_key per request, and they want the except clause narrowed to InvalidSignature rather than Exception.
- ✓The Python trap: verify() returns None. It signals success by not raising. So 'if public_key.verify(sig, msg):' is always false, and 'ok = pub.verify(...)' binds None, so a check written either way rejects every signature, valid ones included.
- ✓Every sign and verify crosses into OpenSSL through the compiled binding, so each call carries a few microseconds of boundary overhead on top of the curve work.
What Digital Signature actually is
Digital Signature in Python: what you actually reach for
Python implementation
from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import ed25519
private_key = ed25519.Ed25519PrivateKey.generate()
public_key = private_key.public_key()
message = b"transfer:acct-91:1200"
signature = private_key.sign(message) # 64 bytes, no hash argument
def verify(pub: ed25519.Ed25519PublicKey, msg: bytes, sig: bytes) -> bool:
try:
pub.verify(sig, msg) # returns None; raises on failure
except InvalidSignature:
return False
return True
assert verify(public_key, message, signature)
assert not verify(public_key, b"transfer:acct-91:9999", signature)
# WRONG: verify() is None-returning, so this branch is never taken.
# if public_key.verify(signature, message): ...
raw = public_key.public_bytes(
encoding=serialization.Encoding.Raw,
format=serialization.PublicFormat.Raw,
)
assert len(raw) == 32
Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Python-specific trap
Performance in Python, beyond the O(n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Python type or library should I use for Digital Signature?
The standard library stops at symmetric integrity: hmac (with hmac.compare_digest) and hashlib. CPython ships no asymmetric signing. The ecosystem answer is pyca/cryptography, which wraps OpenSSL: from cryptography.hazmat.primitives.asymmetric import ed25519, ec, rsa, padding, plus from cryptography.exceptions import InvalidSignature. Ed25519PrivateKey.generate() gives .sign(bytes) -> bytes and .public_key().verify(sig, msg). It won because it publishes wheels with OpenSSL bundled, so no compiler is needed on install. PyNaCl covers libsodium; pyjwt[crypto] layers JWS on top of it.
What is the most common Python mistake when implementing Digital Signature?
verify() returns None. It signals success by not raising. So 'if public_key.verify(sig, msg):' is always false, and 'ok = pub.verify(...)' binds None, so a check written either way rejects every signature, valid ones included. The accept-everything variant is a different shape: 'try: pub.verify(...)' with 'except InvalidSignature: pass' under it, followed by an unconditional 'return True'. The mirror bug is 'except Exception: return False', which also swallows ValueError from a truncated key and TypeError from passing a str, turning a deployment mistake into a silent 'bad signature' that nobody can reproduce. Catch InvalidSignature only and return True after the call falls through.
How does Digital Signature actually perform in Python?
Every sign and verify crosses into OpenSSL through the compiled binding, so each call carries a few microseconds of boundary overhead on top of the curve work. Against Ed25519 that is small; against an HMAC over 200 bytes it dominates, and batching at the Python level buys more than any algorithm swap. Key parsing is the real trap: load_pem_private_key does an ASN.1 decode plus bignum setup and costs far more than one signature for RSA and is still comparable to a whole Ed25519 signature, so hoist it out of the request path either way. bytes are immutable, so building a payload with += in a loop copies quadratically; join a list or use bytearray. Time complexity is O(n) and space is O(1).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialBefore paying for GitHub Copilot, check its student and free-tier options on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.