Skip to content

Instantly share code, notes, and snippets.

@qbig
Created November 5, 2018 07:35
Show Gist options
  • Save qbig/313b06424d96619144b9fd593ae64dac to your computer and use it in GitHub Desktop.
Save qbig/313b06424d96619144b9fd593ae64dac to your computer and use it in GitHub Desktop.
Verify signature with go-ethereum
package main
import (
"bytes"
"crypto/ecdsa"
"fmt"
"log"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/crypto"
)
func main() {
privateKey, err := crypto.HexToECDSA("fad9c8855b740a0b7ed4c221dbad0f33a83a49cad6b3fe8d5817ac83d38b6a19")
if err != nil {
log.Fatal(err)
}
publicKey := privateKey.Public()
publicKeyECDSA, ok := publicKey.(*ecdsa.PublicKey)
if !ok {
log.Fatal("error casting public key to ECDSA")
}
publicKeyBytes := crypto.FromECDSAPub(publicKeyECDSA)
data := []byte("hello")
hash := crypto.Keccak256Hash(data)
fmt.Println(hash.Hex()) // 0x1c8aff950685c2ed4bc3174f3472287b56d9517b9c948127319a09a7a36deac8
signature, err := crypto.Sign(hash.Bytes(), privateKey)
if err != nil {
log.Fatal(err)
}
fmt.Println(hexutil.Encode(signature)) // 0x789a80053e4927d0a898db8e065e948f5cf086e32f9ccaa54c1908e22ac430c62621578113ddbb62d509bf6049b8fb544ab06d36f916685a2eb8e57ffadde02301
sigPublicKey, err := crypto.Ecrecover(hash.Bytes(), signature)
if err != nil {
log.Fatal(err)
}
matches := bytes.Equal(sigPublicKey, publicKeyBytes)
fmt.Println(matches) // true
sigPublicKeyECDSA, err := crypto.SigToPub(hash.Bytes(), signature)
if err != nil {
log.Fatal(err)
}
sigPublicKeyBytes := crypto.FromECDSAPub(sigPublicKeyECDSA)
matches = bytes.Equal(sigPublicKeyBytes, publicKeyBytes)
fmt.Println(matches) // true
signatureNoRecoverID := signature[:len(signature)-1] // remove recovery id
verified := crypto.VerifySignature(publicKeyBytes, hash.Bytes(), signatureNoRecoverID)
fmt.Println(verified) // true
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment