influxdata / wirey

Manage local wireguard interfaces in a distributed system
Apache License 2.0
67 stars 6 forks source link

Implement key generation and interaction with netlink socket #1

Open fntlnz opened 6 years ago

fntlnz commented 6 years ago

Source here: https://github.com/WireGuard/WireGuard/blob/master/contrib/examples/embeddable-wg-library/wireguard.c

fntlnz commented 6 years ago

Reasoned on this and the best way to achieve this seems to do the following:

Updating the original title to reflect this.

fntlnz commented 6 years ago

Did a try with cgo in #13 had memory leaks problems on the heap

fntlnz commented 6 years ago

I'm working on this - dibs

spdowling commented 5 years ago

In case anybody is ever looking for some guidance on programmatically generating keys in go, I found the following a good starting point:

package keys

import (
    crand "crypto/rand"
    "encoding/base64"

    "golang.org/x/crypto/curve25519"
)

func generateKeys() (string, string, error) {
    var (
        privateKey string
        publicKey  string
        err        error
    )

    privateKey, err = generatePrivateKey()
    if err != nil {
        return privateKey, publicKey, err
    }

    publicKey, err = generatePublicKey(private)
    if err != nil {
        return privateKey, publicKey, err
    }

    return privateKey, publicKey, err
}

func generatePrivateKey() (string, error) {
    var (
        b          [32]byte
        privateKey string
        err        error
    )

    _, err = crand.Read(b[:])
    if err != nil {
        return privateKey, err
    }

    b[0] &= 248
    b[31] &= 127
    b[31] |= 64

    privateKey = base64.StdEncoding.EncodeToString(b[:])

    return privateKey, nil
}

func generatePublicKey(privateKeyEnc string) (string, error) {
    var (
        prb       [32]byte
        pub       [32]byte
        publicKey string
    )

    privateKeyDec, err := base64.StdEncoding.DecodeString(privateKeyEnc)
    if err != nil {
        return publicKey, err
    }
    copy(prb[:], privateKeyDec)
    curve25519.ScalarBaseMult(&pub, &prb)
    publicKey = base64.StdEncoding.EncodeToString(pub[:])

    return publicKey, nil
}