-
Notifications
You must be signed in to change notification settings - Fork 22
/
elliptic.go
87 lines (73 loc) · 1.75 KB
/
elliptic.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package ecdh
import (
"crypto"
"crypto/elliptic"
"io"
"math/big"
)
type ellipticECDH struct {
ECDH
curve elliptic.Curve
}
type ellipticPublicKey struct {
elliptic.Curve
X, Y *big.Int
}
type ellipticPrivateKey struct {
D []byte
}
// NewEllipticECDH creates a new instance of ECDH with the given elliptic.Curve curve
// to use as the elliptical curve for elliptical curve diffie-hellman.
func NewEllipticECDH(curve elliptic.Curve) ECDH {
return &ellipticECDH{
curve: curve,
}
}
func (e *ellipticECDH) GenerateKey(rand io.Reader) (crypto.PrivateKey, crypto.PublicKey, error) {
var d []byte
var x, y *big.Int
var priv *ellipticPrivateKey
var pub *ellipticPublicKey
var err error
d, x, y, err = elliptic.GenerateKey(e.curve, rand)
if err != nil {
return nil, nil, err
}
priv = &ellipticPrivateKey{
D: d,
}
pub = &ellipticPublicKey{
Curve: e.curve,
X: x,
Y: y,
}
return priv, pub, nil
}
func (e *ellipticECDH) Marshal(p crypto.PublicKey) []byte {
pub := p.(*ellipticPublicKey)
return elliptic.Marshal(e.curve, pub.X, pub.Y)
}
func (e *ellipticECDH) Unmarshal(data []byte) (crypto.PublicKey, bool) {
var key *ellipticPublicKey
var x, y *big.Int
x, y = elliptic.Unmarshal(e.curve, data)
if x == nil || y == nil {
return key, false
}
key = &ellipticPublicKey{
Curve: e.curve,
X: x,
Y: y,
}
return key, true
}
// GenerateSharedSecret takes in a public key and a private key
// and generates a shared secret.
//
// RFC5903 Section 9 states we should only return x.
func (e *ellipticECDH) GenerateSharedSecret(privKey crypto.PrivateKey, pubKey crypto.PublicKey) ([]byte, error) {
priv := privKey.(*ellipticPrivateKey)
pub := pubKey.(*ellipticPublicKey)
x, _ := e.curve.ScalarMult(pub.X, pub.Y, priv.D)
return x.Bytes(), nil
}