This commit is contained in:
@@ -1,7 +1,7 @@
|
|||||||
[versions]
|
[versions]
|
||||||
kotlin = "2.1.20"
|
kotlin = "2.1.20"
|
||||||
mac = "1.1.0"
|
mac = "1.1.0"
|
||||||
hash = "1.1.0"
|
hash = "1.2.0"
|
||||||
|
|
||||||
[plugins]
|
[plugins]
|
||||||
multiplatform = { id = "org.jetbrains.kotlin.multiplatform", version.ref = "kotlin" }
|
multiplatform = { id = "org.jetbrains.kotlin.multiplatform", version.ref = "kotlin" }
|
||||||
|
|||||||
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()
|
||||||
|
}
|
||||||
|
}
|
||||||
26
src/commonMain/kotlin/com/infendro/kdf/util/ByteArray.kt
Normal file
26
src/commonMain/kotlin/com/infendro/kdf/util/ByteArray.kt
Normal 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()
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user