refactor SHA1 and SHA2
This commit is contained in:
@@ -33,43 +33,45 @@ object `SHA-224` : HashFunction() {
|
||||
value: UByteArray,
|
||||
): UByteArray {
|
||||
val h = initial.copyOf()
|
||||
val l = value.size.toULong() * 8UL
|
||||
|
||||
// padding
|
||||
val paddedValue = buildList {
|
||||
val blocks = pad(value)
|
||||
.chunked(64) { it.toUByteArray() }
|
||||
for (block in blocks) {
|
||||
process(h, block)
|
||||
}
|
||||
|
||||
return h.sliceArray(0..6).toUByteArray()
|
||||
}
|
||||
|
||||
private fun pad(
|
||||
value: UByteArray,
|
||||
): UByteArray {
|
||||
val l = value.size.toULong() * 8UL
|
||||
return buildList {
|
||||
addAll(value)
|
||||
add(0x80U)
|
||||
while (size % 64 != 56) {
|
||||
add(0x00U)
|
||||
}
|
||||
addAll(l.toUByteArray())
|
||||
}
|
||||
|
||||
// process
|
||||
val blocks = paddedValue
|
||||
.chunked(64) { it.toUByteArray() }
|
||||
for (block in blocks) {
|
||||
val w = buildList {
|
||||
addAll(block.toUIntArray())
|
||||
for (i in 16..<64) {
|
||||
val s0 = get(i - 15).rotateRight(7) xor get(i - 15).rotateRight(18) xor (get(i - 15) shr 3)
|
||||
val s1 = get(i - 2).rotateRight(17) xor get(i - 2).rotateRight(19) xor (get(i - 2) shr 10)
|
||||
add(get(i - 16) + s0 + get(i - 7) + s1)
|
||||
}
|
||||
}.toUIntArray()
|
||||
process(h, w)
|
||||
}
|
||||
|
||||
return h.sliceArray(0..6).toUByteArray()
|
||||
}.toUByteArray()
|
||||
}
|
||||
|
||||
private fun process(
|
||||
h: UIntArray,
|
||||
w: UIntArray,
|
||||
block: UByteArray,
|
||||
) {
|
||||
val w = buildList {
|
||||
addAll(block.toUIntArray())
|
||||
for (i in 16..63) {
|
||||
val s0 = get(i - 15).rotateRight(7) xor get(i - 15).rotateRight(18) xor (get(i - 15) shr 3)
|
||||
val s1 = get(i - 2).rotateRight(17) xor get(i - 2).rotateRight(19) xor (get(i - 2) shr 10)
|
||||
add(get(i - 16) + s0 + get(i - 7) + s1)
|
||||
}
|
||||
}.toUIntArray()
|
||||
val v = h.copyOf()
|
||||
|
||||
for (i in 0..<64) {
|
||||
repeat(64) { i ->
|
||||
val s0 = v[0].rotateRight(2) xor v[0].rotateRight(13) xor v[0].rotateRight(22)
|
||||
val s1 = v[4].rotateRight(6) xor v[4].rotateRight(11) xor v[4].rotateRight(25)
|
||||
val ch = (v[4] and v[5]) xor (v[4].inv() and v[6])
|
||||
|
||||
Reference in New Issue
Block a user