实现代码:
func NewAddress(strPrivKey string) (string, error) {
var (
uncompressPubKey []byte
pubKeyHash256 []byte
err error
buf []byte
)
if buf, err = hex.DecodeString(strPrivKey); err != nil {
return "", err
}
privKey := secp256k1.PrivKeyFromBytes(buf)
//拿公钥(非压缩公钥)来hash,计算公钥的 Keccak-256 哈希值(32bytes)
uncompressPubKey = append(privKey.PubKey().X().Bytes(), privKey.PubKey().Y().Bytes()...)
//计算公钥的Keccak256哈希值
pubKeyHash256 = common.Keccak256Hash(uncompressPubKey)
//取上一步结果取后20bytes即以太坊地址
address := string("0x")+hex.EncodeToString(pubKeyHash256[len(pubKeyHash256)-20:])
return ToValidateAddress(string(address)), nil
}
测试代码:
func TestNewAddress(t *testing.T) {
var testcases = []struct {
privk string
address string
} {
{
"E452FE5BB764BE2F3E030B6CE5C16E7A68BB341D0D2FDE13AAE5347690F12B52",
"0x50352B904445576242444bc1924e93e61090738C",
},
}
var (
got string
err error
)
for _, oneCase := range testcases {
if got,err = NewAddress(oneCase.privk); err != nil {
t.Error(err)
return
}
if got != oneCase.address {
t.Error("new address error")
t.Error("want: ", oneCase.address)
t.Error("got: ", got)
return
}
}
}
(全文完)