I know that ECDH private key is a superset of public key. The task is to extract private key ecdh.
Here is the way how to generate PublicKey:
import (
"crypto/ecdh"
"crypto/rand"
"crypto/ecdsa"
"crypto/x509"
"encoding/base64"
"encoding/pem"
"fmt"
)
func main() {
alicePrivateKey, err := ecdh.P256().GenerateKey(rand.Reader)
alicePublicKey, err := MarshalECDHPublicKey(alicePrivateKey.PublicKey())
if err != nil {
fmt.Errorf("failed to marshal public key into PKIX format")
}
fmt.Printf("alicePubK => %s\n", alicePublicKey)
clientECDSAPubKey, err := UnmarshalECDSAPublicKey(alicePublicKey)
if err != nil {
panic(err)
}
println(clientECDSAPubKey)
println("no error")
}
func MarshalECDHPublicKey(pk *ecdh.PublicKey) (string, error) {
ecdhSKBytes, err := x509.MarshalPKIXPublicKey(pk)
if err != nil {
return "", fmt.Errorf("failed to marshal public key into PKIX format")
}
ecdhSKPEMBlock := pem.EncodeToMemory(
&pem.Block{
Type: "PUBLIC KEY",
Bytes: ecdhSKBytes,
},
)
return base64.StdEncoding.EncodeToString(ecdhSKPEMBlock), nil
}
I am assuming you want to extract
ecdh
private key inpem
format just like you did with the public key. Extracting private key from the public key isn't possible (computationally not feasible). I've implemented theUnmarshalECDSAPublicKey
function for you (better renamed asMarshalECDHPrivateKey
)As others pointed in the comments about
MarshalECDHPublicKey
function, you don't need to encode again withbase64.StdEncoding.EncodeToString(ecdhSKPEMBlock)
aspem.EncodeToMemory
does the same, you can just convert that to string.