Blockchain foundations in Go · 5 MIN READ

secp256k1 signatures: sign a 32-byte digest, recover the signer and reject high-s twins

Sign a Keccak-256 digest with go-ethereum's crypto package, recover and check the signer's address, and enforce the low-s rule on untrusted signatures.

A hash chain shows that data changed; a signature shows who approved it. Ethereum and Bitcoin use ECDSA over the secp256k1 curve, and Ethereum appends a recovery byte so that a verifier can compute the signer's public key from the signature instead of receiving it. Recovery always produces some key, so the code that matters is the comparison with the address you expected and the checks that reject malleable signatures.

blockchain · A MAP OF THE IDEA

  1. Hash the message yourself
  2. Sign the 32-byte digest
  3. Recover and compare address
  4. Reject high-s and bad v

Useful when

  • The signer is computed, so no public key travels with the data.
  • Deterministic RFC 6979 nonces make signing reproducible in tests.

Watch out

  • Recovery returns some key for any digest; compare the address.
  • SigToPub and Ecrecover accept high-s twins; validate values first.

Implementation & operation cost: One Keccak-256 and one public-key recovery per verification, plus explicit normalization of v at every boundary that accepts signatures.

01

What a recoverable signature contains

crypto.Sign returns 65 bytes: r and s, 32 bytes each, followed by a recovery id v of 0 or 1. r and s form an ordinary ECDSA signature; v tells the recovery algorithm which candidate curve point the signer used, so crypto.SigToPub and crypto.Ecrecover return exactly one public key. That is why an Ethereum transaction carries no public key and no from field: the sender is computed from the signature. The byte encoding of v varies by context. Legacy transactions store 27 or 28, EIP-155 transactions store chainID*2+35 or +36, typed transactions store a yParity of 0 or 1, and personal_sign signatures usually end in 27 or 28. Normalize to 0 or 1 at the boundary before calling the crypto package, and leave transaction encodings to the signers in core/types.

02

Sign and recover with a fixed test key

The program derives a test key from 32 bytes of 0x01, a well-known throwaway value that must never hold funds, and it never contacts a network. It signs a Keccak-256 digest, recovers the public key, then edits the message and recovers again. Finally it builds the mirror-image signature (r, N-s) with the recovery bit flipped, where N is the curve order, and runs it through the checks go-ethereum offers.

go
package main

import (
	"bytes"
	"fmt"
	"math/big"

	"github.com/ethereum/go-ethereum/crypto"
)

func main() {
	// TEST KEY ONLY: fixed bytes, never funded, never used on a real network.
	key, err := crypto.ToECDSA(bytes.Repeat([]byte{1}, 32))
	if err != nil {
		panic(err)
	}
	signer := crypto.PubkeyToAddress(key.PublicKey)
	fmt.Println("test signer:", signer.Hex())

	if _, err := crypto.Sign([]byte("not a digest"), key); err != nil {
		fmt.Println("raw message:", err)
	}

	digest := crypto.Keccak256([]byte("chain 1337: pay bob 5, nonce 7"))
	sig, err := crypto.Sign(digest, key)
	if err != nil {
		panic(err)
	}
	again, _ := crypto.Sign(digest, key)
	fmt.Println("signature:", len(sig), "bytes, v =", sig[64], "deterministic:", bytes.Equal(sig, again))

	pub, err := crypto.SigToPub(digest, sig)
	fmt.Println("recovered == signer:", err == nil && crypto.PubkeyToAddress(*pub) == signer)

	edited := crypto.Keccak256([]byte("chain 1337: pay bob 500, nonce 7"))
	other, err := crypto.SigToPub(edited, sig)
	if err != nil {
		panic(err)
	}
	fmt.Println("edited message: no error, recovered == signer:", crypto.PubkeyToAddress(*other) == signer)

	// Build the high-s twin (r, N-s) with the recovery bit flipped.
	n := crypto.S256().Params().N
	r := new(big.Int).SetBytes(sig[:32])
	s := new(big.Int).SetBytes(sig[32:64])
	twinS := new(big.Int).Sub(n, s)
	twin := make([]byte, 65)
	copy(twin, sig[:32])
	twinS.FillBytes(twin[32:64])
	twin[64] = sig[64] ^ 1

	twinPub, err := crypto.SigToPub(digest, twin)
	fmt.Println("twin recovers signer:", err == nil && crypto.PubkeyToAddress(*twinPub) == signer)
	pubBytes := crypto.FromECDSAPub(&key.PublicKey)
	fmt.Println("low-s rule accepts original:", crypto.ValidateSignatureValues(sig[64], r, s, true),
		"twin:", crypto.ValidateSignatureValues(twin[64], r, twinS, true))
	fmt.Println("VerifySignature original:", crypto.VerifySignature(pubBytes, digest, sig[:64]),
		"twin:", crypto.VerifySignature(pubBytes, digest, twin[:64]))
}
Read the code

crypto.Sign refuses the 12-byte string because it requires exactly 32 bytes, so callers must hash first. Signing the same digest twice yields identical bytes because the nonce is derived from the key and the digest as in RFC 6979, with no random source. SigToPub on the edited digest returns no error and a valid but different public key; only the address comparison catches it. The twin recovers the same signer, so recovery alone does not make signatures unique. ValidateSignatureValues with homestead set to true and VerifySignature both reject the twin because its s is above N/2.

03

Why you sign a digest, never raw input

ECDSA signs a number smaller than the curve order, so it needs fixed-size input; Ethereum uses Keccak-256 and Bitcoin uses double SHA-256. Size is the smaller reason. The go-ethereum documentation for Sign warns that the hash must not be chosen by an adversary. A service that signs whatever 32 bytes a caller supplies is a signing oracle, and those bytes may be the hash of a transaction that spends the service's funds. Hash your own structured message with a prefix that says what it is: accounts.TextHash implements the EIP-191 prefix "\x19Ethereum Signed Message:\n" plus the message length, and EIP-712 hashes typed data under a domain. The signing-boundaries lesson covers key custody and domain policy; the rule at the primitive level is that the signer owns the hashing step.

04

Malleability and the low-s rule

For every valid ECDSA signature (r, s), the pair (r, N-s) is also valid for the same key and message. If any part of a system identifies data by the hash of its signed bytes, a third party can flip s and produce a second valid encoding with a different identifier, without the key. Bitcoin suffered this as transaction-ID malleability, and Ethereum's Homestead upgrade (EIP-2) made transactions with s above N/2 invalid. In go-ethereum the rule is crypto.ValidateSignatureValues(v, r, s, homestead), which the transaction signers call before recovering, and VerifySignature also rejects high s. Ecrecover and SigToPub do not, and EIP-2 deliberately left the on-chain ecrecover precompile accepting high s, so contracts must check it too. When you accept signatures from users, for logins or off-chain orders, validate the values yourself and never key a record by signature bytes.

05

Test the verifier, not just the signer

Keep the test key fixed and labeled, and assert known answers: the 0x01-repeated key has the address 0x1a642f0E3c3aF545E7AcBD38b07251B3990914F1, so a regression in key derivation fails at once. Write negative tests for a wrong digest, a wrong expected address, the high-s twin, v outside 0 and 1, r or s equal to zero or N, a 64-byte signature without v and a digest of the wrong length. If you ship builds with and without cgo, run the suite both ways: go-ethereum uses the decred secp256k1 package when cgo is off and libsecp256k1 when it is on, and your checks should not depend on which one recovered the key. Prefer fixed vectors to crypto.GenerateKey in tests so that every failure is reproducible.

TAKE THIS WITH YOU

Sign only digests you computed, recover the key and compare its address with the one you expected, and reject high-s or malformed values with ValidateSignatureValues before trusting a signature.

Check your understanding

crypto.SigToPub recovers the same signer from a signature (r, s) and its twin (r, N-s). Which check rejects the twin before you trust it?

Go to the source

Progress stays in this browser. No account needed.