Skip to content
This repository was archived by the owner on Aug 2, 2021. It is now read-only.

Commit 04c1a81

Browse files
committed
Merge pull request #2 from Gustav-Simonsson/correct_ecies_shared_key_generation
Correct ECIES shared key length check
2 parents d899334 + 52a46e6 commit 04c1a81

File tree

1 file changed

+17
-12
lines changed

1 file changed

+17
-12
lines changed

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)