@@ -3,20 +3,29 @@ package nl.sanderdijkhuis.noise
33import nl.sanderdijkhuis.noise.cryptography.*
44import nl.sanderdijkhuis.noise.data.State
55
6- /* * Encompasses all Noise protocol cipher state required to encrypt and decrypt data. */
6+ /* *
7+ * Encompasses all Noise protocol cipher state required to encrypt and decrypt data.
8+ *
9+ * Note that as per Noise revision 34 § 5.1, [[key]] may be uninitialized. In this case [[encrypt]] and [[decrypt]]
10+ * are identity functions over the plaintext and ciphertext.
11+ *
12+ * Encryption and decryption throw if incrementing [[nonce]] results in its maximum value: it means too many messages
13+ * have been exchanged. Too many is a lot indeed: 2^64-1.
14+ */
715data class Cipher (val cryptography : Cryptography , val key : CipherKey ? = null , val nonce : Nonce = Nonce .zero) {
816
917 fun encrypt (associatedData : AssociatedData , plaintext : Plaintext ): State <Cipher , Ciphertext > =
1018 key?.let { k ->
11- nonce.increment()?.let {
12- State (copy(nonce = it), cryptography.encrypt(k, nonce, associatedData, plaintext))
19+ nonce.increment().let { n ->
20+ checkNotNull(n) { " Too many messages" }
21+ State (copy(nonce = n), cryptography.encrypt(k, nonce, associatedData, plaintext))
1322 }
1423 } ? : State (this , Ciphertext (plaintext.data))
1524
1625 fun decrypt (associatedData : AssociatedData , ciphertext : Ciphertext ): State <Cipher , Plaintext >? =
17- nonce.increment()? .let { n ->
18- key?. let {
19- cryptography.decrypt(it, nonce, associatedData, ciphertext)?. let { p -> State (copy(nonce = n), p) }
20- } ? : State (this , ciphertext.plaintext)
26+ nonce.increment().let { n ->
27+ checkNotNull(n) { " Too many messages " }
28+ if (key == null ) return State (this , ciphertext.plaintext)
29+ cryptography.decrypt(key, nonce, associatedData, ciphertext)?. let { p -> State (copy(nonce = n), p) }
2130 }
2231}
0 commit comments