| 1 |
package noiseutil |
| 2 |
|
| 3 |
import ( |
| 4 |
"crypto/ecdh" |
| 5 |
"crypto/rand" |
| 6 |
"fmt" |
| 7 |
"io" |
| 8 |
|
| 9 |
"github.com/flynn/noise" |
| 10 |
) |
| 11 |
|
| 12 |
// DHP256 is the NIST P-256 ECDH function |
| 13 |
var DHP256 noise.DHFunc = newNISTCurve("P256", ecdh.P256(), 32) |
| 14 |
|
| 15 |
type nistCurve struct { |
| 16 |
name string |
| 17 |
curve ecdh.Curve |
| 18 |
dhLen int |
| 19 |
pubLen int |
| 20 |
} |
| 21 |
|
| 22 |
func newNISTCurve(name string, curve ecdh.Curve, byteLen int) nistCurve { |
| 23 |
return nistCurve{ |
| 24 |
name: name, |
| 25 |
curve: curve, |
| 26 |
dhLen: byteLen, |
| 27 |
// Standard uncompressed format, type (1 byte) plus both coordinates |
| 28 |
pubLen: 1 + 2*byteLen, |
| 29 |
} |
| 30 |
} |
| 31 |
|
| 32 |
func (c nistCurve) GenerateKeypair(rng io.Reader) (noise.DHKey, error) { |
| 33 |
if rng == nil { |
| 34 |
rng = rand.Reader |
| 35 |
} |
| 36 |
privkey, err := c.curve.GenerateKey(rng) |
| 37 |
if err != nil { |
| 38 |
return noise.DHKey{}, err |
| 39 |
} |
| 40 |
pubkey := privkey.PublicKey() |
| 41 |
return noise.DHKey{Private: privkey.Bytes(), Public: pubkey.Bytes()}, nil |
| 42 |
} |
| 43 |
|
| 44 |
func (c nistCurve) DH(privkey, pubkey []byte) ([]byte, error) { |
| 45 |
ecdhPubKey, err := c.curve.NewPublicKey(pubkey) |
| 46 |
if err != nil { |
| 47 |
return nil, fmt.Errorf("unable to unmarshal pubkey: %w", err) |
| 48 |
} |
| 49 |
ecdhPrivKey, err := c.curve.NewPrivateKey(privkey) |
| 50 |
if err != nil { |
| 51 |
return nil, fmt.Errorf("unable to unmarshal private key: %w", err) |
| 52 |
} |
| 53 |
|
| 54 |
return ecdhPrivKey.ECDH(ecdhPubKey) |
| 55 |
} |
| 56 |
|
| 57 |
func (c nistCurve) DHLen() int { |
| 58 |
// NOTE: Noise Protocol specifies "DHLen" to represent two things: |
| 59 |
// - The size of the public key |
| 60 |
// - The return size of the DH() function |
| 61 |
// But for standard NIST ECDH, the sizes of these are different. |
| 62 |
// Luckily, the flynn/noise library actually only uses this DHLen() |
| 63 |
// value to represent the public key size, so that is what we are |
| 64 |
// returning here. The length of the DH() return bytes are unaffected by |
| 65 |
// this value here. |
| 66 |
return c.pubLen |
| 67 |
} |
| 68 |
func (c nistCurve) DHName() string { return c.name } |