2025-03-09 15:52:33 -04:00
|
|
|
package keyexchange
|
2025-03-07 21:05:37 -05:00
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto/ecdh"
|
2025-03-09 15:52:33 -04:00
|
|
|
"crypto/hkdf"
|
2025-03-07 21:05:37 -05:00
|
|
|
"crypto/rand"
|
2025-03-09 15:52:33 -04:00
|
|
|
"crypto/sha256"
|
2025-03-07 21:05:37 -05:00
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
// DefaultDHCurve is the default elliptic curve used for signing.
|
|
|
|
DefaultDHCurve = ecdh.P384
|
|
|
|
)
|
|
|
|
|
|
|
|
// GenerateDHKey generates a new ECDH private key for key exchange.
|
|
|
|
func GenerateDHKey() (*ecdh.PrivateKey, error) {
|
|
|
|
return DefaultDHCurve().GenerateKey(rand.Reader)
|
|
|
|
}
|
|
|
|
|
|
|
|
// ComputeDHSecret computes the shared secret from the private key and the public key.
|
|
|
|
func ComputeDHSecret(priv *ecdh.PrivateKey, pub *ecdh.PublicKey) ([]byte, error) {
|
2025-03-09 15:52:33 -04:00
|
|
|
secret, err := priv.ECDH(pub)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
key, err := hkdf.Key(sha256.New, secret, nil, "", 32)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return key, nil
|
2025-03-07 21:05:37 -05:00
|
|
|
}
|
|
|
|
|
2025-03-09 17:09:21 -04:00
|
|
|
// ExportPublicKey exports the public key as a byte slice.
|
|
|
|
func ExportPublicKey(pub *ecdh.PublicKey) ([]byte, error) {
|
2025-03-07 21:05:37 -05:00
|
|
|
return pub.Bytes(), nil
|
|
|
|
}
|
|
|
|
|
2025-03-09 17:09:21 -04:00
|
|
|
// ImportPublicKey imports the public key from a byte slice.
|
|
|
|
func ImportPublicKey(data []byte) (*ecdh.PublicKey, error) {
|
2025-03-07 21:05:37 -05:00
|
|
|
return DefaultDHCurve().NewPublicKey(data)
|
|
|
|
}
|