Search code examples
goecdsa

How to generate the ECDSA public key from its private key?


The following site is frequently referenced and, I assume, accurate:

https://gobittest.appspot.com/Address

I'm trying to repro these steps in Golang but failing at the first step :-(

Is someone able to provide me with a Golang snippet that, given a ECDSA private key, returns the public key? I think I may specifically mean the private key exponent and public key exponent per the above site's examples.

i.e. given e.g. a randomly-generated (hex-encoded) private key (exponent?) E83385AF76B2B1997326B567461FB73DD9C27EAB9E1E86D26779F4650C5F2B75 returns the public key 04369D83469A66920F31E4CF3BD92CB0BC20C6E88CE010DFA43E5F08BC49D11DA87970D4703B3ADBC9A140B4AD03A0797A6DE2D377C80C369FE76A0F45A7A39D3F

I've found many (relevant) results:

https://crypto.stackexchange.com/questions/5756/how-to-generate-a-public-key-from-a-private-ecdsa-key

But none that includes a definitive example.

Go's crypto/ecdsa module allows keys to generated and includes a Public function on the type but this returns the PublicKey property.

Alternative ways that start from a private key appear to require going through a PEM-encoded (including a DER-encoded ASN) form of the key which feels circuitous (and I would need to construct).

Update:

See the answers below: andrew-w-phillips@ and kelsnare@ provided the (same|correct) solution. Thanks to both of them!

For posterity, Bitcoin (and Ethereum) use an elliptic curve defined by secp256k1. The following code from andrew-w-phillips@ and kelsnare@ using Ethereum's implementation of this curve, works:

import (
    "crypto/ecdsa"
    "crypto/elliptic"
    "fmt"
    "math/big"
    "strings"

    "github.com/ethereum/go-ethereum/crypto/secp256k1"
)
func Public(privateKey string) (publicKey string) {
    var e ecdsa.PrivateKey
    e.D, _ = new(big.Int).SetString(privateKey, 16)
    e.PublicKey.Curve = secp256k1.S256()
    e.PublicKey.X, e.PublicKey.Y = e.PublicKey.Curve.ScalarBaseMult(e.D.Bytes())
    return fmt.Sprintf("%x", elliptic.Marshal(secp256k1.S256(), e.X, e.Y))
}
func main() {
    privateKey := "E83385AF76B2B1997326B567461FB73DD9C27EAB9E1E86D26779F4650C5F2B75"
    log.Println(strings.ToUpper(Public(privateKey)))
}

yields:

04369D83469A66920F31E4CF3BD92CB0BC20C6E88CE010DFA43E5F08BC49D11DA87970D4703B3ADBC9A140B4AD03A0797A6DE2D377C80C369FE76A0F45A7A39D3F

Solution

  • I haven't got that low-level but maybe something like this:

    var pri ecdsa.PrivateKey
    pri.D, _ = new(big.Int).SetString("E83385AF76B2B1997326B567461FB73DD9C27EAB9E1E86D26779F4650C5F2B75",16)
    pri.PublicKey.Curve = elliptic.P256()
    pri.PublicKey.X, pri.PublicKey.Y = pri.PublicKey.Curve.ScalarBaseMult(pri.D.Bytes())