@@ -13,11 +13,12 @@ import (
1313)
1414
1515var (
16- ErrImport = fmt .Errorf ("ecies: failed to import key" )
17- ErrInvalidCurve = fmt .Errorf ("ecies: invalid elliptic curve" )
18- ErrInvalidParams = fmt .Errorf ("ecies: invalid ECIES parameters" )
19- ErrInvalidPublicKey = fmt .Errorf ("ecies: invalid public key" )
20- ErrSharedKeyTooBig = fmt .Errorf ("ecies: shared key is too big" )
16+ ErrImport = fmt .Errorf ("ecies: failed to import key" )
17+ ErrInvalidCurve = fmt .Errorf ("ecies: invalid elliptic curve" )
18+ ErrInvalidParams = fmt .Errorf ("ecies: invalid ECIES parameters" )
19+ ErrInvalidPublicKey = fmt .Errorf ("ecies: invalid public key" )
20+ ErrSharedKeyIsPointAtInfinity = fmt .Errorf ("ecies: shared key is point at infinity" )
21+ ErrSharedKeyTooBig = fmt .Errorf ("ecies: shared key params are too big" )
2122)
2223
2324// PublicKey is a representation of an elliptic curve public key.
@@ -90,16 +91,20 @@ func MaxSharedKeyLength(pub *PublicKey) int {
9091// ECDH key agreement method used to establish secret keys for encryption.
9192func (prv * PrivateKey ) GenerateShared (pub * PublicKey , skLen , macLen int ) (sk []byte , err error ) {
9293 if prv .PublicKey .Curve != pub .Curve {
93- err = ErrInvalidCurve
94- return
94+ return nil , ErrInvalidCurve
95+ }
96+ if skLen + macLen > MaxSharedKeyLength (pub ) {
97+ return nil , ErrSharedKeyTooBig
9598 }
9699 x , _ := pub .Curve .ScalarMult (pub .X , pub .Y , prv .D .Bytes ())
97- if x == nil || (x .BitLen ()+ 7 )/ 8 < (skLen + macLen ) {
98- err = ErrSharedKeyTooBig
99- return
100+ if x == nil {
101+ return nil , ErrSharedKeyIsPointAtInfinity
100102 }
101- sk = x .Bytes ()[:skLen + macLen ]
102- return
103+
104+ sk = make ([]byte , skLen + macLen )
105+ skBytes := x .Bytes ()
106+ copy (sk [len (sk )- len (skBytes ):], skBytes )
107+ return sk , nil
103108}
104109
105110var (
0 commit comments