/* * 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 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 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) } } }