Search code examples
godiffie-hellman

Why we need recovering public keys in this Diffie Hellman Key-exchange algorithm in Go


In this module documentation (just consider Alice's side for simplicity) the sample code is:

// Get a group. Use the default one would be enough.
g, _ := GetGroup(0)

// Generate a private key from the group.
// Use the default random number generator.
priv, _ := g.GeneratePrivateKey(nil)

// Get the public key from the private key.
pub := priv.Bytes()

// Send the public key to Bob.
Send("Bob", pub)

// Receive a slice of bytes from Bob, which contains Bob's public key
b := Recv("Bob")

// Recover Bob's public key
bobPubKey := NewPublicKey(b)

// Compute the key
k, _ := group.ComputeKey(bobPubKey, priv)

// Get the key in the form of []byte
key := k.Bytes()

Here are my questions:

1)

// Get the public key from the private key.
pub := priv.Bytes()

How private bytes are used as public key bytes? Is it just a bad naming of the method? (should be something like priv.GetPubBytes() assuming priv contains both private and public keys)

2)

// Receive a slice of bytes from Bob, which contains Bob's public key
b := Recv("Bob")

// Recover Bob's public key
bobPubKey := NewPublicKey(b)

If b contains Bob's public key (getting over a channel) then why we need to recover it? This recovery process converts what to what?


Solution

    1. yes, it is naming only. I agree with your remark : a better name would have been something like .GetPubBytes() or something that explicitly indicates that you get the bytes from the public key.

    2. again, this is just how the comment is worded, there is nothing to recover from the network.

    Note that, for public packages like this one (hosted on github), the godoc page has direct links to the code. For example :

    • if you scroll down to the doc entry for func NewPublicKey (this paragraph),
    • clicking on the function's name brings you to its implementation, on github -- in this specific case : you can see that the only action is creating a DHKey struct and assigning the bytes to its y field, which is the public part of the key.