implement optimizations
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
package com.infendro.mac
|
||||
|
||||
import com.infendro.bytearray.padEnd
|
||||
import com.infendro.bytes.bytearray.xorInto
|
||||
import com.infendro.hash.HashFunction
|
||||
|
||||
class HMAC(
|
||||
@@ -9,25 +9,24 @@ class HMAC(
|
||||
override val bytes: Int
|
||||
get() = function.bytes
|
||||
|
||||
override fun hash(
|
||||
key: UByteArray,
|
||||
value: UByteArray,
|
||||
): UByteArray {
|
||||
override fun hashInto(key: ByteArray, value: ByteArray, destination: ByteArray, destinationOffset: Int) {
|
||||
val paddedKey = pad(key)
|
||||
|
||||
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: UByteArray,
|
||||
): UByteArray {
|
||||
return when {
|
||||
key.size > function.block -> function.hash(key)
|
||||
key.size < function.block -> key.padEnd(function.block, 0x00U)
|
||||
else -> key
|
||||
val inner = ByteArray(function.block + value.size).also {
|
||||
paddedKey.xorInto(0x36, it)
|
||||
value.copyInto(it, function.block)
|
||||
}
|
||||
val outer = ByteArray(function.block + function.bytes).also {
|
||||
paddedKey.xorInto(0x5C, it)
|
||||
function.hashInto(inner, it, function.block)
|
||||
}
|
||||
function.hashInto(outer, destination, destinationOffset)
|
||||
}
|
||||
|
||||
private fun pad(key: ByteArray): ByteArray =
|
||||
ByteArray(function.block).also {
|
||||
when {
|
||||
key.size > function.block -> function.hashInto(key, it)
|
||||
else -> key.copyInto(it)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user