How to Sign and Verify with Ed25519 in Python
A minimal Ed25519 sign-and-verify helper that generates a key pair, signs a message, and checks the signature with the cryptography library.
pip install cryptography
Python code
24 linesimport hashlib
from cryptography.hazmat.primitives.asymmetric import ed25519
from cryptography.hazmat.primitives import serialization
def sign_verify_mock(
message: bytes,
private_key: ed25519.Ed25519PrivateKey,
public_key: ed25519.Ed25519PublicKey
) -> tuple[bool, bytes]:
signature = private_key.sign(message)
try:
public_key.verify(signature, message)
valid = True
except Exception:
valid = False
return valid, signature
if __name__ == "__main__":
private_key = ed25519.Ed25519PrivateKey.generate()
public_key = private_key.public_key()
message = b"Hello, Ed25519!"
valid, signature = sign_verify_mock(message, private_key, public_key)
print(f"Signature valid: {valid}")
print(f"Signature (hex): {signature.hex()}")
Output
Signature valid: True
Signature (hex): <random-hex-string>
How it works
The ed25519.Ed25519PrivateKey.generate() creates a new private key. The sign method produces a 64-byte signature. Verification calls public_key.verify; if the signature or message has been tampered with, it raises an exception, which we catch to return False. Returning the signature lets callers store or transmit it separately. This mock pattern is useful for testing workflows before integrating with a real authentication service.
Common mistakes
- Verifying with the wrong key (must match the private key's public key)
- Passing a string instead of bytes to `sign` or `verify` (always encode with `.encode()`)
- Catching `Exception` too broadly — prefer catching `InvalidSignature` from `cryptography.exceptions`
Variations
- Use `private_key.public_key().public_bytes(...)` to export the public key for sharing.
- Use `load_pem_private_key` and `load_pem_public_key` to handle keys stored as PEM files.
Real-world use cases
- Signing and verifying software release artifacts to ensure integrity during distribution.
- Authenticating API requests where the client signs a payload with its private key.
- Verifying identity in blockchain transactions or Decentralized Identifiers (DIDs).
Sponsored
More from Auth & security at scale
- ACME LetsEncrypt Mock Challenge Server in Python medium
- AES GCM encryption and decryption in Python medium
- Build a Mock OIDC Userinfo Endpoint in Python with Flask easy
- ChaCha20-Poly1305 mock in Python medium
- ECDH key agreement in Python with cryptography medium
- Enforce TLS 1.2 Minimum in Python easy
Keep learning
Related tutorials and quizzes for this topic.