Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

crypto/ecies: correct IV and MAC #847

Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 15 additions & 18 deletions crypto/ecies/ecies.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package ecies

import (
"bytes"
"crypto/cipher"
"crypto/ecdsa"
"crypto/elliptic"
Expand Down Expand Up @@ -185,16 +186,17 @@ func symEncrypt(rand io.Reader, params *ECIESParams, key, m []byte) (ct []byte,
if err != nil {
return
}

iv, err := generateIV(params, rand)
if err != nil {
return
}
/*
In SEC 1 Version 2.0 section 3.8 the IV value is not specified in for XOR CTR.
It is specified, however, that it should not be transmitted as part of the ciphertext.
This means it cannot be random, as the other party would not know the value.
Therefore we set it to the zeroed value defined for AES in CTR mode.
*/
iv := bytes.Repeat([]byte{0}, 16)
ctr := cipher.NewCTR(c, iv)

ct = make([]byte, len(m)+params.BlockSize)
copy(ct, iv)
ctr.XORKeyStream(ct[params.BlockSize:], m)
ct = make([]byte, len(m))
ctr.XORKeyStream(ct, m)
return
}

Expand All @@ -206,10 +208,11 @@ func symDecrypt(rand io.Reader, params *ECIESParams, key, ct []byte) (m []byte,
return
}

ctr := cipher.NewCTR(c, ct[:params.BlockSize])
iv := bytes.Repeat([]byte{0}, 16)
ctr := cipher.NewCTR(c, iv)

m = make([]byte, len(ct)-params.BlockSize)
ctr.XORKeyStream(m, ct[params.BlockSize:])
m = make([]byte, len(ct))
ctr.XORKeyStream(m, ct)
return
}

Expand Down Expand Up @@ -240,12 +243,9 @@ func Encrypt(rand io.Reader, pub *PublicKey, m, s1, s2 []byte) (ct []byte, err e
}
Ke := K[:params.KeyLen]
Km := K[params.KeyLen:]
hash.Write(Km)
Km = hash.Sum(nil)
hash.Reset()

em, err := symEncrypt(rand, params, Ke, m)
if err != nil || len(em) <= params.BlockSize {
if err != nil {
return
}

Expand Down Expand Up @@ -320,9 +320,6 @@ func (prv *PrivateKey) Decrypt(rand io.Reader, c, s1, s2 []byte) (m []byte, err

Ke := K[:params.KeyLen]
Km := K[params.KeyLen:]
hash.Write(Km)
Km = hash.Sum(nil)
hash.Reset()

d := messageTag(params.Hash, Km, c[mStart:mEnd], s2)
if subtle.ConstantTimeCompare(c[mEnd:], d) != 1 {
Expand Down