-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcurve25519.go
70 lines (52 loc) · 1.27 KB
/
curve25519.go
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
63
64
65
66
67
68
69
70
package x3dh
import (
"golang.org/x/crypto/curve25519"
"io"
)
type Curve25519 struct {
randSource io.Reader
}
func NewCurve25519(randSource io.Reader) Curve25519 {
return Curve25519{
randSource: randSource,
}
}
// calculate a diffie hellman key exchange
// with given key pair
func (c *Curve25519) KeyExchange(dh DHPair) [32]byte {
var (
sharedSecret [32]byte
priv [32]byte = dh.PrivateKey
pub [32]byte = dh.PublicKey
)
curve25519.ScalarMult(&sharedSecret, &priv, &pub)
return sharedSecret
}
// prefix for curve25519 is a byte array
// of length 32 filled with 0xFF
func (c *Curve25519) PreFix() []byte {
return []byte{
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
}
}
// create a new curve25519 key pair from a random source
func (c *Curve25519) GenerateKeyPair() (KeyPair, error) {
var priv [32]byte
// fill private key
_, err := c.randSource.Read(priv[:])
if err != nil {
return KeyPair{}, err
}
priv[0] &= 248
priv[31] &= 127
priv[31] |= 64
var pubKey [32]byte
curve25519.ScalarBaseMult(&pubKey, &priv)
return KeyPair{
PrivateKey: priv,
PublicKey: pubKey,
}, nil
}