| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
package ecdh |
| 5 |
|
| 6 |
import ( |
| 7 |
"crypto/elliptic" |
| 8 |
cryptorand "crypto/rand" |
| 9 |
"errors" |
| 10 |
"io" |
| 11 |
"math/big" |
| 12 |
) |
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
func unmarshal(curve elliptic.Curve, data []byte) (x, y *big.Int) { |
| 17 |
byteLen := (curve.Params().BitSize + 7) >> 3 |
| 18 |
if len(data) != 1+2*byteLen { |
| 19 |
return |
| 20 |
} |
| 21 |
if data[0] != 4 { |
| 22 |
return |
| 23 |
} |
| 24 |
x = new(big.Int).SetBytes(data[1 : 1+byteLen]) |
| 25 |
y = new(big.Int).SetBytes(data[1+byteLen:]) |
| 26 |
return |
| 27 |
} |
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
func GenericCurve(c elliptic.Curve) KeyExchange { |
| 32 |
if c == nil { |
| 33 |
panic("ecdh: curve is nil") |
| 34 |
} |
| 35 |
return genericCurve{curve: c} |
| 36 |
} |
| 37 |
|
| 38 |
type genericCurve struct { |
| 39 |
curve elliptic.Curve |
| 40 |
} |
| 41 |
|
| 42 |
func (g genericCurve) GenerateKey(rand io.Reader) (private PrivateKey, public PublicKey, err error) { |
| 43 |
if rand == nil { |
| 44 |
rand = cryptorand.Reader |
| 45 |
} |
| 46 |
private, x, y, err := elliptic.GenerateKey(g.curve, rand) |
| 47 |
if err != nil { |
| 48 |
private = nil |
| 49 |
return |
| 50 |
} |
| 51 |
public = elliptic.Marshal(g.curve, x, y) |
| 52 |
return |
| 53 |
} |
| 54 |
|
| 55 |
func (g genericCurve) PublicKey(private PrivateKey) (public PublicKey) { |
| 56 |
N := g.curve.Params().N |
| 57 |
|
| 58 |
if new(big.Int).SetBytes(private).Cmp(N) >= 0 { |
| 59 |
panic("ecdh: private key cannot used with given curve") |
| 60 |
} |
| 61 |
|
| 62 |
x, y := g.curve.ScalarBaseMult(private) |
| 63 |
public = elliptic.Marshal(g.curve, x, y) |
| 64 |
return |
| 65 |
} |
| 66 |
|
| 67 |
func (g genericCurve) Check(peersPublic PublicKey) (err error) { |
| 68 |
x, y := unmarshal(g.curve, peersPublic) |
| 69 |
if !g.curve.IsOnCurve(x, y) { |
| 70 |
err = errors.New("peer's public key is not on curve") |
| 71 |
} |
| 72 |
return |
| 73 |
} |
| 74 |
|
| 75 |
func (g genericCurve) ComputeSecret(private PrivateKey, peersPublic PublicKey) (secret []byte) { |
| 76 |
x, y := unmarshal(g.curve, peersPublic) |
| 77 |
|
| 78 |
sX, _ := g.curve.ScalarMult(x, y, private) |
| 79 |
|
| 80 |
secret = sX.Bytes() |
| 81 |
return |
| 82 |
} |