Skip to content

Digital Signature — Python source

Sign messages with Ed25519 or ECDSA and verify signatures. Prove authorship without revealing your private key.

This is the Python implementation — the same logic the interactive tool runs, in a shareable, citable form.

"""digital-signature — Ed25519 / ECDSA P-256 message signing and verification.

Language: Python 3.8+ (standard library only).
CosmoDev polyglot showcase port of the `digital-signature` tool, ported from
src/lib/digital-signature.ts (the canonical TypeScript implementation).

The TS lib delegates everything to Web Crypto; Python's stdlib has hash
primitives but no asymmetric crypto, so this port implements both algorithms
from scratch: Ed25519 per RFC 8032 and ECDSA P-256 with the RFC 6979
deterministic nonce (Web Crypto uses a random nonce, so ECDSA signatures
differ per call there — both verify against the same keys regardless).

display source — part of CosmoDev's polyglot tool pages.
"""

from __future__ import annotations

import hashlib
import hmac
import secrets

HEX_RE = __import__("re").compile(r"(?:[0-9a-fA-F]{2})+\Z")

# ---------------------------------------------------------------------------
# Ed25519 (RFC 8032), twisted Edwards curve -x^2 + y^2 = 1 + d x^2 y^2 mod p.
# ---------------------------------------------------------------------------

_ED_P = 2**255 - 19
_ED_L = 2**252 + 27742317777372353535851937790883648493
_ED_D = -121665 * pow(121666, _ED_P - 2, _ED_P) % _ED_P
_ED_I = pow(2, (_ED_P - 1) // 4, _ED_P)  # sqrt(-1) mod p
# Fixed DER prefixes: Ed25519 SPKI / PKCS8 wrap a 32-byte point / seed.
_ED25519_SPKI_PREFIX = bytes.fromhex("302a300506032b6570032100")
_ED25519_PKCS8_PREFIX = bytes.fromhex("302e020100300506032b657004220420")


def _ed_recover_x(y: int) -> int:
    """Solve x^2 = (y^2 - 1) / (d y^2 + 1); a valid sqrt puts the point on-curve."""
    xx = (y * y - 1) * pow(_ED_D * y * y + 1, _ED_P - 2, _ED_P) % _ED_P
    x = pow(xx, (_ED_P + 3) // 8, _ED_P)
    if (x * x - xx) % _ED_P:
        x = x * _ED_I % _ED_P
    if (x * x - xx) % _ED_P:
        raise ValueError("point is not on the curve")
    return _ED_P - x if x & 1 else x


_ED_BY = 4 * pow(5, _ED_P - 2, _ED_P) % _ED_P  # y of the RFC 8032 base point
_ED_BX = _ed_recover_x(_ED_BY)
_ED_B = (_ED_BX, _ED_BY, 1, _ED_BX * _ED_BY % _ED_P)  # base point, extended coords
_ED_IDENTITY = (0, 1, 1, 0)


def _ed_add(p1, p2):
    """Unified addition in extended coordinates (X:Y:Z:T with xy == T/Z)."""
    x1, y1, z1, t1 = p1
    x2, y2, z2, t2 = p2
    a = (y1 - x1) * (y2 - x2) % _ED_P
    b = (y1 + x1) * (y2 + x2) % _ED_P
    c = 2 * _ED_D * t1 * t2 % _ED_P
    d = 2 * z1 * z2 % _ED_P
    e, f, g, h = b - a, d - c, d + c, b + a
    return (e * f % _ED_P, g * h % _ED_P, f * g % _ED_P, e * h % _ED_P)


def _ed_mul(point, scalar: int):
    result = _ED_IDENTITY
    while scalar:
        if scalar & 1:
            result = _ed_add(result, point)
        point = _ed_add(point, point)
        scalar >>= 1
    return result


def _ed_compress(point) -> bytes:
    x, y, z, _ = point
    zi = pow(z, _ED_P - 2, _ED_P)
    x, y = x * zi % _ED_P, y * zi % _ED_P
    return (y | ((x & 1) << 255)).to_bytes(32, "little")


def _ed_decompress(data: bytes):
    y = int.from_bytes(data, "little")
    sign, y = y >> 255, y & ((1 << 255) - 1)
    x = _ed_recover_x(y)
    if (x & 1) != sign:
        x = _ED_P - x
    return (x, y, 1, x * y % _ED_P)


def _ed_scalar_from_seed(seed: bytes) -> int:
    """Clamp the left half of SHA-512(seed) into the RFC 8032 secret scalar."""
    a = int.from_bytes(hashlib.sha512(seed).digest()[:32], "little")
    return (a & ((1 << 254) - 8)) | (1 << 254)


def _ed_sign(seed: bytes, message: bytes) -> bytes:
    h = hashlib.sha512(seed).digest()
    a = _ed_scalar_from_seed(seed)
    public = _ed_compress(_ed_mul(_ED_B, a))
    r = int.from_bytes(hashlib.sha512(h[32:] + message).digest(), "little") % _ED_L
    r_enc = _ed_compress(_ed_mul(_ED_B, r))
    k = int.from_bytes(hashlib.sha512(r_enc + public + message).digest(), "little") % _ED_L
    return r_enc + ((r + k * a) % _ED_L).to_bytes(32, "little")


def _ed_verify(message: bytes, signature: bytes, public: bytes) -> bool:
    if len(signature) != 64:
        return False
    s = int.from_bytes(signature[32:], "little")
    if s >= _ED_L:
        return False
    try:
        r_point = _ed_decompress(signature[:32])
    except ValueError:
        return False
    a_point = _ed_decompress(public)
    k = int.from_bytes(
        hashlib.sha512(signature[:32] + public + message).digest(), "little") % _ED_L
    # RFC 8032 check (cofactorless, matching WebCrypto/OpenSSL): [S]B == R + [k]A.
    lhs = _ed_compress(_ed_mul(_ED_B, s))
    rhs = _ed_compress(_ed_add(r_point, _ed_mul(a_point, k)))
    return lhs == rhs


# ---------------------------------------------------------------------------
# ECDSA P-256 (SECP256R1), short Weierstrass y^2 = x^3 - 3x + b mod p.
# ---------------------------------------------------------------------------

_P256_P = 0xFFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF
_P256_N = 0xFFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551
_P256_B = 0x5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B
_P256_G = (0x6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296,
           0x4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5)


def _ec_add(p1, p2):
    """Affine point addition; None is the point at infinity."""
    if p1 is None:
        return p2
    if p2 is None:
        return p1
    x1, y1 = p1
    x2, y2 = p2
    if x1 == x2 and (y1 + y2) % _P256_P == 0:
        return None
    if p1 == p2:  # doubling; the curve has no 2-torsion, so 2y != 0 here
        lam = (3 * x1 * x1 - 3) * pow(2 * y1, _P256_P - 2, _P256_P) % _P256_P
    else:
        lam = (y2 - y1) * pow(x2 - x1, _P256_P - 2, _P256_P) % _P256_P
    x3 = (lam * lam - x1 - x2) % _P256_P
    return (x3, (lam * (x1 - x3) - y1) % _P256_P)


def _ec_mul(point, scalar: int):
    result = None
    while scalar:
        if scalar & 1:
            result = _ec_add(result, point)
        point = _ec_add(point, point)
        scalar >>= 1
    return result


def _rfc6979_candidates(priv: int, z: int):
    """RFC 6979 deterministic nonce stream (HMAC-SHA256) — reproducible sigs."""
    v, k = b"\x01" * 32, b"\x00" * 32
    x = priv.to_bytes(32, "big")
    h1 = (z % _P256_N).to_bytes(32, "big")  # bits2octets
    k = hmac.new(k, v + b"\x00" + x + h1, hashlib.sha256).digest()
    v = hmac.new(k, v, hashlib.sha256).digest()
    k = hmac.new(k, v + b"\x01" + x + h1, hashlib.sha256).digest()
    v = hmac.new(k, v, hashlib.sha256).digest()
    while True:
        v = hmac.new(k, v, hashlib.sha256).digest()
        yield int.from_bytes(v, "big")
        k = hmac.new(k, v + b"\x00", hashlib.sha256).digest()
        v = hmac.new(k, v, hashlib.sha256).digest()


def _ecdsa_sign(priv: int, message: bytes) -> bytes:
    z = int.from_bytes(hashlib.sha256(message).digest(), "big")
    for k in _rfc6979_candidates(priv, z):
        if not 1 <= k < _P256_N:
            continue
        r = _ec_mul(_P256_G, k)[0] % _P256_N
        s = pow(k, -1, _P256_N) * (z + r * priv) % _P256_N
        if r and s:
            return r.to_bytes(32, "big") + s.to_bytes(32, "big")  # IEEE P1363 r||s
    raise AssertionError("unreachable")


def _ecdsa_verify(message: bytes, signature: bytes, q) -> bool:
    if len(signature) != 64:
        return False
    r = int.from_bytes(signature[:32], "big")
    s = int.from_bytes(signature[32:], "big")
    if not (1 <= r < _P256_N and 1 <= s < _P256_N):
        return False
    z = int.from_bytes(hashlib.sha256(message).digest(), "big")
    w = pow(s, -1, _P256_N)
    point = _ec_add(_ec_mul(_P256_G, z * w % _P256_N), _ec_mul(q, r * w % _P256_N))
    return point is not None and point[0] % _P256_N == r


# ---------------------------------------------------------------------------
# Minimal DER (ASN.1) helpers for the SPKI / PKCS8 key envelope.
# ---------------------------------------------------------------------------

_OID_EC_PUB = bytes.fromhex("06072a8648ce3d0201")  # 1.2.840.10045.2.1 ecPublicKey
_OID_P256 = bytes.fromhex("06082a8648ce3d030107")  # 1.2.840.10045.3.1.7 prime256v1


def _der(tag: int, content: bytes) -> bytes:
    if len(content) < 0x80:
        length = bytes([len(content)])
    else:
        body = len(content).to_bytes((len(content).bit_length() + 7) // 8, "big")
        length = bytes([0x80 | len(body)]) + body
    return bytes([tag]) + length + content


def _der_int(value: int) -> bytes:
    body = value.to_bytes(max((value.bit_length() + 7) // 8, 1), "big")
    return _der(0x02, b"\x00" + body if body[0] & 0x80 else body)


def _der_children(data: bytes):
    """Walk one DER level, returning [(tag, content), ...]."""
    out, i = [], 0
    while i < len(data):
        tag = data[i]
        i += 1
        length = data[i]
        i += 1
        if length & 0x80:
            n = length & 0x7F
            length = int.from_bytes(data[i:i + n], "big")
            i += n
        out.append((tag, data[i:i + length]))
        i += length
    return out


def _ecdsa_point_der(point) -> bytes:
    """Uncompressed SEC1 point 04 || X || Y (what Web Crypto exports)."""
    return b"\x04" + point[0].to_bytes(32, "big") + point[1].to_bytes(32, "big")


def _ecdsa_keys(d: int):
    """Build (SPKI, PKCS8) DER for the private scalar d per RFC 5915 / 5958."""
    point = _ecdsa_point_der(_ec_mul(_P256_G, d))
    alg = _der(0x30, _OID_EC_PUB + _OID_P256)
    sec1 = _der(0x30, _der_int(1) + _der(0x04, d.to_bytes(32, "big"))
                + _der(0xA1, _der(0x03, b"\x00" + point)))
    return _der(0x30, alg + _der(0x03, b"\x00" + point)), \
        _der(0x30, _der_int(0) + alg + _der(0x04, sec1))


def _ecdsa_public_point(spki: bytes):
    """Parse the SPKI envelope down to the (x, y) curve point."""
    try:
        (seq,) = _der_children(spki)
        alg, bits = _der_children(seq[1])
        point = bits[1][1:]  # strip the BIT STRING "unused bits" octet
        if alg[0] != 0x30 or bits[0] != 0x03 or len(point) != 65 or point[0] != 0x04:
            raise ValueError
    except (ValueError, IndexError):
        raise ValueError("Invalid public key for ECDSA P-256 (expected hex SPKI).")
    x = int.from_bytes(point[1:33], "big")
    y = int.from_bytes(point[33:], "big")
    if (y * y - (x * x * x - 3 * x + _P256_B)) % _P256_P:
        raise ValueError("Invalid public key for ECDSA P-256 (expected hex SPKI).")
    return (x, y)


def _ecdsa_private_scalar(pkcs8: bytes) -> int:
    """Parse the PKCS8 envelope (RFC 5958 wrapping an RFC 5915 SEC1 key)."""
    try:
        (seq,) = _der_children(pkcs8)
        version, _, inner = _der_children(seq[1])
        (sec1,) = _der_children(inner[1])
        fields = _der_children(sec1[1])
        if version[1] != b"\x00" or inner[0] != 0x04 or fields[1][0] != 0x04:
            raise ValueError
    except (ValueError, IndexError):
        raise ValueError("Invalid private key for ECDSA P-256 (expected hex PKCS8).")
    return int.from_bytes(fields[1][1], "big")


# ---------------------------------------------------------------------------
# Public API — mirrors generateKeyPair / signMessage / verifySignature in the
# TS lib (function names snake_cased, KeyPair fields public_key / private_key).
# ---------------------------------------------------------------------------


def _assert_algorithm(algorithm: str) -> None:
    if algorithm not in ("ed25519", "ecdsa-p256"):
        raise ValueError('Unknown algorithm. Use "ed25519" or "ecdsa-p256".')


def _label(algorithm: str) -> str:
    return "Ed25519" if algorithm == "ed25519" else "ECDSA P-256"


def hex_to_bytes(hex_str: str, what: str) -> bytes:
    if not hex_str or not HEX_RE.match(hex_str):
        raise ValueError(
            f"{what} must be a non-empty hex string (pairs of 0-9 / a-f digits).")
    return bytes.fromhex(hex_str)


def generate_key_pair(algorithm: str) -> dict:
    """Generate a fresh signing key pair, exported as hex SPKI / PKCS8 keys."""
    _assert_algorithm(algorithm)
    if algorithm == "ed25519":
        seed = secrets.token_bytes(32)
        public = _ed_compress(_ed_mul(_ED_B, _ed_scalar_from_seed(seed)))
        return {
            "public_key": (_ED25519_SPKI_PREFIX + public).hex(),
            "private_key": (_ED25519_PKCS8_PREFIX + seed).hex(),
        }
    d = 1 + secrets.randbelow(_P256_N - 1)
    spki, pkcs8 = _ecdsa_keys(d)
    return {"public_key": spki.hex(), "private_key": pkcs8.hex()}


def sign_message(message: str, private_key_hex: str, algorithm: str) -> str:
    """Sign `message` with a hex PKCS8 private key. Returns the hex signature."""
    _assert_algorithm(algorithm)
    if message == "":
        raise ValueError("Message must not be empty.")
    message_bytes = message.encode("utf-8")  # TextEncoder's role in the TS lib
    if algorithm == "ed25519":
        seed = hex_to_bytes(private_key_hex, "Private key")
        if not seed.startswith(_ED25519_PKCS8_PREFIX) or len(seed) != 48:
            raise ValueError("Invalid private key for Ed25519 (expected hex PKCS8).")
        return _ed_sign(seed[16:], message_bytes).hex()
    return _ecdsa_sign(_ecdsa_private_scalar(
        hex_to_bytes(private_key_hex, "Private key")), message_bytes).hex()


def verify_signature(message: str, signature_hex: str, public_key_hex: str,
                     algorithm: str) -> bool:
    """Verify `signatureHex` against `message` with a hex SPKI public key.

    Returns False when the signature, message or key simply do not match;
    raises only for malformed input (non-hex / wrong key type).
    """
    _assert_algorithm(algorithm)
    signature = hex_to_bytes(signature_hex, "Signature")
    public = hex_to_bytes(public_key_hex, "Public key")
    message_bytes = message.encode("utf-8")
    if algorithm == "ed25519":
        if not public.startswith(_ED25519_SPKI_PREFIX) or len(public) != 44:
            raise ValueError("Invalid public key for Ed25519 (expected hex SPKI).")
        try:
            _ed_decompress(public[12:])
        except ValueError:
            raise ValueError("Invalid public key for Ed25519 (expected hex SPKI).")
        return _ed_verify(message_bytes, signature, public[12:])
    return _ecdsa_verify(message_bytes, signature,
                         _ecdsa_public_point(public))

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →