-
Notifications
You must be signed in to change notification settings - Fork 0
/
kx.go
executable file
·49 lines (40 loc) · 1.3 KB
/
kx.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
// Package x25519 implements ECDHE over curve25519.
package x25519
import (
"io"
"golang.org/x/crypto/curve25519"
)
type Public [32]byte
type Scalar [32]byte
// KX is the client-generated public and secret portions of a key exchange.
type KX struct {
Public
Scalar // secret
}
// New begins a new key exchange by generating a public and secret value.
// Public portions must be exchanged between parties to derive a shared secret
// key.
func New(rand io.Reader) (*KX, error) {
kx := new(KX)
_, err := io.ReadFull(rand, kx.Scalar[:])
if err != nil {
return nil, err
}
// https://cr.yp.to/ecdh.html; Computing secret keys.
kx.Scalar[0] &= 248
kx.Scalar[31] &= 127
kx.Scalar[31] |= 64
curve25519.ScalarBaseMult((*[32]byte)(&kx.Public), (*[32]byte)(&kx.Scalar))
return kx, nil
}
// SharedKey computes a shared key with the other party from our secret value
// and their public value. The result should be securely hashed before usage.
func (kx *KX) SharedKey(theirPublic *Public) []byte {
var sharedKey [32]byte
curve25519.ScalarMult(&sharedKey, (*[32]byte)(&kx.Scalar), (*[32]byte)(theirPublic))
return sharedKey[:]
}
// ValidScalar returns whether a secret X25519 scalar was properly constructed.
func ValidScalar(s *Scalar) bool {
return s[0]&248 == s[0] && s[31]&127 == s[31] && s[31]|64 == s[31]
}