Skip to content

Commit 7f8984c

Browse files
committed
Fixed issue when using CipherSource and fully relying on it reporting -1 only if nothing was written to the Sink.
This was happening when using Okio's BufferedSource which short-cuts reading even if bytes were written to the wrapped Buffer. A test was added to capture the bug.
1 parent 80b9dc1 commit 7f8984c

File tree

2 files changed

+19
-2
lines changed

2 files changed

+19
-2
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 and our buffer is empty
57-
return if (streamEnd && decipheredBuffer.size() == 0L) -1 else bytesToReturn
56+
// Return number of written deciphered bytes, or -1 if there is nothing more to decipher
57+
return if (bytesToReturn > 0) bytesToReturn else -1
5858
}
5959

6060
}

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

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@ import com.google.common.truth.Truth.assertThat
44
import nl.nl2312.okio.base64.Base64Source
55
import okio.Buffer
66
import okio.ByteString
7+
import okio.Okio
8+
import okio.Source
79
import org.junit.Test
810
import java.security.SecureRandom
911
import javax.crypto.Cipher
@@ -104,6 +106,21 @@ class CipherSourceTest {
104106
assertThat(output.readUtf8()).isEqualTo("okio oh my¿¡ okio oh my¿¡ okio oh my¿¡")
105107
}
106108

109+
@Test
110+
fun read_buffered_whileBytesRead() {
111+
val ciphered = encodeCipher.doFinal("okio oh my¿¡ okio oh my¿¡ okio oh my¿¡".toByteArray())
112+
val cipheredSource = Buffer().write(ciphered)
113+
114+
val decoded = CipherSource(cipheredSource, decodeCipher)
115+
116+
// Okio's RealBufferedSource.read(Buffer, Long) will only write to the given buffer when the
117+
// CipherSource.read(Buffer, Long) returns a non-negative byes read could
118+
val buffer = Okio.buffer(decoded as Source)
119+
val output = Buffer()
120+
buffer.read(output, 8192)
121+
assertThat(output.readUtf8()).isEqualTo("okio oh my¿¡ okio oh my¿¡ okio oh my¿¡")
122+
}
123+
107124
@Test
108125
fun read_base64Wrapped() {
109126
val ciphered = encodeCipher.doFinal("okio oh my¿¡".toByteArray())

0 commit comments

Comments
 (0)