使用Go语言创建Polygon公链钱包地址
生成Polygon公链钱包地址
Polygon是建立在以太坊上的Layer2解决方案,私钥、公钥、地址生成原理和以太坊一样。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
package main
import (
"crypto/ecdsa"
"fmt"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/crypto"
)
func main() {
ad, pk := generateKeyPair()
fmt.Printf("%s\n%s\n", ad, pk)
}
func generateKeyPair() (ad, pk string) {
// 生成私钥:生成一个随机的椭圆曲线数字签名算法(ECDSA)私钥
privateKey, _ := crypto.GenerateKey()
privateKeyBytes := crypto.FromECDSA(privateKey)
// 从私钥生成公钥
publicKey := privateKey.Public()
publicKeyECDSA, _ := publicKey.(*ecdsa.PublicKey)
// 从公钥生成钱包地址
address := crypto.PubkeyToAddress(*publicKeyECDSA).Hex()[2:]
return address, hexutil.Encode(privateKeyBytes)[2:]
}
|
运行代码,可在控制台看到生成的Polygon公链钱包地址:
1
2
3
|
go run main.go
533743B37E0cAbFc03bD9D97FfB91DD2c0A67AFA
ad6f0ae7269bb62831270ec2eeecc7db5b27c070dd7c312c382c4d21d0325347
|
生成Tron钱包地址
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
package main
import (
"crypto/ecdsa"
"crypto/sha256"
"encoding/hex"
"fmt"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/crypto"
"github.com/mr-tron/base58"
)
func main() {
b5, pk := generateKeyPair()
fmt.Printf("%s\n%s\n", b5, pk)
}
func generateKeyPair() (b5, pk string) {
privateKey, _ := crypto.GenerateKey()
privateKeyBytes := crypto.FromECDSA(privateKey)
publicKey := privateKey.Public()
publicKeyECDSA, _ := publicKey.(*ecdsa.PublicKey)
address := crypto.PubkeyToAddress(*publicKeyECDSA).Hex()
address = "41" + address[2:]
addb, _ := hex.DecodeString(address)
firstHash := sha256.Sum256(addb)
secondHash := sha256.Sum256(firstHash[:])
secret := secondHash[:4]
addb = append(addb, secret...)
return base58.Encode(addb), hexutil.Encode(privateKeyBytes)[2:]
}
|
运行代码,可在控制台看到生成的Tron钱包地址:
1
2
3
|
go run main.go
TSyuBVjRYSBWrpYVEim4WwVGjje1jQ5T43
0cae15edd66e8c74f29e33f63cd8553fa0d5facb97a4f8c6a16268859aaf11d3
|
参考