diff --git a/src/commonMain/kotlin/com/infendro/random/csprng/HMAC-DRBG.kt b/src/commonMain/kotlin/com/infendro/random/csprng/HMAC-DRBG.kt index 485a6e1..02d0bb5 100644 --- a/src/commonMain/kotlin/com/infendro/random/csprng/HMAC-DRBG.kt +++ b/src/commonMain/kotlin/com/infendro/random/csprng/HMAC-DRBG.kt @@ -6,7 +6,7 @@ import com.infendro.mac.HMAC import com.infendro.random.CSPRNG import kotlin.properties.Delegates.notNull -class `HMAC-DRBG` internal constructor( +class `HMAC-DRBG`( private val function: HashFunction, ) : CSPRNG() { private val hmac = HMAC(function) @@ -14,6 +14,8 @@ class `HMAC-DRBG` internal constructor( private var k: ByteArray by notNull() private var v: ByteArray by notNull() + private val buffer = ByteArray(function.bytes + 1) + override fun seed(seed: ByteArray) { k = ByteArray(function.bytes) { 0x00 } v = ByteArray(function.bytes) { 0x01 } @@ -21,17 +23,28 @@ class `HMAC-DRBG` internal constructor( } override fun reseed(entropy: ByteArray) { - k = hmac.hash(k, v + byteArrayOf(0x00) + entropy) - v = hmac.hash(k, v) - k = hmac.hash(k, v + byteArrayOf(0x01) + entropy) - v = hmac.hash(k, v) + val value = ByteArray(v.size + 1 + entropy.size) + + v.copyInto(value) + value[v.size] = 0x00 + entropy.copyInto(value, v.size + 1) + hmac.hashInto(k, value, k) + hmac.hashInto(k, v, v) + + value[v.size] = 0x01 + hmac.hashInto(k, value, k) + hmac.hashInto(k, v, v) } override fun generate(): Int { - v = hmac.hash(k, v) + hmac.hashInto(k, v, v) val result = v.toInt() - k = hmac.hash(k, v + byteArrayOf(0x00)) - v = hmac.hash(k, v) + + v.copyInto(buffer) + buffer[v.size] = 0x00 + hmac.hashInto(k, buffer, k) + hmac.hashInto(k, v, v) + return result } } diff --git a/src/commonMain/kotlin/com/infendro/random/prng/LCG.kt b/src/commonMain/kotlin/com/infendro/random/prng/LCG.kt index 64e1bef..085e622 100644 --- a/src/commonMain/kotlin/com/infendro/random/prng/LCG.kt +++ b/src/commonMain/kotlin/com/infendro/random/prng/LCG.kt @@ -5,7 +5,7 @@ import com.infendro.hash.sha2.`SHA-256` import com.infendro.random.PRNG import kotlin.properties.Delegates.notNull -class LCG internal constructor() : PRNG() { +class LCG : PRNG() { private val a: Long = 25214903917L private val c: Long = 11L private val mask: Long = (1L shl 48) - 1