如何在Go中转换ECDSA私钥的数据类型

huangapple go评论82阅读模式
英文:

How to convert data type ECDSA private key in Go

问题

我正在使用ecdsa.GenerateKey方法在Go语言中生成私钥对。我想通过套接字编程发送我的私钥(priva),并且可以从其他程序中读取另一个私钥(privb)。

priva, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)

_, err = connection.Write([]byte(priva))
buffer := make([]byte, 1024)
mLen, err := connection.Read(buffer)
if err != nil {
fmt.Println("Error reading:", err.Error())
}
privb := buffer[:mLen]

这是我用于发送和接收数据的代码,但是我无法发送我的私钥(priva),因为它的类型无法更改。如何修复这个问题,或者是否有推荐的方法来发送/接收数据?

英文:

I am using the ecdsa.GenerateKey method to generate a private key pair in Go. I would like to send my private key(priva) with socket programming and can read other private key(privb) from other program.

priva, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)

_, err = connection.Write([]byte(priva))
buffer := make([]byte, 1024)
mLen, err := connection.Read(buffer)
if err != nil {
	fmt.Println("Error reading:", err.Error())
}
privb := buffer[:mLen]

There is my code to send data and read data to/from other program, but i can't send my private key(priva) because it can't change the types. How to fixed, or is there a recommended way to send/read the data ?

答案1

得分: 1

*ecdsa.PrivateKey 不能直接通过网络发送。它必须首先被编组为 []byte

您可以使用 x509.MarshalECPrivateKey 将其编组为 DER 格式,然后使用 x509.ParseECPrivateKey 进行解组。

例如:

package main

import (
    "crypto/ecdsa"
    "crypto/elliptic"
    "crypto/rand"
    "crypto/x509"
    "fmt"
)

func main() {
    priv, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)

    derBuf, _ := x509.MarshalECPrivateKey(priv)

    // 将 []byte 传输到新位置。

    privCopy, _ := x509.ParseECPrivateKey(derBuf)

    fmt.Println(priv.Equal(privCopy))
    /// 输出: true
}

注意:此示例未提供有关私钥的任何额外安全性。您可能希望确保传输/协议处理符合您的安全需求。

英文:

The *ecdsa.PrivateKey cannot be directly sent over the network. It must be marshalled into a []byte first.

You can use x509.MarshalECPrivateKey to marshal into DER format, and x509.ParseECPrivateKey to unmarshal.

For example:

package main

import (
    "crypto/ecdsa"
    "crypto/elliptic"
    "crypto/rand"
    "crypto/x509"
    "fmt"
)

func main() {
    priv, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)

    derBuf, _ := x509.MarshalECPrivateKey(priv)

    // Transfer []byte to new location.

    privCopy, _ := x509.ParseECPrivateKey(derBuf)

    fmt.Println(priv.Equal(privCopy))
    /// Output: true
}

Note: this example doesn't provide any additional security around the private key. You may want to ensure the transfer/protocol handling is appropriate for your security needs.

huangapple
  • 本文由 发表于 2022年4月14日 22:30:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/71873283.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定