1
0
mirror of https://github.com/Mrs4s/MiraiGo.git synced 2025-05-04 11:07:40 +08:00

internal/crypto: use crypto/ecdh in go1.20

This commit is contained in:
wdvxdr 2022-09-25 00:09:25 +08:00
parent e657427abd
commit 8aa1683866
3 changed files with 44 additions and 16 deletions

View File

@ -1,9 +1,6 @@
package crypto package crypto
import ( import (
"crypto/elliptic"
"crypto/md5"
"crypto/rand"
"encoding/hex" "encoding/hex"
"encoding/json" "encoding/json"
"net/http" "net/http"
@ -26,21 +23,11 @@ func NewECDH() *ECDH {
e := &ECDH{ e := &ECDH{
SvrPublicKeyVer: 1, SvrPublicKeyVer: 1,
} }
e.generateKey(serverPublicKey) key, _ := hex.DecodeString(serverPublicKey)
e.init(key)
return e 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 { type pubKeyResp struct {
Meta struct { Meta struct {
PubKeyVer uint16 `json:"KeyVer"` PubKeyVer uint16 `json:"KeyVer"`
@ -61,5 +48,6 @@ func (e *ECDH) FetchPubKey(uin int64) {
return return
} }
e.SvrPublicKeyVer = pubKey.Meta.PubKeyVer 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
} }

View File

@ -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)
}

View File

@ -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()
}