Skip to content

Instantly share code, notes, and snippets.

@udhos
Created August 27, 2020 07:50
Show Gist options
  • Select an option

  • Save udhos/b1370f0bdeb6f9010564a6d48dcf0866 to your computer and use it in GitHub Desktop.

Select an option

Save udhos/b1370f0bdeb6f9010564a6d48dcf0866 to your computer and use it in GitHub Desktop.
Golang : Example for ECDSA(Elliptic Curve Digital Signature Algorithm) package functions
// https://www.socketloop.com/tutorials/golang-example-for-ecdsa-elliptic-curve-digital-signature-algorithm-functions
package main
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/md5"
"crypto/rand"
"fmt"
"hash"
"io"
"math/big"
"os"
)
func main() {
pubkeyCurve := elliptic.P256() //see http://golang.org/pkg/crypto/elliptic/#P256
privatekey := new(ecdsa.PrivateKey)
privatekey, err := ecdsa.GenerateKey(pubkeyCurve, rand.Reader) // this generates a public & private key pair
if err != nil {
fmt.Println(err)
os.Exit(1)
}
var pubkey ecdsa.PublicKey
pubkey = privatekey.PublicKey
fmt.Println("Private Key :")
fmt.Printf("%x \n", privatekey)
fmt.Println("Public Key :")
fmt.Printf("%x \n", pubkey)
// Sign ecdsa style
var h hash.Hash
h = md5.New()
r := big.NewInt(0)
s := big.NewInt(0)
io.WriteString(h, "This is a message to be signed and verified by ECDSA!")
signhash := h.Sum(nil)
r, s, serr := ecdsa.Sign(rand.Reader, privatekey, signhash)
if serr != nil {
fmt.Println(err)
os.Exit(1)
}
signature := r.Bytes()
signature = append(signature, s.Bytes()...)
fmt.Printf("Signature : %x\n", signature)
// Verify
verifystatus := ecdsa.Verify(&pubkey, signhash, r, s)
fmt.Println(verifystatus) // should be true
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment