Skip to content

Commit 80b9dc1

Browse files
committed
Fixed issue where CipherSource as reporting the end of the cipher stream incorrectly.
This was happening if the wrapped (source) steam ended but we already read and deciphered more bytes than the last read requested. A test was added to capture the bug.
1 parent 905ed0d commit 80b9dc1

File tree

2 files changed

+19
-3
lines changed

2 files changed

+19
-3
lines changed

lib/src/main/java/nl/nl2312/okio/cipher/CipherSource.kt

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -53,8 +53,8 @@ class CipherSource(
5353
val bytesToReturn = bytesRequested.coerceAtMost(decipheredBuffer.size())
5454
sink.write(decipheredBuffer, bytesToReturn)
5555

56-
// Return number of written deciphered bytes, or -1 if the source stream is exhausted
57-
return if (streamEnd) -1 else bytesToReturn
56+
// Return number of written deciphered bytes, or -1 if the source stream is exhausted and our buffer is empty
57+
return if (streamEnd && decipheredBuffer.size() == 0L) -1 else bytesToReturn
5858
}
5959

6060
}

lib/src/test/java/nl/nl2312/okio/cipher/CipherSourceTest.kt

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ class CipherSourceTest {
7070
}
7171

7272
@Test
73-
fun read_cipheredChunked() {
73+
fun read_cipheredChunked_exactCharacters() {
7474
val ciphered = encodeCipher.doFinal("okio oh my¿¡ okio oh my¿¡ okio oh my¿¡".toByteArray())
7575
val cipheredSource = Buffer().write(ciphered)
7676

@@ -88,6 +88,22 @@ class CipherSourceTest {
8888
assertThat(output.readUtf8()).isEqualTo("okio oh my¿¡ okio oh my¿¡")
8989
}
9090

91+
@Test
92+
fun read_cipheredChunked_untilStreamEnd() {
93+
val ciphered = encodeCipher.doFinal("okio oh my¿¡ okio oh my¿¡ okio oh my¿¡".toByteArray())
94+
val cipheredSource = Buffer().write(ciphered)
95+
96+
val decoded = CipherSource(cipheredSource, decodeCipher)
97+
98+
// Request 5 bytes until the stream claims to be empty
99+
val output = Buffer()
100+
var readBytesCount = Long.MAX_VALUE
101+
while (readBytesCount > 0) {
102+
readBytesCount = decoded.read(output, 5)
103+
}
104+
assertThat(output.readUtf8()).isEqualTo("okio oh my¿¡ okio oh my¿¡ okio oh my¿¡")
105+
}
106+
91107
@Test
92108
fun read_base64Wrapped() {
93109
val ciphered = encodeCipher.doFinal("okio oh my¿¡".toByteArray())

0 commit comments

Comments
 (0)