I'm not sure what the issue is, but I do know a solution. First of all, you probably want to read in the file in chucks. You don't want to store e.g. an entire movie in RAM. So what you can do is to treat the SFTP connection as stream:
According to the sample code here:
$connection = ssh2_connect('shell.example.com', 22); ssh2_auth_password($connection, 'username', 'password'); $sftp = ssh2_sftp($connection); $stream = fopen("ssh2.sftp://$sftp/path/to/file", 'rb');
Note that I used
'rb' to force binary mode.
So now you can read in chunks from the stream, the only thing you need to do is to encrypt/decrypt the stream. Mcrypt does actually provide this functionality using a filter implementation.
So now that you can stream everything, go ahead and implement it.
- mcrypt is an old library that should not be used anymore;
- use MCRYPT_RIJNDAEL_128 instead of using MCRYPT_RIJNDAEL_256 if you want to use AES (the 256 is the block size, not the key size, the key size is determined by - wait for it - the size of the provided key);
- HMAC is secure, but it should be performed over the ciphertext and the IV;
- this is not a full transport protocol - but that doesn't matter much if you send the file over sftp.