From 4bf2e8f8bf0002f23f639aefce5f5162f6f183eb Mon Sep 17 00:00:00 2001 From: Abyr Valg Date: Mon, 13 Apr 2020 07:31:17 +0300 Subject: [PATCH 1/2] Make sure that buffer is always a string substr() returns false when offset is greater than total length. --- src/AesEncryptingStream.php | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/AesEncryptingStream.php b/src/AesEncryptingStream.php index 97dfcdb..1322406 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 : ''; } From 8fc77f6c46b0028905789ec195a162504c0c4342 Mon Sep 17 00:00:00 2001 From: Abyr Valg Date: Sun, 12 Apr 2020 21:26:25 +0300 Subject: [PATCH 2/2] Make eof() consider padding when reading less than block size --- src/AesEncryptingStream.php | 5 +++++ tests/AesEncryptingStreamTest.php | 20 ++++++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/src/AesEncryptingStream.php b/src/AesEncryptingStream.php index 1322406..d61b5ae 100644 --- a/src/AesEncryptingStream.php +++ b/src/AesEncryptingStream.php @@ -97,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); + } }