import ( “crypto/ecdsa” “crypto/rand” “crypto/x509” “encoding/pem” “fmt” ) func signData(data []byte, privateKey *ecdsa.PrivateKey) ([]byte, error) { hash := sha256.Sum256(data) return ecdsa.SignASN1(rand.Reader, privateKey, hash[:]) } func main() { // generate a new ECDSA private key privateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) if err != nil { panic(err) } // encode private key as PEM privKeyBytes, err := x509.MarshalECPrivateKey(privateKey) if err != nil { panic(err) } pemKey := pem.EncodeToMemory(&pem.Block{ Type: "EC PRIVATE KEY", Bytes: privKeyBytes, }) // sign some data data := []byte("hello world") signature, err := signData(data, privateKey) if err != nil { panic(err) } fmt.Printf("signature: %x\n", signature) }
import ( “crypto/rand” “crypto/rsa” “crypto/x509” “encoding/pem” “fmt” ) func signData(data []byte, privateKey *rsa.PrivateKey) ([]byte, error) { hash := sha256.Sum256(data) return rsa.SignPKCS1v15(rand.Reader, privateKey, crypto.SHA256, hash[:]) } func main() { // generate a new RSA private key privateKey, err := rsa.GenerateKey(rand.Reader, 2048) if err != nil { panic(err) } // encode private key as PEM privKeyBytes := x509.MarshalPKCS1PrivateKey(privateKey) pemKey := pem.EncodeToMemory(&pem.Block{ Type: "RSA PRIVATE KEY", Bytes: privKeyBytes, }) // sign some data data := []byte("hello world") signature, err := signData(data, privateKey) if err != nil { panic(err) } fmt.Printf("signature: %x\n", signature) }In both examples, the Go crypto Signer package is used to perform the signing operations.