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:
parent
e657427abd
commit
8aa1683866
@ -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
|
||||
}
|
||||
|
19
internal/crypto/ecdh_119.go
Normal file
19
internal/crypto/ecdh_119.go
Normal 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)
|
||||
}
|
21
internal/crypto/ecdh_120.go
Normal file
21
internal/crypto/ecdh_120.go
Normal 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()
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user