This is my old code.
PKCS8GCSprvkey, _ := x509.ParsePKCS8PrivateKey([]byte(privateKeyFile))
GCSprvkey, _ := PKCS8GCSprvkey.(*ecdsa.PrivateKey)
GCSpubkey, _ := os.ReadFile("public_key.txt")
Clientkeybuffer := ciphertext[0:len(GCSpubkey)]
parseClientpub, _ := x509.ParsePKIXPublicKey(Clientkeybuffer)
Clientpubkey, _ := parseClientpub.(*ecdsa.PublicKey)
GCSsecret, _ := GCSprvkey.PublicKey.Curve.ScalarMult(Clientpubkey.X, Clientpubkey.Y, GCSprvkey.D.Bytes())
GCSsecretstring := GCSsecret.Text(16)
But the method
GCSprvkey.PublicKey.Curve.ScalarMult(Clientpubkey.X, Clientpubkey.Y, GCSprvkey.D.Bytes())
.ScalarMult() is deprecated and it says "this is a low-Level unsafe API. For ECDH, use the crypto/ecdh package. Most of uses of ScalarMult can be replaced by a call to the ECDH methods of NIST curves in crypto/ECDH." . I'm not sure how to use the crypto/ecdh of golang to achieve the same thing. I tried to load my public key file into an *ecdh.PublicKey but I keep getting invalid public key error.
I've tried to convert the ecdsa.PublicKey to ecdh.PublicKey but it failed.
The short answer is that in the
ecdsapackage, there are methods which convert each key type to their counterparts in the theecdhpackage. This extra conversion step is mentioned in theecdhdocumentation.From
ecdh.PrivateKey:From
ecdh.PublicKey:Taking your code example, here's how you'd parse the keys using
x509, convert them toecdhkeys, and then compute a shared secret.Output:
Go Playground