Skip to content

Commit

Permalink
Fixed issue when using CipherSource and fully relying on it reporting…
Browse files Browse the repository at this point in the history
… -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.
  • Loading branch information
erickok committed May 22, 2018
1 parent 80b9dc1 commit 7f8984c
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
4 changes: 2 additions & 2 deletions lib/src/main/java/nl/nl2312/okio/cipher/CipherSource.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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 and our buffer is empty
return if (streamEnd && decipheredBuffer.size() == 0L) -1 else bytesToReturn
// Return number of written deciphered bytes, or -1 if there is nothing more to decipher
return if (bytesToReturn > 0) bytesToReturn else -1
}

}
17 changes: 17 additions & 0 deletions lib/src/test/java/nl/nl2312/okio/cipher/CipherSourceTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import com.google.common.truth.Truth.assertThat
import nl.nl2312.okio.base64.Base64Source
import okio.Buffer
import okio.ByteString
import okio.Okio
import okio.Source
import org.junit.Test
import java.security.SecureRandom
import javax.crypto.Cipher
Expand Down Expand Up @@ -104,6 +106,21 @@ class CipherSourceTest {
assertThat(output.readUtf8()).isEqualTo("okio oh my¿¡ okio oh my¿¡ okio oh my¿¡")
}

@Test
fun read_buffered_whileBytesRead() {
val ciphered = encodeCipher.doFinal("okio oh my¿¡ okio oh my¿¡ okio oh my¿¡".toByteArray())
val cipheredSource = Buffer().write(ciphered)

val decoded = CipherSource(cipheredSource, decodeCipher)

// Okio's RealBufferedSource.read(Buffer, Long) will only write to the given buffer when the
// CipherSource.read(Buffer, Long) returns a non-negative byes read could
val buffer = Okio.buffer(decoded as Source)
val output = Buffer()
buffer.read(output, 8192)
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())
Expand Down

0 comments on commit 7f8984c

Please sign in to comment.