Skip to content

Commit

Permalink
Add test for in-place ChaCha20 encryption
Browse files Browse the repository at this point in the history
ChaCha20 is designed to allow encrypting directly inside the plaintext
array to avoid allocating another array for the ciphertext. We add a test
case to ensure this is working as expected.
  • Loading branch information
t-bast committed May 17, 2021
1 parent 1e1037f commit 9fb8417
Showing 1 changed file with 25 additions and 0 deletions.
25 changes: 25 additions & 0 deletions eclair-core/src/test/scala/fr/acinq/eclair/crypto/RandomSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,10 @@

package fr.acinq.eclair.crypto

import fr.acinq.bitcoin.ByteVector32
import fr.acinq.eclair.crypto.RandomSpec.entropyScore
import org.bouncycastle.crypto.engines.ChaCha7539Engine
import org.bouncycastle.crypto.params.{KeyParameter, ParametersWithIV}
import org.scalatest.funsuite.AnyFunSuiteLike
import scodec.bits.BitVector

Expand Down Expand Up @@ -71,6 +74,28 @@ class RandomSpec extends AnyFunSuiteLike {
}
}

// This test shows that we can do in-place encryption with ChaCha20 (no need to allocate another array for the
// ciphertext, we can directly write in the plaintext array).
test("chacha20 in-place stream encryption") {
val noExtraBuffer = new Array[Byte](512)
val withExtraBuffer = new Array[Byte](512)

{
val stream = new ChaCha7539Engine()
stream.init(true, new ParametersWithIV(new KeyParameter(ByteVector32.One.toArray), new Array[Byte](12)))
stream.processBytes(noExtraBuffer, 0, noExtraBuffer.length, noExtraBuffer, 0)
}
{
val stream = new ChaCha7539Engine()
stream.init(true, new ParametersWithIV(new KeyParameter(ByteVector32.One.toArray), new Array[Byte](12)))
val ciphertext = new Array[Byte](withExtraBuffer.length)
stream.processBytes(withExtraBuffer, 0, withExtraBuffer.length, ciphertext, 0)
ciphertext.copyToArray(withExtraBuffer)
}

assert(noExtraBuffer.sameElements(withExtraBuffer))
}

}

object RandomSpec {
Expand Down

0 comments on commit 9fb8417

Please sign in to comment.