生成新钱包

package main

import (
    "crypto/ecdsa"
    "fmt"
    "log"

    "github.com/ethereum/go-ethereum/common/hexutil"
    "github.com/ethereum/go-ethereum/crypto"
    "golang.org/x/crypto/sha3"
)

func main() {
    privateKey, err := crypto.GenerateKey()
    if err != nil {
        log.Fatal(err)
    }

    privateKeyBytes := crypto.FromECDSA(privateKey)
    fmt.Println(hexutil.Encode(privateKeyBytes)[2:]) // fad9c8855b740a0b7ed4c221dbad0f33a83a49cad6b3fe8d5817ac83d38b6a19

    publicKey := privateKey.Public()
    publicKeyECDSA, ok := publicKey.(*ecdsa.PublicKey)
    if !ok {
        log.Fatal("cannot assert type: publicKey is not of type *ecdsa.PublicKey")
    }

    publicKeyBytes := crypto.FromECDSAPub(publicKeyECDSA)
    fmt.Println(hexutil.Encode(publicKeyBytes)[4:]) // 9a7df67f79246283fdc93af76d4f8cdd62c4886e8cd870944e817dd0b97934fdd7719d0810951e03418205868a5c1b40b192451367f28e0088dd75e15de40c05

    address := crypto.PubkeyToAddress(*publicKeyECDSA).Hex()
    fmt.Println(address) // 0x96216849c49358B10257cb55b28eA603c874b05E

    hash := sha3.NewLegacyKeccak256()
    hash.Write(publicKeyBytes[1:])
    fmt.Println(hexutil.Encode(hash.Sum(nil)[12:])) // 0x96216849c49358b10257cb55b28ea603c874b05e
}

要生成新的钱包,首先我们需要导入提供生成随机私钥的方法的go - ethereum 包。cryptoGenerateKey

privateKey, err := crypto.GenerateKey()
if err != nil {
  log.Fatal(err)
}

然后我们可以通过导入golang crypto/ecdsa包并使用该FromECDSA方法将其转换为字节。

privateKeyBytes := crypto.FromECDSA(privateKey)

现在,我们可以使用go - ethereum 包将其转换为十六进制字符串,hexutil该包提供了采用字节切片的方法。然后我们在十六进制编码后Encode删除。0x

fmt.Println(hexutil.Encode(privateKeyBytes)[2:]) // fad9c8855b740a0b7ed4c221dbad0f33a83a49cad6b3fe8d5817ac83d38b6a19

这是用于签署交易的私钥,应像密码一样对待,不得共享,因为拥有它的人就可以访问您的所有资金。

由于公钥是从私钥派生出来的,因此go - ethereum的加密私钥有一个Public方法可以返回公钥。

publicKey := privateKey.Public()

将其转换为十六进制的过程与我们对私钥进行的操作类似。我们删除0x前 2 个字符,04这 2 个字符始终是 EC 前缀,并且不是必需的。

publicKeyECDSA, ok := publicKey.(*ecdsa.PublicKey)
if !ok {
  log.Fatal("cannot assert type: publicKey is not of type *ecdsa.PublicKey")
}

publicKeyBytes := crypto.FromECDSAPub(publicKeyECDSA)
fmt.Println(hexutil.Encode(publicKeyBytes)[4:]) // 9a7df67f79246283fdc93af76d4f8cdd62c4886e8cd870944e817dd0b97934fdd7719d0810951e03418205868a5c1b40b192451367f28e0088dd75e15de40c05

现在我们有了公钥,我们可以轻松生成您习惯看到的公共地址。为了做到这一点,go - ethereum crypto 包有一个PubkeyToAddress方法,它接受 ECDSA 公钥并返回公共地址。

address := crypto.PubkeyToAddress(*publicKeyECDSA).Hex()
fmt.Println(address) // 0x96216849c49358B10257cb55b28eA603c874b05E

公共地址只是公钥的Keccak-2560x哈希,然后我们取最后 40 个字符(20 个字节)并在其前面加上前缀。以下是使用crypto/sha3keccak256 函数手动执行此操作的方法。

hash := sha3.NewLegacyKeccak256()
hash.Write(publicKeyBytes[1:])
fmt.Println(hexutil.Encode(hash.Sum(nil)[12:])) // 0x96216849c49358b10257cb55b28ea603c874b05e

你可能感兴趣的:(golang)