upgrade
Some checks failed
/ publish (pull_request) Has been cancelled
/ test (pull_request) Has been cancelled
/ publish (push) Has been cancelled
/ test (push) Has been cancelled

This commit is contained in:
2026-02-03 23:42:46 +01:00
parent 8686be3346
commit f78b10f565
7 changed files with 79 additions and 78 deletions

View File

@@ -1,10 +1,10 @@
package com.infendro.kdf
import com.infendro.bytearray.toUByteArray
import com.infendro.bytearray.xor
import com.infendro.bytes.bytearray.xorInto
import com.infendro.bytes.int.copyInto
import com.infendro.hash.HashFunction
import com.infendro.kdf.util.ceilDiv
import com.infendro.mac.HMAC
import kotlin.math.min
class PBKDF2(
override val bytes: Int,
@@ -16,34 +16,25 @@ class PBKDF2(
require(iterations > 0)
}
private val mac = HMAC(function)
private val hmac = HMAC(function)
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()
}
override fun hashInto(value: ByteArray, salt: ByteArray, destination: ByteArray, destinationOffset: Int) {
val buffer = ByteArray(hmac.bytes)
private fun f(
value: UByteArray,
salt: UByteArray,
iteration: Int,
): UByteArray {
return buildList {
add(mac.hash(value, salt + iteration.toUByteArray()))
for (iteration in 1..bytes.ceilDiv(hmac.bytes)) {
val offset = (iteration - 1) * hmac.bytes
val block = minOf(bytes - offset, hmac.bytes)
val s = ByteArray(salt.size + 4)
salt.copyInto(s)
iteration.copyInto(s, salt.size)
hmac.hashInto(value, s, buffer)
buffer.copyInto(destination, destinationOffset + offset, endIndex = block)
repeat(iterations - 1) {
add(mac.hash(value, last()))
hmac.hashInto(value, buffer, buffer)
buffer.xorInto(destination, destinationOffset + offset, endIndex = block)
}
}.reduce { acc, bytes -> acc xor bytes }
}
}
}