From 8f21a346dbb4565e49df9b8b371f5da2911dc9bf Mon Sep 17 00:00:00 2001 From: Infendro Date: Fri, 12 Dec 2025 16:10:57 +0100 Subject: [PATCH] implement common interface --- src/commonMain/kotlin/com/infendro/kdf/KDF.kt | 12 ++++ .../kotlin/com/infendro/kdf/PBKDF2.kt | 62 +++++++++++-------- 2 files changed, 48 insertions(+), 26 deletions(-) create mode 100644 src/commonMain/kotlin/com/infendro/kdf/KDF.kt diff --git a/src/commonMain/kotlin/com/infendro/kdf/KDF.kt b/src/commonMain/kotlin/com/infendro/kdf/KDF.kt new file mode 100644 index 0000000..50c31fe --- /dev/null +++ b/src/commonMain/kotlin/com/infendro/kdf/KDF.kt @@ -0,0 +1,12 @@ +package com.infendro.kdf + +interface KDF { + val bytes: Int + val bits: Int + get() = bytes * 8 + + fun hash( + value: UByteArray, + salt: UByteArray, + ): UByteArray +} diff --git a/src/commonMain/kotlin/com/infendro/kdf/PBKDF2.kt b/src/commonMain/kotlin/com/infendro/kdf/PBKDF2.kt index 8c83875..4259661 100644 --- a/src/commonMain/kotlin/com/infendro/kdf/PBKDF2.kt +++ b/src/commonMain/kotlin/com/infendro/kdf/PBKDF2.kt @@ -1,39 +1,49 @@ package com.infendro.kdf -import com.infendro.bytearray.addAll -import com.infendro.bytearray.toByteArray +import com.infendro.bytearray.toUByteArray import com.infendro.bytearray.xor import com.infendro.hash.HashFunction import com.infendro.mac.HMAC +import kotlin.math.min class PBKDF2( - private val function: HashFunction, -) { - private val hmac = HMAC(function) + override val bytes: Int, + private val iterations: Int, + function: HashFunction, +) : KDF { + init { + if (bytes < 1) throw IllegalArgumentException() + if (iterations < 1) throw IllegalArgumentException() + } - fun hash( - value: ByteArray, - salt: ByteArray, - iterations: Int, - length: Int, - ): ByteArray { - val key = buildList { - for (i in 1..(length + function.bytes - 1) / function.bytes) { - val input = salt + i.toUInt().toByteArray() + private val mac = HMAC(function) - var u = hmac.hash(value, input) - var result = u - repeat(iterations - 1) { - u = hmac.hash(value, u) - result = result xor u - } - - addAll(result) + override fun hash( + value: UByteArray, + salt: UByteArray, + ): UByteArray { + return buildList { + var i = 1 + while (size < bytes) { + addAll( + f(value, salt, i) + .sliceArray(0.. acc xor bytes } } }