How to Sign and Verify Data with RSA or ECDSA in Go

Sign and verify data in Go using the crypto/rsa and crypto/ecdsa packages with SHA256 hashing.

Use the crypto/rsa or crypto/ecdsa packages with crypto/x509 to sign and verify data in Go.

package main

import (
	"crypto"
	"crypto/ecdsa"
	"crypto/rand"
	"crypto/rsa"
	"crypto/sha256"
	"crypto/x509"
	"encoding/pem"
)

func main() {
	// Generate RSA Key Pair
	pk, _ := rsa.GenerateKey(rand.Reader, 2048)
	pkBytes, _ := x509.MarshalPKCS8PrivateKey(pk)
	pem.Encode(os.Stdout, &pem.Block{Type: "PRIVATE KEY", Bytes: pkBytes})

	// Sign Data
	data := []byte("Hello")
	h := sha256.New()
	h.Write(data)
	signature, _ := rsa.SignPKCS1v15(rand.Reader, pk, crypto.SHA256, h.Sum(nil))

	// Verify Signature
	pkPub := pk.Public()
	err := rsa.VerifyPKCS1v15(pkPub, crypto.SHA256, h.Sum(nil), signature)
	if err != nil {
		panic(err)
	}

	// ECDSA Example
	ecKey, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	ecSig, _ := ecdsa.Sign(rand.Reader, ecKey, h.Sum(nil))
	ecValid := ecdsa.Verify(&ecKey.PublicKey, h.Sum(nil), ecSig.R, ecSig.S)
}