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
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..<min(bytes - size, mac.bytes))
)
i++
}
}
}.toUByteArray()
}
return key
.take(length)
.toByteArray()
private fun f(
value: UByteArray,
salt: UByteArray,
iteration: Int,
): UByteArray {
return buildList {
add(mac.hash(value, salt + iteration.toUByteArray()))
repeat(iterations - 1) {
add(mac.hash(value, last()))
}
}.reduce { acc, bytes -> acc xor bytes }
}
}