借助geth官方提供的函數可以很簡單的實現代碼如下
package main import ( "crypto/ecdsa" "encoding/hex" "fmt" "github.com/ethereum/go-ethereum/crypto" ) func main() { priKeyHash := "796c823671b118258b53ef6056fd1f9fc96d125600f348f75f397b2000267fe8" // 創建私鑰對象,上面私鑰沒有錢哦 priKey, err := crypto.HexToECDSA(priKeyHash) if err != nil { panic(err) } priKeyBytes := crypto.FromECDSA(priKey) fmt.Printf("私鑰為: %s\n", hex.EncodeToString(priKeyBytes)) pubKey := priKey.Public().(*ecdsa.PublicKey) // 獲取公鑰並去除頭部0x04 pubKeyBytes := crypto.FromECDSAPub(pubKey)[1:] fmt.Printf("公鑰為: %s\n", hex.EncodeToString(pubKeyBytes)) // 獲取地址 addr := crypto.PubkeyToAddress(*pubKey) fmt.Printf("地址為: %s\n", addr.Hex()) }