simplifies nonce calculation

This commit is contained in:
sergeych committed 2024-06-14 11:52:43 +07:00
1 parent 9660379891
commit 3dd1654f70
2 files changed
+9 -24

No files matched your search

@@ -1,10 +1,6 @@
package net.sergeych.kiloparsec
import kotlinx.coroutines.CompletableDeferred
import net.sergeych.mp_logger.LogTag
import net.sergeych.mp_logger.Loggable
import net.sergeych.mp_logger.debug
import net.sergeych.mp_logger.info
import net.sergeych.tools.AtomicCounter
import net.sergeych.utools.pack
@@ -19,7 +15,10 @@ private val idCounter = AtomicCounter(0)
internal class KiloL0Interface<T>(
private val clientInterface: LocalInterface<KiloScope<T>>,
private val deferredParams: CompletableDeferred<KiloParams<T>>,
) : LocalInterface<Unit>(), Loggable by LogTag("KL0:${idCounter.incrementAndGet()}") {
) : LocalInterface<Unit>() {
override var logTag: String = "KL0:${idCounter.incrementAndGet()}"
init {
// local interface uses the same session as a client:
addErrorProvider(clientInterface)
@@ -47,23 +47,9 @@ data class KiloParams<S>(
blake2b("token_".encodeToUByteArray() + sessionKey.sessionTag).sliceArray(0..<SymmetricKey.nonceByteLength)
}
private inline fun encodeNonce(base: UByteArray, nonce: ULong): UByteArray {
val result = base.copyOf()
var x = nonce
var i = 0
while (x > 0u) {
result[i] = result[i] xor (x and 0xFFu).toUByte()
x = x shr 8
i++
}
return result
}
private val numericNonce = NumericNonce(token)
private inline fun encodeSendNonce(nonce: ULong): UByteArray = encodeNonce(token, nonce)
private inline fun encodeReceiveNonce(nonce: ULong): UByteArray = encodeNonce(token, nonce)
private val proptectedOp = ProtectedOp()
private val protectedOp = ProtectedOp()
/**
* Encrypt using send keys and proper nonce
@@ -74,10 +60,10 @@ data class KiloParams<S>(
else
null
val n = proptectedOp.invoke { nonce++ }
val n = protectedOp.invoke { nonce++ }
return pack(
Package(n, sessionKey.encryptWithNonce(message, encodeSendNonce(n), fill))
Package(n, sessionKey.encryptWithNonce(message, numericNonce.withULong(n), fill))
)
}
@@ -85,7 +71,7 @@ data class KiloParams<S>(
fun decrypt(encryptedMessage: UByteArray): UByteArray =
protectDecryption {
val p: Package = BipackDecoder.decode(encryptedMessage.toDataSource())
sessionKey.decryptWithNonce(p.encryptedMessage, encodeReceiveNonce(p.nonce))
sessionKey.decryptWithNonce(p.encryptedMessage, numericNonce.withULong(p.nonce))
}
}