diff --git a/cipher/chacha20.go b/cipher/chacha20.go index 46cf1efc85d9..9c35e4237369 100644 --- a/cipher/chacha20.go +++ b/cipher/chacha20.go @@ -8,6 +8,7 @@ import ( "crypto/rand" "encoding/hex" "io" + "math" "github.com/pkg/errors" "golang.org/x/crypto/chacha20poly1305" @@ -43,6 +44,11 @@ func (c *XChaCha20Poly1305) Encrypt(ctx context.Context, message []byte) (string return "", herodot.ErrInternalServerError.WithWrap(err).WithReason("Unable to generate key") } + // Make sure the size calculation does not overflow. + if len(message) > math.MaxInt-aead.NonceSize()-aead.Overhead() { + return "", errors.WithStack(herodot.ErrInternalServerError.WithReason("plaintext too large")) + } + nonce := make([]byte, aead.NonceSize(), aead.NonceSize()+len(message)+aead.Overhead()) _, err = io.ReadFull(rand.Reader, nonce) if err != nil {