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.

Medium Python 3.9+ Aug 9, 2026 Auth & security at scale 13 views 0 copies

Requires third-party packages — install first
pip install cryptography

Python code

24 lines
Python 3.9+
import 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

stdout
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

  1. Use `private_key.public_key().public_bytes(...)` to export the public key for sharing.
  2. 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

Run locally

This sample needs third-party packages, so it cannot run in the browser IDE. Copy the code above, install the packages shown at the top, then run it in your own Python environment.

More from Auth & security at scale

Related tutorials and quizzes for this topic.