refactor SHA1 and SHA2

This commit is contained in:
2025-12-04 19:20:35 +01:00
parent b41debf948
commit 17b765b13c
5 changed files with 124 additions and 114 deletions

View File

@@ -45,43 +45,45 @@ object `SHA-384` : HashFunction() {
value: UByteArray,
): UByteArray {
val h = initial.copyOf()
val l = value.size.toULong() * 8UL
// padding
val paddedValue = buildList {
val blocks = pad(value)
.chunked(128) { it.toUByteArray() }
for (block in blocks) {
process(h, block)
}
return h.sliceArray(0..5).toUByteArray()
}
private fun pad(
value: UByteArray,
): UByteArray {
val l = value.size.toULong() * 8UL
return buildList {
addAll(value)
add(0x80U)
while (size % 128 != 120) {
add(0x00U)
}
addAll(l.toUByteArray())
}
// process
val blocks = paddedValue
.chunked(128) { it.toUByteArray() }
for (block in blocks) {
val w = buildList {
addAll(block.toULongArray())
for (i in 16..<80) {
val s0 = get(i - 15).rotateRight(1) xor get(i - 15).rotateRight(8) xor (get(i - 15) shr 7)
val s1 = get(i - 2).rotateRight(19) xor get(i - 2).rotateRight(61) xor (get(i - 2) shr 6)
add(get(i - 16) + s0 + get(i - 7) + s1)
}
}.toULongArray()
process(h, w)
}
return h.sliceArray(0..5).toUByteArray()
}.toUByteArray()
}
private fun process(
h: ULongArray,
w: ULongArray,
block: UByteArray,
) {
val w = buildList {
addAll(block.toULongArray())
for (i in 16..79) {
val s0 = get(i - 15).rotateRight(1) xor get(i - 15).rotateRight(8) xor (get(i - 15) shr 7)
val s1 = get(i - 2).rotateRight(19) xor get(i - 2).rotateRight(61) xor (get(i - 2) shr 6)
add(get(i - 16) + s0 + get(i - 7) + s1)
}
}.toULongArray()
val v = h.copyOf()
for (i in 0..<80) {
repeat(80) { i ->
val s0 = v[0].rotateRight(28) xor v[0].rotateRight(34) xor v[0].rotateRight(39)
val s1 = v[4].rotateRight(14) xor v[4].rotateRight(18) xor v[4].rotateRight(41)
val ch = (v[4] and v[5]) xor (v[4].inv() and v[6])