This commit is contained in:
45
src/commonMain/kotlin/com/infendro/mac/HMAC.kt
Normal file
45
src/commonMain/kotlin/com/infendro/mac/HMAC.kt
Normal file
@@ -0,0 +1,45 @@
|
||||
package com.infendro.mac
|
||||
|
||||
import com.infendro.hash.*
|
||||
import kotlin.experimental.xor
|
||||
|
||||
class HMAC(
|
||||
val function: HashFunction,
|
||||
) {
|
||||
val block: Int
|
||||
get() = when (function) {
|
||||
MD5, SHA1, SHA224, SHA256 -> 64
|
||||
SHA384, SHA512 -> 128
|
||||
}
|
||||
|
||||
fun hash(
|
||||
key: ByteArray,
|
||||
value: ByteArray,
|
||||
): ByteArray {
|
||||
val paddedKey = pad(key)
|
||||
|
||||
val innerKey = paddedKey.map { it xor 0x36 }.toByteArray()
|
||||
val outerKey = paddedKey.map { it xor 0x5C }.toByteArray()
|
||||
|
||||
return function.hash(outerKey + function.hash(innerKey + value))
|
||||
}
|
||||
|
||||
private fun pad(
|
||||
key: ByteArray,
|
||||
): ByteArray {
|
||||
if (key.size > block) {
|
||||
return function.hash(key)
|
||||
}
|
||||
|
||||
if (key.size < block) {
|
||||
return buildList {
|
||||
addAll(key.toList())
|
||||
repeat(block - size) {
|
||||
add(0x00)
|
||||
}
|
||||
}.toByteArray()
|
||||
}
|
||||
|
||||
return key
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user