implement common class, refactor HMAC

This commit is contained in:
2025-11-10 14:54:19 +01:00
parent 045af38398
commit 9db4ee21a0
4 changed files with 39 additions and 30 deletions

View File

@@ -1,45 +1,33 @@
package com.infendro.mac
import com.infendro.hash.*
import kotlin.experimental.xor
import com.infendro.bytearray.padEnd
import com.infendro.hash.HashFunction
class HMAC(
val function: HashFunction,
) {
val block: Int
get() = when (function) {
MD5, SHA1, SHA224, SHA256 -> 64
SHA384, SHA512 -> 128
}
) : MAC() {
override val bytes: Int
get() = function.bytes
fun hash(
key: ByteArray,
value: ByteArray,
): ByteArray {
override fun hash(
key: UByteArray,
value: UByteArray,
): UByteArray {
val paddedKey = pad(key)
val innerKey = paddedKey.map { it xor 0x36 }.toByteArray()
val outerKey = paddedKey.map { it xor 0x5C }.toByteArray()
val innerKey = paddedKey.map { it xor 0x36U }.toUByteArray()
val outerKey = paddedKey.map { it xor 0x5CU }.toUByteArray()
return function.hash(outerKey + function.hash(innerKey + value))
}
private fun pad(
key: ByteArray,
): ByteArray {
if (key.size > block) {
return function.hash(key)
key: UByteArray,
): UByteArray {
return when {
key.size > function.block -> function.hash(key)
key.size < function.block -> key.padEnd(function.block, 0x00U)
else -> key
}
if (key.size < block) {
return buildList {
addAll(key.toList())
repeat(block - size) {
add(0x00)
}
}.toByteArray()
}
return key
}
}