How to decrypt response on whatsapp flows using phpseclib3 library? on whatsapp business API
im failing to decrypt the response from the whatsapp flow, and im using php, codeigniter 4 with the phpseclib3 library, and below is my sample code:
private function decryptRequest($body, $privatePem) { $encryptedAesKey = base64_decode($body['encrypted_aes_key']); $encryptedFlowData = base64_decode($body['encrypted_flow_data']); $initialVector = base64_decode($body['initial_vector']); $rsa = RSA::load($privatePem) ->withPadding(RSA::ENCRYPTION_OAEP) ->withHash('sha256') ->withMGFHash('sha256'); $decryptedAesKey = $rsa->decrypt($encryptedAesKey); if (!$decryptedAesKey) { throw new Exception('Decryption of AES key failed.'); } $aes = new AES('gcm'); $aes->setKey($decryptedAesKey); $aes->setNonce($initialVector); $decrypted = $aes->decrypt($encryptedFlowData); if (!$decrypted) { throw new Exception('Decryption of flow data failed.'); } return [ 'decryptedBody' => json_decode($decrypted, true), 'aesKeyBuffer' => $decryptedAesKey, 'initialVectorBuffer' => $initialVector, ]; }
and im getting the Ciphertext representative too long error on this line: $decryptedAesKey = $rsa->decrypt($encryptedAesKey);
I have tried to refer to the docementation here https://developers.facebook.com/docs/whatsapp/cloud-api/reference/whatsapp-business-encryption
I have some questions to help debug:
Did you use a passphrase while generating the private key? You don't seem to be using it in the code above Did you recently update the public key and you're testing on a phone? If so, the old public key might be cached on the phone. Return HTTP code 421 from the endpoint to refresh the key on the client as mentioned in the docs https://developers.facebook.com/docs/whatsapp/flows/reference/error-codes#endpoint_error_codes Are you able to preview with the endpoint in the Flow Builder? https://developers.facebook.com/docs/whatsapp/flows/introduction/flowbuilderuiThere's a full code example in PHP for decryption here. You seem to be missing a few steps after the one that's currently failing, so please refer to the example https://developers.facebook.com/docs/whatsapp/flows/guides/implementingyourflowendpoint#php-slim-example
1. on the passpharase, yes, i pass it here $rsa = RSA::load($privatePem,'passphrase'); 2. I had to reverify my key and all seems well 3. Are you able to preview with the endpoint in the Flow Builder? , Yes im able to do that
on #2, if you recently updated the key and it's working on builder but not on phone, then it is likely caching an older key. Can you try on a different phone? if you return http error code 421 from the endpoint, it will force the phone to refresh the key