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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With