{"record":{"id":"fcaefa3a7b568686","repo":"phalcon/cphalcon","slug":"could-not-encrypt-data","errorCode":null,"errorMessage":"Could not encrypt data","messagePattern":"Could not encrypt data","errorType":"exception","errorClass":"EncryptionFailed","httpStatus":null,"severity":"error","filePath":"phalcon/Encryption/Crypt.zep","lineNumber":924,"sourceCode":"                iv,\n                authTag,\n                authData,\n                authTagLength\n            );\n\n            let this->authTag = authTag;\n        } else {\n            let encrypted = openssl_encrypt(\n                padded,\n                cipher,\n                encryptKey,\n                OPENSSL_RAW_DATA,\n                iv\n            );\n        }\n\n        if (false === encrypted) {\n            throw new EncryptionFailed();\n        }\n\n        /**\n         * Store the tag with encrypted data and return it. In the non AEAD\n         * mode this is an empty string\n         */\n        return encrypted . authTag;\n    }\n\n    /**\n     * Initialize available cipher algorithms.\n     *\n     * @return static\n     * @throws Exception\n     */\n    protected function initializeAvailableCiphers() -> <static>\n    {\n        var available, cipher;","sourceCodeStart":906,"sourceCodeEnd":942,"githubUrl":"https://github.com/phalcon/cphalcon/blob/b7419de9cd0a8a3f48441ead84c9f8415d463e25/phalcon/Encryption/Crypt.zep#L906-L942","documentation":"Crypt's encrypt path calls openssl_encrypt(); a false return is converted to EncryptionFailed('Could not encrypt data'). OpenSSL refuses to encrypt when the key length does not match the cipher (e.g., a 13-byte string with aes-256 requiring 32), or when GCM/CCM is used with invalid tag/length parameters - Phalcon surfaces it as this exception.","triggerScenarios":"setKey($passphrase) with an arbitrary-length string while the cipher expects an exact key size; AEAD mode with an incompatible auth tag setup; extremely rare OpenSSL build issues with the chosen cipher (usually caught earlier by the availability check).","commonSituations":"Passing human passwords directly as keys; env key values that lost bytes (encoding, quoting) so their length no longer matches; mixing key derivation on one side but not the other; truncated keys after config serialization.","solutions":["Derive an exact-length key: 32 bytes for aes-256-* - e.g. hash('sha256', $secret, true) - or generate with random_bytes(32) and store verbatim.","Validate key length at boot: if (strlen($key) !== 32) throw ... next to your Crypt setup.","For GCM/CCM confirm setAuthData() was called and the tag length (if set) is 4..16.","Catch EncryptionFailed where user data is encrypted and degrade gracefully (log, reject the operation) - never retry with a different key silently."],"exampleFix":"// before\n$crypt->setKey(getenv('APP_SECRET'));   // arbitrary length, e.g. 19 chars\n$crypt->encrypt($data);                 // openssl_encrypt false -> throws\n\n// after\n$crypt->setKey(substr(hash('sha256', getenv('APP_SECRET'), true), 0, 32));\n$crypt->encrypt($data);","handlingStrategy":"try-catch","validationCode":"$required = ['aes-128' => 16, 'aes-192' => 24, 'aes-256' => 32];\n$prefix = substr($cipher, 0, 7);\nif (isset($required[$prefix]) && strlen($key) !== $required[$prefix]) {\n    throw new \\RuntimeException(\"Key for {$cipher} must be {$required[$prefix]} bytes\");\n}\n$crypt->setKey($key);\n$crypt->encrypt($data);","typeGuard":null,"tryCatchPattern":"try {\n    $stored = $crypt->encrypt($data);\n} catch (\\Phalcon\\Encryption\\Crypt\\Exception\\EncryptionFailed $e) {\n    // wrong key length or AEAD misconfiguration - fail the write, alert\n    $logger->error('Encryption failed: ' . $e->getMessage());\n    throw new \\RuntimeException('Could not secure payload', 0, $e);\n}","preventionTips":["Always derive exact-length keys (hash('sha256', $secret, true) or random_bytes(32)).","Validate key length at boot next to your Crypt DI setup.","Never store plaintext as a fallback when encryption fails - surface the error instead."],"tags":["phalcon","crypt","encryption","openssl","key-length"],"backgroundTag":"encryption-failed","analyzedSha":"b7419de9cd0a8a3f48441ead84c9f8415d463e25","analyzedAt":"2026-08-21T06:21:18.811Z","schemaVersion":2},"datasetVersion":"2026-08-21T11:28:35.574Z"}