This commit is contained in:
45
src/commonMain/kotlin/com/infendro/kdf/PBKDF2.kt
Normal file
45
src/commonMain/kotlin/com/infendro/kdf/PBKDF2.kt
Normal 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()
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user