Skip to content

Digital Signature — Go source

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

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

// Package digitalsignature is the Go twin of CosmoDev's
// src/lib/digital-signature.ts (dual source: the web lib is TypeScript, the
// CLI lib is Go — kept in lock-step). Pure logic, never panics — invalid input
// returns errors. The table-driven tests in digital_signature_test.go share
// vectors with src/lib/digital-signature.test.ts so the two implementations
// are held to the same contract.
//
// Where the TS lib leans on the Web Crypto API, this port uses the Go stdlib:
// crypto/ed25519 and crypto/ecdsa over P-256, keys marshalled with crypto/x509.
// Key encoding matches the TS lib exactly: hex of the standard DER structures —
// SPKI (SubjectPublicKeyInfo) for public keys, PKCS8 for private keys — so keys
// interoperate with OpenSSL, SSH, JOSE tooling and the web tool. Signatures
// are hex of the raw signature bytes: 64 bytes for both algorithms (Ed25519
// R||S; ECDSA P-256 in IEEE P1363 r||s layout, NOT ASN.1 DER — Go's ecdsa
// package speaks DER, so this port converts both directions). ECDSA signs the
// SHA-256 digest of the message, like Web Crypto's {hash: 'SHA-256'}.
package digitalsignature

import (
	"crypto/ecdsa"
	"crypto/ed25519"
	"crypto/elliptic"
	"crypto/rand"
	"crypto/sha256"
	"crypto/x509"
	"encoding/hex"
	"errors"
	"fmt"
	"math/big"
)

// SignAlgorithm selects the signing algorithm. It mirrors the TS union type
// 'ed25519' | 'ecdsa-p256'; plain string constants convert implicitly.
type SignAlgorithm string

const (
	// Ed25519 is the Ed25519 digital signature scheme (signs the message
	// directly; deterministic signatures).
	Ed25519 SignAlgorithm = "ed25519"
	// EcdsaP256 is ECDSA over the NIST P-256 curve, signing the SHA-256
	// digest of the message.
	EcdsaP256 SignAlgorithm = "ecdsa-p256"
)

// KeyPair is a freshly generated signing key pair, mirroring the TS KeyPair.
type KeyPair struct {
	// PublicKey is the hex-encoded SPKI (SubjectPublicKeyInfo) public key.
	// Safe to share.
	PublicKey string
	// PrivateKey is the hex-encoded PKCS8 private key. Keep it secret — it
	// IS the identity.
	PrivateKey string
}

// assertAlgorithm mirrors assertAlgorithm() in the TS lib.
func assertAlgorithm(algorithm SignAlgorithm) error {
	if algorithm != Ed25519 && algorithm != EcdsaP256 {
		return errors.New(`Unknown algorithm. Use "ed25519" or "ecdsa-p256".`)
	}
	return nil
}

// label mirrors label() in the TS lib: the human name used in key errors.
func label(algorithm SignAlgorithm) string {
	if algorithm == Ed25519 {
		return "Ed25519"
	}
	return "ECDSA P-256"
}

// hexToBytes mirrors hexToBytes() in the TS lib: non-empty, even-length,
// hexadecimal-only input, decoded to bytes. `what` names the value in errors.
func hexToBytes(s, what string) ([]byte, error) {
	if s == "" {
		return nil, fmt.Errorf("%s must be a non-empty hex string (pairs of 0-9 / a-f digits).", what)
	}
	out, err := hex.DecodeString(s)
	if err != nil {
		return nil, fmt.Errorf("%s must be a non-empty hex string (pairs of 0-9 / a-f digits).", what)
	}
	return out, nil
}

// toHex lower-hex-encodes bytes, mirroring toHex() in the TS lib.
func toHex(b []byte) string {
	return hex.EncodeToString(b)
}

// parsePrivateKey mirrors importPrivateKey() in the TS lib: decode hex PKCS8
// DER and require the key type to match the requested algorithm.
func parsePrivateKey(privateKeyHex string, algorithm SignAlgorithm) (any, error) {
	der, err := hexToBytes(privateKeyHex, "Private key")
	if err != nil {
		return nil, err
	}
	key, err := x509.ParsePKCS8PrivateKey(der)
	if err != nil {
		return nil, invalidPrivateKey(algorithm)
	}
	switch k := key.(type) {
	case ed25519.PrivateKey:
		if algorithm != Ed25519 {
			return nil, invalidPrivateKey(algorithm)
		}
	case *ecdsa.PrivateKey:
		if algorithm != EcdsaP256 || k.Curve != elliptic.P256() {
			return nil, invalidPrivateKey(algorithm)
		}
	default:
		return nil, invalidPrivateKey(algorithm)
	}
	return key, nil
}

// parsePublicKey mirrors importPublicKey() in the TS lib: decode hex SPKI DER
// and require the key type to match the requested algorithm.
func parsePublicKey(publicKeyHex string, algorithm SignAlgorithm) (any, error) {
	der, err := hexToBytes(publicKeyHex, "Public key")
	if err != nil {
		return nil, err
	}
	key, err := x509.ParsePKIXPublicKey(der)
	if err != nil {
		return nil, invalidPublicKey(algorithm)
	}
	switch k := key.(type) {
	case ed25519.PublicKey:
		if algorithm != Ed25519 {
			return nil, invalidPublicKey(algorithm)
		}
	case *ecdsa.PublicKey:
		if algorithm != EcdsaP256 || k.Curve != elliptic.P256() {
			return nil, invalidPublicKey(algorithm)
		}
	default:
		return nil, invalidPublicKey(algorithm)
	}
	return key, nil
}

func invalidPrivateKey(algorithm SignAlgorithm) error {
	return fmt.Errorf("Invalid private key for %s (expected hex PKCS8).", label(algorithm))
}

func invalidPublicKey(algorithm SignAlgorithm) error {
	return fmt.Errorf("Invalid public key for %s (expected hex SPKI).", label(algorithm))
}

// GenerateKeyPair generates a fresh signing key pair, exported as hex SPKI /
// PKCS8 keys. It is the Go twin of generateKeyPair() in
// src/lib/digital-signature.ts.
func GenerateKeyPair(algorithm SignAlgorithm) (KeyPair, error) {
	if err := assertAlgorithm(algorithm); err != nil {
		return KeyPair{}, err
	}
	var spki, pkcs8 []byte
	if algorithm == Ed25519 {
		pub, priv, err := ed25519.GenerateKey(rand.Reader)
		if err != nil {
			return KeyPair{}, errors.New("Ed25519 key generation failed.")
		}
		if spki, err = x509.MarshalPKIXPublicKey(pub); err != nil {
			return KeyPair{}, errors.New("Ed25519 key generation failed.")
		}
		if pkcs8, err = x509.MarshalPKCS8PrivateKey(priv); err != nil {
			return KeyPair{}, errors.New("Ed25519 key generation failed.")
		}
	} else {
		priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
		if err != nil {
			return KeyPair{}, errors.New("ECDSA P-256 key generation failed.")
		}
		if spki, err = x509.MarshalPKIXPublicKey(&priv.PublicKey); err != nil {
			return KeyPair{}, errors.New("ECDSA P-256 key generation failed.")
		}
		if pkcs8, err = x509.MarshalPKCS8PrivateKey(priv); err != nil {
			return KeyPair{}, errors.New("ECDSA P-256 key generation failed.")
		}
	}
	return KeyPair{PublicKey: toHex(spki), PrivateKey: toHex(pkcs8)}, nil
}

// SignMessage signs message with a hex PKCS8 private key and returns the hex
// signature. It is the Go twin of signMessage() in
// src/lib/digital-signature.ts and must agree with it on every shared vector.
func SignMessage(message string, privateKeyHex string, algorithm SignAlgorithm) (string, error) {
	if err := assertAlgorithm(algorithm); err != nil {
		return "", err
	}
	if message == "" {
		return "", errors.New("Message must not be empty.")
	}
	key, err := parsePrivateKey(privateKeyHex, algorithm)
	if err != nil {
		return "", err
	}
	if algorithm == Ed25519 {
		return toHex(ed25519.Sign(key.(ed25519.PrivateKey), []byte(message))), nil
	}
	digest := sha256.Sum256([]byte(message))
	r, s, err := ecdsa.Sign(rand.Reader, key.(*ecdsa.PrivateKey), digest[:])
	if err != nil {
		return "", fmt.Errorf("Signing failed: %v", err)
	}
	// Fixed-width IEEE P1363 r||s layout (32 + 32 bytes for P-256), matching
	// the raw Web Crypto signature bytes.
	raw := make([]byte, 64)
	r.FillBytes(raw[:32])
	s.FillBytes(raw[32:])
	return toHex(raw), nil
}

// VerifySignature verifies signatureHex against message with a hex SPKI
// public key. It returns false when the signature, message or key simply do
// not match; it errors only for malformed input (non-hex / wrong key type) —
// mirroring verifySignature() in src/lib/digital-signature.ts.
func VerifySignature(message string, signatureHex string, publicKeyHex string, algorithm SignAlgorithm) (bool, error) {
	if err := assertAlgorithm(algorithm); err != nil {
		return false, err
	}
	signature, err := hexToBytes(signatureHex, "Signature")
	if err != nil {
		return false, err
	}
	key, err := parsePublicKey(publicKeyHex, algorithm)
	if err != nil {
		return false, err
	}
	if algorithm == Ed25519 {
		return ed25519.Verify(key.(ed25519.PublicKey), []byte(message), signature), nil
	}
	if len(signature) != 64 {
		return false, nil // wrong-length signature never verifies (browser parity)
	}
	digest := sha256.Sum256([]byte(message))
	r := new(big.Int).SetBytes(signature[:32])
	s := new(big.Int).SetBytes(signature[32:])
	return ecdsa.Verify(key.(*ecdsa.PublicKey), digest[:], r, s), nil
}

// flipHexChar flips one hex character of s at index i to a different hex
// digit, mirroring the tampered-signature vector in the TS tests.
func flipHexChar(s string, i int) string {
	b := []byte(s)
	if b[i] == 'a' {
		b[i] = 'b'
	} else {
		b[i] = 'a'
	}
	return string(b)
}

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 →