Files
crypto2/src/commonTest/kotlin/HashTest.kt
T

99 lines
3.0 KiB
Kotlin

/*
* Copyright (c) 2025. Sergey S. Chernov - All Rights Reserved
*
* You may use, distribute and modify this code under the
* terms of the private license, which you must obtain from the author
*
* To obtain the license, contact the author: https://t.me/real_sergeych or email to
* real dot sergeych at gmail.
*/
import kotlinx.coroutines.flow.asFlow
import kotlinx.coroutines.test.runTest
import kotlin.time.Clock
import net.sergeych.crypto2.Hash
import net.sergeych.crypto2.initCrypto
import kotlin.random.Random
import kotlin.random.nextUBytes
import kotlin.test.Ignore
import kotlin.test.Test
import kotlin.test.assertContentEquals
import kotlin.test.assertEquals
import kotlin.test.assertFalse
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 (hash in Hash.entries) {
for (i in 1..257) {
val x = hash.deriveSalt("base one", i)
val y = hash.deriveSalt("base one", i)
val z = hash.deriveSalt("base two", i)
assertContentEquals(x, y)
if (i > 1) assertFalse { x contentEquals z }
assertEquals(i, x.size)
assertEquals(i, y.size)
assertEquals(i, z.size)
}
}
}
@Test
fun deriveSaltFromBytesTest() = runTest {
initCrypto()
val base = "base one".encodeToByteArray().asUByteArray()
for (hash in Hash.entries) {
for (i in listOf(1, 5, 31, 32, 33, 96, 97)) {
val fromString = hash.deriveSalt("base one", i)
val fromBytes = hash.deriveSaltFromBytes(base, i)
val fromTypoAlias = hash.deriveSaltFormBytes(base, i)
assertEquals(i, fromBytes.size)
assertContentEquals(fromString, fromBytes)
assertContentEquals(fromBytes, fromTypoAlias)
}
}
}
}
@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
}