From 2f13fbfdf79e96fc10f2c679d11643994d58334e Mon Sep 17 00:00:00 2001 From: Sander Dijkhuis Date: Wed, 31 Jan 2024 17:36:43 +0100 Subject: [PATCH] test: throw upon reaching too high nonces Thanks to @breynders-cb and @tvandriessel-cb for spotting the risk. --- src/test/kotlin/CipherTest.kt | 37 +++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 src/test/kotlin/CipherTest.kt diff --git a/src/test/kotlin/CipherTest.kt b/src/test/kotlin/CipherTest.kt new file mode 100644 index 0000000..78b649d --- /dev/null +++ b/src/test/kotlin/CipherTest.kt @@ -0,0 +1,37 @@ +package nl.sanderdijkhuis.noise + +import nl.sanderdijkhuis.noise.cryptography.AssociatedData +import nl.sanderdijkhuis.noise.cryptography.CipherKey +import nl.sanderdijkhuis.noise.cryptography.Nonce +import nl.sanderdijkhuis.noise.cryptography.Plaintext +import nl.sanderdijkhuis.noise.data.Data +import org.junit.jupiter.api.assertThrows +import kotlin.test.Test + +@OptIn(ExperimentalStdlibApi::class) +class CipherTest { + private val data = AssociatedData(Data.empty) + private val plaintext = Plaintext(Data.empty) + + @Test + fun `throws upon reaching nonce maximum while encrypting`() { + val nonceTooHighToToUse = Nonce(ULong.MAX_VALUE - 1uL) // 2^64-2 + + assertThrows { cipher(nonceTooHighToToUse).encrypt(data, plaintext) } + } + + @Test + fun `throws upon reaching nonce maximum while decrypting`() { + val nonceTooHighToEncrypt = Nonce(ULong.MAX_VALUE - 2uL) // 2^64-3 + val (cipher, ciphertext) = cipher(nonceTooHighToEncrypt).encrypt(data, plaintext) + + assertThrows { cipher.decrypt(data, ciphertext) } + } + + private fun cipher(nonce: Nonce) = + Cipher( + JavaCryptography, + CipherKey(Data("76fef1ab184aa7539e3b62a43019ecafc621248b3ac2f5297dd5814e3bd560d3".hexToByteArray())), + nonce + ) +}