aboutsummaryrefslogtreecommitdiffstats
path: root/vendor/github.com/wsddn/go-ecdh/curve25519.go
blob: 6426cbf8a25e5bf26d43cde820720eacf84efc0d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package ecdh

import (
    "crypto"
    "io"

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

type curve25519ECDH struct {
    ECDH
}

// NewCurve25519ECDH creates a new ECDH instance that uses djb's curve25519
// elliptical curve.
func NewCurve25519ECDH() ECDH {
    return &curve25519ECDH{}
}

func (e *curve25519ECDH) GenerateKey(rand io.Reader) (crypto.PrivateKey, crypto.PublicKey, error) {
    var pub, priv [32]byte
    var err error

    _, err = io.ReadFull(rand, priv[:])
    if err != nil {
        return nil, nil, err
    }

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

    curve25519.ScalarBaseMult(&pub, &priv)

    return &priv, &pub, nil
}

func (e *curve25519ECDH) Marshal(p crypto.PublicKey) []byte {
    pub := p.(*[32]byte)
    return pub[:]
}

func (e *curve25519ECDH) Unmarshal(data []byte) (crypto.PublicKey, bool) {
    var pub [32]byte
    if len(data) != 32 {
        return nil, false
    }

    copy(pub[:], data)
    return &pub, true
}

func (e *curve25519ECDH) GenerateSharedSecret(privKey crypto.PrivateKey, pubKey crypto.PublicKey) ([]byte, error) {
    var priv, pub, secret *[32]byte

    priv = privKey.(*[32]byte)
    pub = pubKey.(*[32]byte)
    secret = new([32]byte)

    curve25519.ScalarMult(secret, priv, pub)
    return secret[:], nil
}