refactor Keccak

This commit is contained in:
2025-12-04 19:13:39 +01:00
parent 16390b0308
commit 6dc3cf3b87

View File

@@ -41,44 +41,39 @@ open class Keccak(
): UByteArray { ): UByteArray {
val state = ULongArray(25) val state = ULongArray(25)
// padding val blocks = pad(value)
val paddedValue = buildList { .chunked(rate) { it.toUByteArray() }
for (block in blocks) {
absorb(state, block)
}
return squeeze(state)
}
private fun pad(
value: UByteArray,
): UByteArray {
return buildList {
addAll(value) addAll(value)
add(domain) add(domain)
while ((size % rate) != (rate - 1)) { while ((size % rate) != (rate - 1)) {
add(0x00U) add(0x00U)
} }
add(0x80U) add(0x80U)
}
// absorb
val blocks = paddedValue
.chunked(rate) { it.toUByteArray() }
for (block in blocks) {
val numbers = block.toULongArray(LITTLE_ENDIAN)
for ((i, number) in numbers.withIndex()) {
state[i] = state[i] xor number
}
permute(state)
}
// squeeze
return buildList {
var i = 0
while (size < bytes) {
if (i == rate / 8) {
permute(state)
i = 0
}
addAll(
state[i++].toUByteArray(LITTLE_ENDIAN)
.sliceArray(0..<min(bytes - size, 8))
)
}
}.toUByteArray() }.toUByteArray()
} }
private fun absorb(
state: ULongArray,
block: UByteArray,
) {
val numbers = block.toULongArray(LITTLE_ENDIAN)
for ((i, number) in numbers.withIndex()) {
state[i] = state[i] xor number
}
permute(state)
}
private fun permute( private fun permute(
a: ULongArray, a: ULongArray,
) { ) {
@@ -112,4 +107,22 @@ open class Keccak(
a[0] = a[0] xor rc[round] a[0] = a[0] xor rc[round]
} }
} }
fun squeeze(
state: ULongArray,
): UByteArray {
return buildList {
var i = 0
while (size < bytes) {
if (i == rate / 8) {
permute(state)
i = 0
}
addAll(
state[i++].toUByteArray(LITTLE_ENDIAN)
.sliceArray(0..<min(bytes - size, 8))
)
}
}.toUByteArray()
}
} }