diff --git a/src/AesEncryptingStream.php b/src/AesEncryptingStream.php index 97dfcdb..d61b5ae 100644 --- a/src/AesEncryptingStream.php +++ b/src/AesEncryptingStream.php @@ -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 : ''; } @@ -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()) { diff --git a/tests/AesEncryptingStreamTest.php b/tests/AesEncryptingStreamTest.php index 201c6e9..af97dc3 100644 --- a/tests/AesEncryptingStreamTest.php +++ b/tests/AesEncryptingStreamTest.php @@ -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); + } }