简体   繁体   中英

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.

ie given eg 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

After reading the answer by Andrew W. Phillips and a little help from https://github.com/bitherhq/go-bither/tree/release/1.7/crypto

package main

import (
    "crypto/ecdsa"
    "crypto/elliptic"
    "crypto/rand"
    "fmt"
    "log"
    "math/big"
)

func PubBytes(pub *ecdsa.PublicKey) []byte {
    if pub == nil || pub.X == nil || pub.Y == nil {
        return nil
    }
    return elliptic.Marshal(elliptic.P256(), pub.X, pub.Y)
}

func toECDSAFromHex(hexString string) (*ecdsa.PrivateKey, error) {
    pk := new(ecdsa.PrivateKey)
    pk.D, _ = new(big.Int).SetString(hexString, 16)
    pk.PublicKey.Curve = elliptic.P256()
    pk.PublicKey.X, pk.PublicKey.Y = pk.PublicKey.Curve.ScalarBaseMult(pk.D.Bytes())
    return pk, nil
}

func main() {
    pHex := "E83385AF76B2B1997326B567461FB73DD9C27EAB9E1E86D26779F4650C5F2B75"
    pk, err := toECDSAFromHex(pHex)
        if err != nil {
        log.Fatal(err.Error())
    }
    fmt.Printf("Generated Public Key: %x\n", PubBytes(&pk.PublicKey))

    hash := []byte("Hello Gopher!")

    fmt.Printf("\nSigning...\n\n")
    r, s, err := ecdsa.Sign(rand.Reader, pk, hash)
    if err != nil {
        log.Fatal(err.Error())
    }
    fmt.Printf("\nVerifying..\n\n")
    if ecdsa.Verify(&pk.PublicKey, hash, r, s) {
        fmt.Println("Success!!")
    } else {
        fmt.Println("Failure!!")
    }
}
// Output
// Generated Public Key: 04265a5015c0cfd960e5a41f35e0a87874c1d8a28289d0d6ef6ac521ad49c3d80a8a7019ceef189819f066a947ad5726db1a4fe70a3208954c46b0e60f2bf7809c
// 
// Signing...
// 
// 
// Verifying..
// 
// Success!!

======== ORIGINAL ANSWER ===========

Dunno much of crypto but crypto/elliptic has a Marshal function

So once you have a * PrivateKey maybe the below will work

import (
  "crypto/elliptic"
  "crypto/ecdsa"
)
var privKey *ecdsa.PrivateKey
func main() {
  // some init to privKey
  pk := privKey.PublicKey()
  keybuf := elliptic.Marshal(pk.Curve, pk.X, pk.Y)
  log.Printf("Key: %s\n", string(keybuf))
}

I'm shooting completely in the dark with this. Hope it helps

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())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM