github.com/LagrangeDev/LagrangeGo@v0.0.0-20240512064304-ad4a85e10cb4/utils/crypto/ecdh/impl.go (about)

     1  package ecdh
     2  
     3  import (
     4  	"crypto/ecdh"
     5  	"crypto/rand"
     6  )
     7  
     8  type Exchanger interface {
     9  	PublicKey() []byte
    10  	SharedKey() []byte
    11  	Exange(remote []byte) ([]byte, error)
    12  }
    13  
    14  /*
    15  
    16  type s192exchanger struct {
    17  	provider    *provider
    18  	publicKey   []byte
    19  	sharedKey   []byte
    20  	compressKey bool
    21  }
    22  
    23  func (e *s192exchanger) PublicKey() []byte {
    24  	return e.publicKey
    25  }
    26  
    27  func (e *s192exchanger) SharedKey() []byte {
    28  	return e.sharedKey
    29  }
    30  
    31  func (e *s192exchanger) Exange(newKey []byte) ([]byte, error) {
    32  	return e.provider.keyExchange(newKey, e.compressKey)
    33  }
    34  
    35  func news192exchanger() *s192exchanger {
    36  	p, err := newProvider(newS192Curve())
    37  	if err != nil {
    38  		panic(err)
    39  	}
    40  	shk, err := p.keyExchange(ecdhS192PublicBytes, true)
    41  	if err != nil {
    42  		panic(err)
    43  	}
    44  	return &s192exchanger{
    45  		provider:    p,
    46  		publicKey:   p.packPublic(true),
    47  		sharedKey:   shk,
    48  		compressKey: true,
    49  	}
    50  }
    51  
    52  */
    53  
    54  type p256exchanger struct {
    55  	privateKey *ecdh.PrivateKey
    56  	shareKey   []byte
    57  }
    58  
    59  func (e *p256exchanger) PublicKey() []byte {
    60  	return e.privateKey.PublicKey().Bytes()
    61  }
    62  
    63  func (e *p256exchanger) SharedKey() []byte {
    64  	return e.shareKey
    65  }
    66  
    67  func (e *p256exchanger) Exange(remote []byte) ([]byte, error) {
    68  	rk, err := e.privateKey.Curve().NewPublicKey(remote)
    69  	if err != nil {
    70  		return nil, err
    71  	}
    72  	return e.privateKey.ECDH(rk)
    73  }
    74  
    75  func newp256exchanger() *p256exchanger {
    76  	p256 := ecdh.P256()
    77  	privateKey, err := p256.GenerateKey(rand.Reader)
    78  	if err != nil {
    79  		panic(err)
    80  	}
    81  	pk, err := p256.NewPublicKey(ecdhP256PublicBytes)
    82  	if err != nil {
    83  		panic(err)
    84  	}
    85  	shk, err := privateKey.ECDH(pk)
    86  	if err != nil {
    87  		panic(err)
    88  	}
    89  	return &p256exchanger{
    90  		privateKey: privateKey,
    91  		shareKey:   shk,
    92  	}
    93  }