Last active
February 16, 2018 22:20
-
-
Save alexanderattar/8808bfe686c4e31b693a39da2accb92a to your computer and use it in GitHub Desktop.
Example of verifying a ethereum signature from a signed message in Go. Returns the signers address.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"github.com/ethereum/go-ethereum/crypto" | |
"github.com/go-ethereum/common/hexutil" | |
) | |
func main() { | |
sig := hexutil.MustDecode( | |
"0xb79ef6e60652a547eda5b873ee846244ac294814bb4f15b24845ba93f5f5a5224faa295a885d7b08da327e3b884a7a436c45bb6471d02e0331a8f17a768042511b", | |
) | |
if len(sig) != 65 { | |
panic(fmt.Errorf("signature must be 65 bytes long")) | |
} | |
if sig[64] != 27 && sig[64] != 28 { | |
panic(fmt.Errorf("invalid Ethereum signature (V is not 27 or 28)")) | |
} | |
sig[64] -= 27 // Transform yellow paper V from 27/28 to 0/1 | |
msg := "\x19Ethereum Signed Message:\n5Login" | |
data := crypto.Keccak256([]byte(msg)) | |
rpk, err := crypto.Ecrecover(data, sig) | |
if err != nil { | |
panic(err) | |
} | |
pubKey := crypto.ToECDSAPub(rpk) | |
recoveredAddr := crypto.PubkeyToAddress(*pubKey) | |
fmt.Printf("0x%x\n", recoveredAddr) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment