Reputation: 49
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 ?
Upvotes: 3
Views: 2266
Reputation: 1354
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.
Upvotes: 2