diff --git a/lib/src/main/java/nl/nl2312/okio/cipher/CipherSource.kt b/lib/src/main/java/nl/nl2312/okio/cipher/CipherSource.kt index f2174d7..899fca6 100644 --- a/lib/src/main/java/nl/nl2312/okio/cipher/CipherSource.kt +++ b/lib/src/main/java/nl/nl2312/okio/cipher/CipherSource.kt @@ -53,8 +53,8 @@ class CipherSource( val bytesToReturn = bytesRequested.coerceAtMost(decipheredBuffer.size()) sink.write(decipheredBuffer, bytesToReturn) - // Return number of written deciphered bytes, or -1 if the source stream is exhausted - return if (streamEnd) -1 else bytesToReturn + // Return number of written deciphered bytes, or -1 if the source stream is exhausted and our buffer is empty + return if (streamEnd && decipheredBuffer.size() == 0L) -1 else bytesToReturn } } diff --git a/lib/src/test/java/nl/nl2312/okio/cipher/CipherSourceTest.kt b/lib/src/test/java/nl/nl2312/okio/cipher/CipherSourceTest.kt index 8823a18..98ecc8b 100644 --- a/lib/src/test/java/nl/nl2312/okio/cipher/CipherSourceTest.kt +++ b/lib/src/test/java/nl/nl2312/okio/cipher/CipherSourceTest.kt @@ -70,7 +70,7 @@ class CipherSourceTest { } @Test - fun read_cipheredChunked() { + fun read_cipheredChunked_exactCharacters() { val ciphered = encodeCipher.doFinal("okio oh my¿¡ okio oh my¿¡ okio oh my¿¡".toByteArray()) val cipheredSource = Buffer().write(ciphered) @@ -88,6 +88,22 @@ class CipherSourceTest { assertThat(output.readUtf8()).isEqualTo("okio oh my¿¡ okio oh my¿¡") } + @Test + fun read_cipheredChunked_untilStreamEnd() { + val ciphered = encodeCipher.doFinal("okio oh my¿¡ okio oh my¿¡ okio oh my¿¡".toByteArray()) + val cipheredSource = Buffer().write(ciphered) + + val decoded = CipherSource(cipheredSource, decodeCipher) + + // Request 5 bytes until the stream claims to be empty + val output = Buffer() + var readBytesCount = Long.MAX_VALUE + while (readBytesCount > 0) { + readBytesCount = decoded.read(output, 5) + } + assertThat(output.readUtf8()).isEqualTo("okio oh my¿¡ okio oh my¿¡ okio oh my¿¡") + } + @Test fun read_base64Wrapped() { val ciphered = encodeCipher.doFinal("okio oh my¿¡".toByteArray())