Skip to content

[4.x] Wrap defuse exceptions for malformed keys in the Crypto cipher - #40

Open
Hackwar wants to merge 1 commit into
joomla-framework:4.x-devfrom
Hackwar:4.x-crypto-wrap-key-errors
Open

Hackwar wants to merge 1 commit into
joomla-framework:4.x-devfrom
Hackwar:4.x-crypto-wrap-key-errors

Conversation

@Hackwar

@Hackwar Hackwar commented Nov 12, 2026

Copy link
Copy Markdown
Contributor

Summary of Changes

Cipher\Crypto::encrypt()/decrypt() only catch WrongKeyOrModifiedCiphertextException and EnvironmentIsBrokenException. A malformed key (e.g. a truncated or hand-edited getPrivate() string) makes Defuse\Crypto\Key::loadFromAsciiSafeString() throw Defuse\Crypto\Exception\BadFormatException, which does not implement CryptExceptionInterface, so catch (CryptExceptionInterface $e) does not catch it. With zend.exception_ignore_args=0, its stack trace also contains the key string.

This PR catches it and throws InvalidKeyException('The key is not a valid crypto key.') without chaining the defuse exception, so neither the message nor the trace of the thrown exception contains the key. Any other defuse CryptoException is wrapped in EncryptionException/DecryptionException (also unchained). Correct keys and ciphertexts behave as before.

Marking key parameters with #[\SensitiveParameter] (also suggested for this problem) is done in a separate PR together with the other Key hardening, because it changes the same method signatures.

Testing Instructions

CryptoTest::testMalformedKeyIsRejectedWithoutExposingIt (for encrypt and decrypt) uses a malformed key with zend.exception_ignore_args=0 and expects an InvalidKeyException without a previous exception whose string form does not contain the key. Before the change, BadFormatException escapes.

php vendor/bin/phpunit

Documentation Changes Required

docs/overview.md ("Handling failures"): InvalidKeyException is also thrown for a malformed crypto key.

🤖 Generated with Claude Code

Only WrongKeyOrModifiedCiphertextException and EnvironmentIsBrokenException
were caught. A malformed key raised Defuse's BadFormatException, which does
not implement CryptExceptionInterface, and whose stack trace contains the
key string. Throw InvalidKeyException instead, without chaining the defuse
exception, and wrap any other defuse exception as well.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@Hackwar Hackwar mentioned this pull request Nov 12, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant