简体   繁体   English

在 Go 中的字符串中解析以太坊私钥

[英]Parse Ethereum private key in string in Go

I am trying really hard to convert Ethereum private keys BIP44 in string format to a type that can (*ecdsa.PrivateKey) be used by rest of the code.我正在努力将字符串格式的以太坊私钥 BIP44 转换为代码的 rest 可以使用的类型(*ecdsa.PrivateKey)。


import (
    "crypto/x509"
    "fmt"
    "log"

    "github.com/ethereum/go-ethereum/common/hexutil"
    "github.com/ethereum/go-ethereum/crypto"
)

const (
    privateKey2 string = "0xbacd06016aea4280e14efd7182ba18cd98bf11701943d3d47d76b04bb7baad19"
)

func main() {
    _, err = x509.ParsePKCS8PrivateKey(firstKey)
    if err != nil {
        fmt.Println("Cannot parse private key")
    }

}

Here is how a private key can be converted to Ethereum address You need to import one additional package "crypto/ecdsa" and also remove "0x" from the private key.这是如何将私钥转换为以太坊地址的方法 您需要导入一个额外的 package “crypto/ecdsa”,并从私钥中删除“0x”。

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

    publicKey := privateKey.Public()
    publicKeyECDSA, ok := publicKey.(*ecdsa.PublicKey)
    if !ok {
        log.Fatal("error casting public key to ECDSA")
    }

    fromAddress := crypto.PubkeyToAddress(*publicKeyECDSA)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM