Skip to content

Commit

Permalink
Fixed issue where CipherSource as reporting the end of the cipher str…
Browse files Browse the repository at this point in the history
…eam 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.
  • Loading branch information
erickok committed May 8, 2018
1 parent 905ed0d commit 80b9dc1
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 3 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
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
}

}
18 changes: 17 additions & 1 deletion lib/src/test/java/nl/nl2312/okio/cipher/CipherSourceTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand All @@ -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())
Expand Down

0 comments on commit 80b9dc1

Please sign in to comment.