implement common interface
This commit is contained in:
12
src/commonMain/kotlin/com/infendro/kdf/KDF.kt
Normal file
12
src/commonMain/kotlin/com/infendro/kdf/KDF.kt
Normal 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
|
||||
}
|
||||
@@ -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
|
||||
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()
|
||||
}
|
||||
|
||||
private fun f(
|
||||
value: UByteArray,
|
||||
salt: UByteArray,
|
||||
iteration: Int,
|
||||
): UByteArray {
|
||||
return buildList {
|
||||
add(mac.hash(value, salt + iteration.toUByteArray()))
|
||||
repeat(iterations - 1) {
|
||||
u = hmac.hash(value, u)
|
||||
result = result xor u
|
||||
add(mac.hash(value, last()))
|
||||
}
|
||||
|
||||
addAll(result)
|
||||
}
|
||||
}
|
||||
|
||||
return key
|
||||
.take(length)
|
||||
.toByteArray()
|
||||
}.reduce { acc, bytes -> acc xor bytes }
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user