forked from sergeych/crypto2
70 lines
2.0 KiB
Kotlin
70 lines
2.0 KiB
Kotlin
import kotlinx.coroutines.flow.asFlow
|
|
import kotlinx.coroutines.test.runTest
|
|
import kotlinx.datetime.Clock
|
|
import net.sergeych.crypto2.Hash
|
|
import net.sergeych.crypto2.initCrypto
|
|
import kotlin.random.Random
|
|
import kotlin.random.nextUBytes
|
|
import kotlin.test.Test
|
|
import kotlin.test.assertContentEquals
|
|
import kotlin.test.assertEquals
|
|
import kotlin.test.assertFalse
|
|
|
|
@Suppress("UNUSED_PARAMETER", "UNUSED_VARIABLE")
|
|
suspend fun <T> sw(label: String, f: suspend () -> T): T {
|
|
val t1 = Clock.System.now()
|
|
val result = f()
|
|
val t2 = Clock.System.now()
|
|
// println("$label: ${t2 - t1}")
|
|
return result
|
|
}
|
|
|
|
class HashTest {
|
|
@Test
|
|
fun testEqualMethods() {
|
|
fun testMethod(h: Hash) = runTest {
|
|
initCrypto()
|
|
val a = Random.Default.nextUBytes(1024)
|
|
val b = Random.Default.nextUBytes(1024)
|
|
val c = a + b
|
|
val h1 = sw("dir $h") { h.digest(c) }
|
|
val h2 = sw("ind $h") { h.ofFlow(listOf(a, b).asFlow()) }
|
|
|
|
assertContentEquals(h1, h2)
|
|
}
|
|
for (i in 0..10) {
|
|
testMethod(Hash.Blake2b)
|
|
testMethod(Hash.Sha3_256)
|
|
testMethod(Hash.Sha3_384)
|
|
}
|
|
}
|
|
|
|
@Test
|
|
fun testSynthetic() = runTest {
|
|
initCrypto()
|
|
val a = Random.Default.nextUBytes(1024)
|
|
val x = Hash.Sha3AndBlake.digest(a)
|
|
val p1 = x.sliceArray(0..31)
|
|
val p2 = x.drop(32)
|
|
assertContentEquals(Hash.Blake2b.digest(a), p1)
|
|
assertContentEquals(Hash.Sha3_384.digest(a), p2)
|
|
}
|
|
|
|
@Test
|
|
fun deriveSaltTest() = runTest {
|
|
initCrypto()
|
|
for( i in 2..257 ) {
|
|
val x = Hash.Sha3AndBlake.deriveSalt("base one", i)
|
|
val y = Hash.Sha3AndBlake.deriveSalt("base one", i)
|
|
val z = Hash.Sha3AndBlake.deriveSalt("base two", i)
|
|
assertContentEquals(x, y)
|
|
assertFalse { x contentEquals z }
|
|
assertEquals(x.size, i)
|
|
assertEquals(y.size, i)
|
|
assertEquals(z.size, i)
|
|
}
|
|
}
|
|
|
|
}
|
|
|