initial commit
All checks were successful
/ publish (push) Successful in 2m36s

This commit is contained in:
2025-07-12 19:42:23 +02:00
commit 88ed9108fe
11 changed files with 650 additions and 0 deletions

View 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
}
}