diff --git a/internal/crypto/crypto.go b/internal/crypto/crypto.go index 48cb1d03..a72d8418 100644 --- a/internal/crypto/crypto.go +++ b/internal/crypto/crypto.go @@ -1,9 +1,6 @@ package crypto import ( - "crypto/elliptic" - "crypto/md5" - "crypto/rand" "encoding/hex" "encoding/json" "net/http" @@ -26,21 +23,11 @@ func NewECDH() *ECDH { e := &ECDH{ SvrPublicKeyVer: 1, } - e.generateKey(serverPublicKey) + key, _ := hex.DecodeString(serverPublicKey) + e.init(key) return e } -func (e *ECDH) generateKey(sPubKey string) { - pub, _ := hex.DecodeString(sPubKey) - p256 := elliptic.P256() - key, sx, sy, _ := elliptic.GenerateKey(p256, rand.Reader) - tx, ty := elliptic.Unmarshal(p256, pub) - x, _ := p256.ScalarMult(tx, ty, key) - hash := md5.Sum(x.Bytes()[:16]) - e.ShareKey = hash[:] - e.PublicKey = elliptic.Marshal(p256, sx, sy) -} - type pubKeyResp struct { Meta struct { PubKeyVer uint16 `json:"KeyVer"` @@ -61,5 +48,6 @@ func (e *ECDH) FetchPubKey(uin int64) { return } e.SvrPublicKeyVer = pubKey.Meta.PubKeyVer - e.generateKey(pubKey.Meta.PubKey) // todo check key sign + key, _ := hex.DecodeString(pubKey.Meta.PubKey) + e.init(key) // todo check key sign } diff --git a/internal/crypto/ecdh_119.go b/internal/crypto/ecdh_119.go new file mode 100644 index 00000000..fbbde39f --- /dev/null +++ b/internal/crypto/ecdh_119.go @@ -0,0 +1,19 @@ +//go:build !go1.20 + +package crypto + +import ( + "crypto/elliptic" + "crypto/md5" + "crypto/rand" +) + +func (e *ECDH) init(svrPubKey []byte) { + p256 := elliptic.P256() + key, sx, sy, _ := elliptic.GenerateKey(p256, rand.Reader) + tx, ty := elliptic.Unmarshal(p256, svrPubKey) + x, _ := p256.ScalarMult(tx, ty, key) + hash := md5.Sum(x.Bytes()[:16]) + e.ShareKey = hash[:] + e.PublicKey = elliptic.Marshal(p256, sx, sy) +} diff --git a/internal/crypto/ecdh_120.go b/internal/crypto/ecdh_120.go new file mode 100644 index 00000000..12f8fa4e --- /dev/null +++ b/internal/crypto/ecdh_120.go @@ -0,0 +1,21 @@ +//go:build go1.20 + +package crypto + +import ( + "crypto/ecdh" + "crypto/md5" + "crypto/rand" +) + +func (e *ECDH) init(svrPubKey []byte) { + p256 := ecdh.P256() + local, _ := p256.GenerateKey(rand.Reader) + remote, _ := p256.NewPublicKey(svrPubKey) + share, _ := p256.ECDH(local, remote) + + hash := md5.New() + hash.Write(share[:16]) + e.ShareKey = hash.Sum(nil) + e.PublicKey = local.PublicKey().Bytes() +}