ECDSA SignASN1 And VerifyASN1 With P256

SignASN1 produces a DER-encoded ECDSA signature over a SHA-256 digest, and VerifyASN1 rejects the same signature for a different message.

GoSecurity Boundaries

Code

gosnippet
33 lines
package main

import (
	"crypto/ecdsa"
	"crypto/elliptic"
	"crypto/rand"
	"crypto/sha256"
	"fmt"
)

func main() {
	key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		panic(err)
	}

	message := []byte("release notes 2026-11-20")
	digest := sha256.Sum256(message)

	// SignASN1 produces a DER-encoded signature over the digest
	signature, err := ecdsa.SignASN1(rand.Reader, key, digest[:])
	if err != nil {
		panic(err)
	}
	fmt.Println("signature bytes:", len(signature))

	// VerifyASN1 checks the same digest against the public key
	fmt.Println("valid:", ecdsa.VerifyASN1(&key.PublicKey, digest[:], signature))

	// a different message fails verification with the same signature
	tampered := sha256.Sum256([]byte("release notes 2026-11-21"))
	fmt.Println("tampered valid:", ecdsa.VerifyASN1(&key.PublicKey, tampered[:], signature))
}

How it works

Everything happens inside the function main.

Failure handling is panic(err): 2 checkpoints abort the program at the point a problem is detected.

What to watch for

  • Runs on the standard library alone; nothing to install.
  • panic(err) is the only failure path here: the first problem stops the program.

Using it

The one signature that matters here is func main()

The output comes back labeled — signature bytes:, valid:, tampered valid: — when the file runs.

Key statements worth quoting

if err != nil {
	panic(err)
}

Interactive Tools for This Topic

FAQ

How does the code signal failure?
Through `panic(err)` — the 2 checkpoints test `err` and abort the run on the first non-nil one.
What does ECDSA SignASN1 And VerifyASN1 With P256 print when run?
Invoke the file as-is — the `signature bytes:`, `valid:`, `tampered valid:` prefixes identify which step printed each line.