implement common interface

This commit is contained in:
2025-12-12 16:10:57 +01:00
parent 6dec2fea74
commit 8f21a346db
2 changed files with 48 additions and 26 deletions

View File

@@ -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
}

View File

@@ -1,39 +1,49 @@
package com.infendro.kdf package com.infendro.kdf
import com.infendro.bytearray.addAll import com.infendro.bytearray.toUByteArray
import com.infendro.bytearray.toByteArray
import com.infendro.bytearray.xor import com.infendro.bytearray.xor
import com.infendro.hash.HashFunction import com.infendro.hash.HashFunction
import com.infendro.mac.HMAC import com.infendro.mac.HMAC
import kotlin.math.min
class PBKDF2( class PBKDF2(
private val function: HashFunction, override val bytes: Int,
) { private val iterations: Int,
private val hmac = HMAC(function) function: HashFunction,
) : KDF {
init {
if (bytes < 1) throw IllegalArgumentException()
if (iterations < 1) throw IllegalArgumentException()
}
fun hash( private val mac = HMAC(function)
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()
var u = hmac.hash(value, input) override fun hash(
var result = u value: UByteArray,
salt: UByteArray,
): UByteArray {
return buildList {
var i = 1
while (size < bytes) {
addAll(
f(value, salt, i)
.sliceArray(0..<min(bytes - size, mac.bytes))
)
i++
}
}.toUByteArray()
}
private fun f(
value: UByteArray,
salt: UByteArray,
iteration: Int,
): UByteArray {
return buildList {
add(mac.hash(value, salt + iteration.toUByteArray()))
repeat(iterations - 1) { repeat(iterations - 1) {
u = hmac.hash(value, u) add(mac.hash(value, last()))
result = result xor u
} }
}.reduce { acc, bytes -> acc xor bytes }
addAll(result)
}
}
return key
.take(length)
.toByteArray()
} }
} }