Skip to content

Commit

Permalink
test-first for XD-676
Browse files Browse the repository at this point in the history
  • Loading branch information
morj committed Feb 27, 2018
1 parent 0f2c413 commit 7a7132f
Showing 1 changed file with 26 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import jetbrains.exodus.util.LightOutputStream
import org.junit.Assert
import org.junit.Test
import java.io.ByteArrayInputStream
import java.io.InputStream

private val KEY =
byteArrayOf(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0)
Expand All @@ -28,14 +29,36 @@ open class StreamCipherTest {

@Test
fun testTrivialCipher() {
val cipherInputStream = makeInput() decryptBy { createCipher().init() }
Assert.assertEquals(RENAT_GILFANOV, cipherInputStream.reader().readText())
}

@Test
fun testTrivialCipherBlockWise() {
val cipherInputStream = makeInput().buffered(32) decryptBy { createCipher().init() }
Assert.assertEquals(RENAT_GILFANOV, String(cipherInputStream.readBytesBlockWise(64)))
}

private fun makeInput(): ByteArrayInputStream {
val baseOutputStream = LightOutputStream()
val cipherOutputStream = baseOutputStream encryptBy createCipher().init()
cipherOutputStream.writer().use {
it.write(RENAT_GILFANOV)
}
val baseInputStream = ByteArrayInputStream(baseOutputStream.bufferBytes, 0, baseOutputStream.size())
val cipherInputStream = baseInputStream decryptBy { createCipher().init() }
Assert.assertEquals(RENAT_GILFANOV, cipherInputStream.reader().readText())
return ByteArrayInputStream(baseOutputStream.bufferBytes, 0, baseOutputStream.size())
}

private fun InputStream.readBytesBlockWise(block: Int): ByteArray {
var offset = 0
var remaining = available()
val result = ByteArray(remaining)
while (remaining > 0) {
val read = read(result, offset, minOf(block, remaining))
if (read < 0) break
remaining -= read
offset += read
}
return if (remaining == 0) result else result.copyOf(offset)
}

open fun createCipher(): StreamCipher = TrivialStreamCipher()
Expand Down

0 comments on commit 7a7132f

Please sign in to comment.