Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate bytes array from PublicKey

I'm use crypto lib, ran into a problem: I need to convert the PublicKey type into byte[], as it can be done with a private key:

privkey.D.Bytes()

How can I solve this problem?

like image 805
Folleah Avatar asked Mar 06 '23 08:03

Folleah


1 Answers

ecdsa.PrivateKey is a struct:

type PrivateKey struct {
        PublicKey
        D *big.Int
}

So privkey.D.Bytes() returns you the bytes of the D big integer.

Similarly, ecdsa.PublicKey:

type PublicKey struct {
        elliptic.Curve
        X, Y *big.Int
}

You may do the same with pubkey.X and pubkey.Y fields. These will give you 2 separate byte slices. If you need to merge them into one, you need to come up with some kind of "format", e.g. encoding the length of the first slice (the result of pubkey.X.Bytes()) using 4 bytes, then the first slice, then the length (4 bytes again) of the 2nd slice, and the second slice itself.

Best would be to use the elliptic.Marshal() function for this:

func Marshal(curve Curve, x, y *big.Int) []byte

Marshal converts a point into the uncompressed form specified in section 4.3.6 of ANSI X9.62.

Example using it:

var pubkey *ecdsa.PublicKey = // ...

data := elliptic.Marshal(pubkey, pubkey.X, pubkey.Y)
like image 133
icza Avatar answered Mar 09 '23 06:03

icza