Skip to content

Instantly share code, notes, and snippets.

@rociiu
Created October 21, 2018 23:33
Show Gist options
  • Save rociiu/1460fffd1b07967c08447bd8207ce15c to your computer and use it in GitHub Desktop.
Save rociiu/1460fffd1b07967c08447bd8207ce15c to your computer and use it in GitHub Desktop.
convert private key from hex string
package main
import (
"crypto/ecdsa"
"encoding/hex"
"fmt"
"log"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/crypto"
)
func main() {
// pub: 0xc9a0554956b0f41c378975892fef4cff7158e807
// pri: 4aa770014d9a0324dea63ca32332561e752e0da861e18dc8a24a3894af2d789c
const privKeyHex string = "4aa770014d9a0324dea63ca32332561e752e0da861e18dc8a24a3894af2d789c"
key, err := hex.DecodeString(privKeyHex)
if err != nil {
fmt.Println("Failed to decode string")
return
}
priKey, err := crypto.ToECDSA(key)
if err != nil {
fmt.Println("Failed generate private key")
return
}
publicKey := priKey.Public()
publicKeyECDSA, ok := publicKey.(*ecdsa.PublicKey)
if !ok {
log.Fatal("error casting public key to ECDSA")
}
publicKeyBytes := crypto.FromECDSAPub(publicKeyECDSA)
fmt.Println(hexutil.Encode(publicKeyBytes)[4:])
address := crypto.PubkeyToAddress(*publicKeyECDSA).Hex()
fmt.Println(address)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment