implement PBKDF2
All checks were successful
/ publish (push) Successful in 2m37s

This commit is contained in:
2025-07-20 10:43:05 +02:00
parent 778b00fddf
commit c047b04d95
3 changed files with 72 additions and 1 deletions

View File

@@ -0,0 +1,45 @@
package com.infendro.kdf
import com.infendro.hash.HashFunction
import com.infendro.kdf.util.addAll
import com.infendro.kdf.util.toByteArray
import com.infendro.kdf.util.xor
import com.infendro.mac.HMAC
class PBKDF2(
function: HashFunction,
) {
private val size = function.bytes
private val hmac = HMAC(function)
fun hash(
value: ByteArray,
salt: ByteArray,
iterations: Int,
length: Int,
): ByteArray {
val key = mutableListOf<Byte>()
for (i in 1..(length + size - 1) / size) {
val input = salt + i.toUInt().toByteArray()
var u = hmac.hash(value, input)
var result = u
repeat(iterations - 1) {
u = hmac.hash(value, u)
result = result xor u
}
key.addAll(result)
if (key.size >= length) {
println(key.size)
break
}
}
return key
.take(length)
.toByteArray()
}
}

View File

@@ -0,0 +1,26 @@
package com.infendro.kdf.util
import kotlin.experimental.xor
internal infix fun ByteArray.xor(
that: ByteArray,
): ByteArray {
if (this.size != that.size) throw Exception()
return ByteArray(size) { i ->
this[i] xor that[i]
}
}
internal fun MutableCollection<Byte>.addAll(
bytes: ByteArray,
): Boolean {
return addAll(bytes.toList())
}
internal fun UInt.toByteArray(): ByteArray {
return ByteArray(4) { i ->
val offset = (3 - i) * 8
(this shr offset).toByte()
}
}