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.
Code
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
HMAC GeneratorCompute an HMAC-SHA-256, SHA-384, or SHA-512 signature for a message and key using the Web Crypto API, with hex and Base64 output.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.SHA-256 Hash GeneratorGenerate SHA-256 cryptographic hashes from text input using the Web Crypto API. Compare hashes and verify data integrity with hexadecimal digest output.JWT Signature InspectorInspect a JWT signature: decode the header and payload, show the algorithm and signature bytes, and verify HS256/384/512 HMAC signatures with a secret.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.