Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make eof() consider padding when reading less than block size #17

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion src/AesEncryptingStream.php
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,11 @@ public function read($length): string
}

$data = substr($this->buffer, 0, $length);
$this->buffer = substr($this->buffer, $length);
if ($length < strlen($this->buffer)) {
$this->buffer = substr($this->buffer, $length);
} else {
$this->buffer = '';
}

return $data ? $data : '';
}
Expand All @@ -93,6 +97,11 @@ public function seek($offset, $whence = SEEK_SET): void
}
}

public function eof(): bool
{
return $this->stream->eof() && $this->buffer === '';
}

private function encryptBlock(int $length): string
{
if ($this->stream->eof()) {
Expand Down
20 changes: 20 additions & 0 deletions tests/AesEncryptingStreamTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -216,4 +216,24 @@ public function seek(int $offset, int $whence = SEEK_SET): void {}

$this->assertRegExp("/EncryptionFailedException: Unable to encrypt/", $error);
}

/**
* @dataProvider cipherMethodProvider
*
* @param CipherMethod $cipherMethod
*/
public function testEofShouldConsiderPaddingWhenReadSizeIsLessThenBlockSize(CipherMethod $cipherMethod)
{
$stream = new AesEncryptingStream(
new RandomByteStream(100),
self::KEY,
$cipherMethod
);
$expectedSize = $stream->getSize();
$actualSize = 0;
while (!$stream->eof()) {
$actualSize += strlen($stream->read(15));
}
$this->assertSame($expectedSize, $actualSize);
}
}