Skip to content

Commit 9a1a8ba

Browse files
committed
fix: prevent panic on short ciphertext in XChaCha20Poly1305.Decrypt
1 parent b0952b2 commit 9a1a8ba

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

cipher/chacha20.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ func (c *XChaCha20Poly1305) Decrypt(ctx context.Context, ciphertext string) ([]b
7676
return nil, errors.WithStack(herodot.ErrInternalServerError.WithWrap(err).WithReason("Unable to instantiate chacha20"))
7777
}
7878

79-
if len(ciphertext) < aead.NonceSize() {
79+
if len(rawCiphertext) < aead.NonceSize() {
8080
return nil, errors.WithStack(herodot.ErrInternalServerError.WithReason("cipher text too short"))
8181
}
8282

cipher/cipher_test.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,25 @@ func TestCipher(t *testing.T) {
7373
_, err = c.Decrypt(contextx.WithConfigValue(ctx, config.ViperKeySecretsCipher, []string{""}), "not-empty")
7474
require.Error(t, err)
7575
})
76+
77+
t.Run("case=short_ciphertext", func(t *testing.T) {
78+
t.Parallel()
79+
80+
// XChaCha20-Poly1305 has 24-byte nonce, hex encoded is 48 chars
81+
// A valid ciphertext needs at least 24 bytes (nonce) + 16 bytes (tag) = 40 bytes minimum
82+
// Hex encoded minimum is 80 chars
83+
// This tests that we don't get panic on short ciphertext
84+
85+
// 24 hex chars is only 12 bytes - less than nonce size (24 bytes)
86+
shortCiphertext := "00112233445566778899aabbccddeeff"
87+
_, err := c.Decrypt(ctx, shortCiphertext)
88+
require.Error(t, err)
89+
90+
// 64 hex chars is 32 bytes - still less than nonce(24)+tag(16)=40
91+
mediumCiphertext := "00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff"
92+
_, err = c.Decrypt(ctx, mediumCiphertext)
93+
require.Error(t, err)
94+
})
7695
})
7796
}
7897

0 commit comments

Comments
 (0)