crypto: hide BitCurve behind interface again

This commit is contained in:
Marius van der Wijden 2024-03-15 11:57:18 +01:00
parent 29a7673986
commit 16d89e0d7b
3 changed files with 16 additions and 15 deletions

View file

@ -40,6 +40,8 @@ import (
"hash" "hash"
"io" "io"
"math/big" "math/big"
"github.com/ethereum/go-ethereum/crypto"
) )
var ( var (
@ -255,11 +257,7 @@ func Encrypt(rand io.Reader, pub *PublicKey, m, s1, s2 []byte) (ct []byte, err e
d := messageTag(params.Hash, Km, em, s2) d := messageTag(params.Hash, Km, em, s2)
type marshaller interface { if curve, ok := pub.Curve.(crypto.BetterCurve); ok {
Marshal(x, y *big.Int) []byte
}
if curve, ok := pub.Curve.(marshaller); ok {
Rb := curve.Marshal(R.PublicKey.X, R.PublicKey.Y) Rb := curve.Marshal(R.PublicKey.X, R.PublicKey.Y)
ct = make([]byte, len(Rb)+len(em)+len(d)) ct = make([]byte, len(Rb)+len(em)+len(d))
copy(ct, Rb) copy(ct, Rb)
@ -305,10 +303,7 @@ func (prv *PrivateKey) Decrypt(c, s1, s2 []byte) (m []byte, err error) {
R := new(PublicKey) R := new(PublicKey)
R.Curve = prv.PublicKey.Curve R.Curve = prv.PublicKey.Curve
type unmarshaler interface { if curve, ok := R.Curve.(crypto.BetterCurve); ok {
Unmarshal([]byte) (x, y *big.Int)
}
if curve, ok := R.Curve.(unmarshaler); ok {
R.X, R.Y = curve.Unmarshal(c[:rLen]) R.X, R.Y = curve.Unmarshal(c[:rLen])
if R.X == nil { if R.X == nil {
return nil, ErrInvalidPublicKey return nil, ErrInvalidPublicKey

View file

@ -21,8 +21,10 @@ package crypto
import ( import (
"crypto/ecdsa" "crypto/ecdsa"
"crypto/elliptic"
"errors" "errors"
"fmt" "fmt"
"math/big"
"github.com/ethereum/go-ethereum/common/math" "github.com/ethereum/go-ethereum/common/math"
"github.com/ethereum/go-ethereum/crypto/secp256k1" "github.com/ethereum/go-ethereum/crypto/secp256k1"
@ -80,7 +82,15 @@ func CompressPubkey(pubkey *ecdsa.PublicKey) []byte {
return secp256k1.CompressPubkey(pubkey.X, pubkey.Y) return secp256k1.CompressPubkey(pubkey.X, pubkey.Y)
} }
// BetterCurve is an interface that combines both a curve
// and (un)-marshalling functions to and from that curve.
type BetterCurve interface {
elliptic.Curve
Marshal(x, y *big.Int) []byte
Unmarshal(data []byte) (x, y *big.Int)
}
// S256 returns an instance of the secp256k1 curve. // S256 returns an instance of the secp256k1 curve.
func S256() *secp256k1.BitCurve { func S256() BetterCurve {
return secp256k1.S256() return secp256k1.S256()
} }

View file

@ -29,7 +29,6 @@ import (
"fmt" "fmt"
"hash" "hash"
"io" "io"
"math/big"
mrand "math/rand" mrand "math/rand"
"net" "net"
"time" "time"
@ -664,10 +663,7 @@ func exportPubkey(pub *ecies.PublicKey) []byte {
if pub == nil { if pub == nil {
panic("nil pubkey") panic("nil pubkey")
} }
type marshaller interface { if curve, ok := pub.Curve.(crypto.BetterCurve); ok {
Marshal(x, y *big.Int) []byte
}
if curve, ok := pub.Curve.(marshaller); ok {
return curve.Marshal(pub.X, pub.Y)[1:] return curve.Marshal(pub.X, pub.Y)[1:]
} }
return []byte{} return []byte{}