如何使用GO?

发布于 2025-02-10 07:07:36 字数 1194 浏览 0 评论 0原文

我有以下代码:

func newAddress() string {
    privKey, _ := crypto.GenerateKey()
    publicKey := privKey.Public()
    publicKeyECDSA, _ := publicKey.(*ecdsa.PublicKey)
    address := crypto.PubkeyToAddress(*publicKeyECDSA).Hex()
    return address
}

现在我想编码publickey和privateKey并保存:

func newAddress() string {
    privKey, _ := crypto.GenerateKey()
    publicKey := privKey.Public()
    publicKeyECDSA, _ := publicKey.(*ecdsa.PublicKey)
    address := crypto.PubkeyToAddress(*publicKeyECDSA).Hex()
    x509EncodedPri, _ := x509.MarshalECPrivateKey(privKey)
    block := pem.Block{
        Type:    "ECDSA Private Key",
        Headers: nil,
        Bytes:   x509EncodedPri,
    }
    file, err := os.Create("eccPrivate.pem")
    if err != nil {
        log.Fatal(err)
    }
    defer file.Close()
    pem.Encode(file, &block)
    return address
}

我发现它是空的:

$ cat  eccPrivate.pem
-----BEGIN ECDSA Private Key-----
-----END ECDSA Private Key-----

我知道我应该使用ecdsa.generetykey(elliptic.p256(),rand.reader)>要生成私钥,但我最终得到了与crypto.generekey()
不同的地址 如果有人能告诉我我出错了哪里,那将不胜感激。

I have the following code:

func newAddress() string {
    privKey, _ := crypto.GenerateKey()
    publicKey := privKey.Public()
    publicKeyECDSA, _ := publicKey.(*ecdsa.PublicKey)
    address := crypto.PubkeyToAddress(*publicKeyECDSA).Hex()
    return address
}

Now I want to pem encode the publicKey and privatekey and save:

func newAddress() string {
    privKey, _ := crypto.GenerateKey()
    publicKey := privKey.Public()
    publicKeyECDSA, _ := publicKey.(*ecdsa.PublicKey)
    address := crypto.PubkeyToAddress(*publicKeyECDSA).Hex()
    x509EncodedPri, _ := x509.MarshalECPrivateKey(privKey)
    block := pem.Block{
        Type:    "ECDSA Private Key",
        Headers: nil,
        Bytes:   x509EncodedPri,
    }
    file, err := os.Create("eccPrivate.pem")
    if err != nil {
        log.Fatal(err)
    }
    defer file.Close()
    pem.Encode(file, &block)
    return address
}

I found it empty:

$ cat  eccPrivate.pem
-----BEGIN ECDSA Private Key-----
-----END ECDSA Private Key-----

I know I should use ecdsa.GenerateKey(elliptic.P256(), rand.Reader) to generate the private key, but I end up with a different address than crypto.GenerateKey().
If anyone can tell me where I am going wrong, it would be greatly appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文