Skip to content

Commit 52a46e6

Browse files
author
Gustav Simonsson
committed
Correct ECIES shared key length check
* Ensure the ECIES shared key is padded with zero bytes if it's smaller than the requested key length. * Split the ECIES shared key error into two; one for when the generated key is too big for the params and one for when it's nil (point of infinity returned by the curve scalar multiplication).
1 parent d899334 commit 52a46e6

1 file changed

Lines changed: 17 additions & 12 deletions

File tree

‎ecies.go‎

Lines changed: 17 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -13,11 +13,12 @@ import (
1313
)
1414

1515
var (
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.
9192
func (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

105110
var (

0 commit comments

Comments
 (0)