implement optimizations

This commit is contained in:
2026-01-15 22:06:28 +01:00
parent ab036f4f9f
commit d40df04e2e
26 changed files with 463 additions and 855 deletions

View File

@@ -1,9 +1,10 @@
package com.infendro.hash.blake2
import com.infendro.bytearray.ByteOrder
import com.infendro.bytearray.toUByteArray
import com.infendro.bytearray.toULongArray
import com.infendro.bytes.ByteOrder.LITTLE_ENDIAN
import com.infendro.bytes.bytearray.copyInto
import com.infendro.bytes.longarray.toByteArray
import com.infendro.hash.HashFunction
import com.infendro.hash.util.ceilPow2
class Blake2b(
override val bytes: Int,
@@ -20,7 +21,7 @@ class Blake2b(
0x3c6ef372fe94f82bUL, 0xa54ff53a5f1d36f1UL,
0x510e527fade682d1UL, 0x9b05688c2b3e6c1fUL,
0x1f83d9abfb41bd6bUL, 0x5be0cd19137e2179UL,
)
).asLongArray()
private val sigma = arrayOf(
intArrayOf(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15),
@@ -35,45 +36,42 @@ class Blake2b(
intArrayOf(10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0),
)
override fun hash(value: UByteArray): UByteArray {
val l = value.size.toULong()
override fun hashInto(value: ByteArray, destination: ByteArray) {
val length = value.size.toULong()
val input = pad(value)
val h = initial.copyOf()
h[0] = h[0] xor (0x01010000UL or bytes.toULong())
h[0] = h[0] xor (0x01010000L or bytes.toLong())
val m = LongArray(16)
val v = LongArray(16)
var t = 0UL
val blocks = pad(value)
.chunked(128) { it.toUByteArray() }
for ((i, block) in blocks.withIndex()) {
t += minOf(l - t, 128UL)
compress(h, block, t, i == blocks.lastIndex)
for (i in input.indices step block) {
t += minOf(length - t, 128UL)
compress(h, input, i, m, v, t, t < 1024UL)
}
return h.toUByteArray(ByteOrder.LITTLE_ENDIAN).sliceArray(0..<bytes)
h.toByteArray(LITTLE_ENDIAN).copyInto(destination, endIndex = bytes)
}
private fun pad(
value: UByteArray,
): UByteArray {
return buildList {
addAll(value)
if (isEmpty()) add(0x00U)
while (size % 128 != 0) {
add(0x00U)
}
}.toUByteArray()
private fun pad(value: ByteArray): ByteArray {
val size = maxOf(ceilPow2(value.size, block), block)
val result = ByteArray(size)
value.copyInto(result)
return result
}
private fun compress(
h: ULongArray,
block: UByteArray,
h: LongArray,
value: ByteArray,
offset: Int,
m: LongArray,
v: LongArray,
t: ULong,
last: Boolean,
) {
val m = block.toULongArray()
val v = ULongArray(16)
value.copyInto(m, startIndex = offset, endIndex = offset + block)
for (i in 0..<8) v[i] = h[i]
for (i in 0..<8) v[i + 8] = initial[i]
v[12] = v[12] xor t
v[12] = v[12] xor t.toLong()
if (last) v[14] = v[14].inv()
repeat(12) { r ->
@@ -90,20 +88,12 @@ class Blake2b(
mix(v, 3, 4, 9, 14, m[s[14]], m[s[15]])
}
for (i in 0..7) {
for (i in 0..<8) {
h[i] = h[i] xor v[i] xor v[i + 8]
}
}
private fun mix(
v: ULongArray,
a: Int,
b: Int,
c: Int,
d: Int,
x: ULong,
y: ULong,
) {
private fun mix(v: LongArray, a: Int, b: Int, c: Int, d: Int, x: Long, y: Long) {
v[a] += v[b] + x
v[d] = (v[d] xor v[a]).rotateRight(32)
v[c] += v[d]